2023-09-28 21:55:19 -04:00
|
|
|
import mongoose from "mongoose";
|
|
|
|
import jwt from "jsonwebtoken";
|
2023-12-29 20:11:07 -05:00
|
|
|
import { User } from "@models/user";
|
2023-12-20 17:23:31 -05:00
|
|
|
import { log } from "@server/logger";
|
2023-09-28 21:55:19 -04:00
|
|
|
|
|
|
|
export default eventHandler(async (event) => {
|
|
|
|
const wrongMsg = "wrong credentials";
|
|
|
|
let reqbody = await readBody(event);
|
|
|
|
let user = await User.findOne({ username: reqbody.username }).exec();
|
2024-03-16 21:16:43 -04:00
|
|
|
// log.debug(reqbody, { label: "login/body" });
|
|
|
|
// log.debug("USER -> " + user, { label: "login" });
|
|
|
|
// log.debug("conn ->" + mongoose.connection, { label: "login" });
|
2023-09-28 21:55:19 -04:00
|
|
|
let cok = getHeader(event, "Authorization")?.replace("Bearer ", "");
|
|
|
|
if (!cok) {
|
|
|
|
if (!user) {
|
|
|
|
throw createError({ statusCode: 401, message: wrongMsg });
|
|
|
|
}
|
|
|
|
if (user.banned) {
|
|
|
|
throw createError({
|
|
|
|
statusCode: 401,
|
|
|
|
message: "This account has been banned.",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (user.validPassword(reqbody.password)) {
|
|
|
|
if (!user.auth.emailVerified) {
|
|
|
|
throw createError({
|
|
|
|
statusCode: 401,
|
2023-12-29 20:11:07 -05:00
|
|
|
message: 'Account inactive!<br><a href="/activate/resend">Resend verification</a>?',
|
2023-09-28 21:55:19 -04:00
|
|
|
});
|
|
|
|
}
|
2023-12-28 03:21:09 -05:00
|
|
|
let tok = user.generateJWT(useRuntimeConfig().jwt);
|
2023-09-28 21:55:19 -04:00
|
|
|
// setCookie(event, "rockfic_cookie", tok);
|
|
|
|
return {
|
|
|
|
user,
|
|
|
|
token: tok,
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
throw createError({ statusCode: 401, message: wrongMsg });
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (jwt.verify(cok, useRuntimeConfig().jwt)) {
|
|
|
|
throw createError({
|
|
|
|
statusCode: 405,
|
|
|
|
message: "Already logged in.",
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
throw createError({ statusCode: 401, message: wrongMsg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|