fosrl.pangolin/server/routers/auth/login.ts

161 lines
4.5 KiB
TypeScript
Raw Normal View History

2024-10-01 20:48:03 -04:00
import { verify } from "@node-rs/argon2";
2024-10-13 17:13:47 -04:00
import {
createSession,
generateSessionToken,
serializeSessionCookie,
verifySession,
} from "@server/auth";
2024-10-01 20:48:03 -04:00
import db from "@server/db";
import { users } from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
import response from "@server/utils/response";
import { eq } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
2024-10-05 22:31:30 -04:00
import { verifyTotpCode } from "@server/auth/2fa";
import config from "@server/config";
import logger from "@server/logger";
2024-10-01 20:48:03 -04:00
export const loginBodySchema = z.object({
email: z.string().email(),
password: z.string(),
2024-10-02 20:19:48 -04:00
code: z.string().optional(),
2024-12-21 21:01:12 -05:00
}).strict();
2024-10-01 20:48:03 -04:00
2024-10-02 20:19:48 -04:00
export type LoginBody = z.infer<typeof loginBodySchema>;
export type LoginResponse = {
codeRequested?: boolean;
2024-10-04 23:14:40 -04:00
emailVerificationRequired?: boolean;
2024-10-02 20:19:48 -04:00
};
export async function login(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-01 20:48:03 -04:00
const parsedBody = loginBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
2024-10-01 20:48:03 -04:00
);
}
2024-10-02 20:19:48 -04:00
const { email, password, code } = parsedBody.data;
2024-10-01 20:48:03 -04:00
2024-10-04 23:14:40 -04:00
try {
const { session: existingSession } = await verifySession(req);
if (existingSession) {
return response<null>(res, {
data: null,
success: true,
error: false,
2024-10-04 23:14:40 -04:00
message: "Already logged in",
status: HttpCode.OK,
});
2024-10-02 20:19:48 -04:00
}
2024-10-04 23:14:40 -04:00
const existingUserRes = await db
.select()
.from(users)
.where(eq(users.email, email));
if (!existingUserRes || !existingUserRes.length) {
2024-10-02 20:19:48 -04:00
return next(
createHttpError(
2024-10-04 23:14:40 -04:00
HttpCode.BAD_REQUEST,
"Username or password is incorrect"
)
2024-10-02 20:19:48 -04:00
);
}
2024-10-04 23:14:40 -04:00
const existingUser = existingUserRes[0];
const validPassword = await verify(
existingUser.passwordHash,
password,
{
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
}
2024-10-02 20:19:48 -04:00
);
2024-10-04 23:14:40 -04:00
if (!validPassword) {
2024-10-02 20:19:48 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Username or password is incorrect"
)
2024-10-02 20:19:48 -04:00
);
}
2024-10-04 23:14:40 -04:00
if (existingUser.twoFactorEnabled) {
if (!code) {
return response<{ codeRequested: boolean }>(res, {
data: { codeRequested: true },
success: true,
error: false,
message: "Two-factor authentication required",
status: HttpCode.ACCEPTED,
});
}
2024-10-05 15:11:51 -04:00
const validOTP = await verifyTotpCode(
2024-10-04 23:14:40 -04:00
code,
2024-10-05 15:11:51 -04:00
existingUser.twoFactorSecret!,
existingUser.userId
2024-10-04 23:14:40 -04:00
);
if (!validOTP) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"The two-factor code you entered is incorrect"
)
2024-10-04 23:14:40 -04:00
);
}
}
2024-10-13 17:13:47 -04:00
const token = generateSessionToken();
await createSession(token, existingUser.userId);
const cookie = serializeSessionCookie(token);
2024-10-12 21:23:12 -04:00
2024-10-13 17:13:47 -04:00
res.appendHeader("Set-Cookie", cookie);
2024-10-04 23:14:40 -04:00
if (
!existingUser.emailVerified &&
config.flags?.require_email_verification
) {
2024-10-04 23:14:40 -04:00
return response<LoginResponse>(res, {
data: { emailVerificationRequired: true },
success: true,
error: false,
message: "Email verification code sent",
2024-11-28 00:11:13 -05:00
status: HttpCode.OK,
2024-10-04 23:14:40 -04:00
});
}
return response<null>(res, {
data: null,
success: true,
error: false,
message: "Logged in successfully",
status: HttpCode.OK,
});
} catch (e) {
2024-12-21 21:01:12 -05:00
logger.error(e);
2024-10-04 23:14:40 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to authenticate user"
)
2024-10-04 23:14:40 -04:00
);
}
2024-10-01 20:48:03 -04:00
}