import mongoose from "mongoose";
import jwt from "jsonwebtoken";
import { User } from "@models/user";
import { log } from "@server/logger";
export default eventHandler(async (event) => {
const wrongMsg = "wrong credentials";
let reqbody = await readBody(event);
let user = await User.findOne({ username: reqbody.username }).exec();
// log.debug(reqbody, { label: "login/body" });
// log.debug("USER -> " + user, { label: "login" });
// log.debug("conn ->" + mongoose.connection, { label: "login" });
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,
message: 'Account inactive!
Resend verification?',
});
}
let tok = user.generateRefreshToken(useRuntimeConfig().jwt);
// setCookie(event, "rockfic_cookie", tok);
return {
user,
token: {
refresh: tok,
access: user.generateAccessToken(useRuntimeConfig().jwt),
},
};
} 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 });
}
}
});