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

180 lines
5.3 KiB
TypeScript
Raw Normal View History

2024-10-13 17:13:47 -04:00
import {
createSession,
generateSessionToken,
2025-01-01 21:41:31 -05:00
serializeSessionCookie
} from "@server/auth/sessions/app";
2024-10-01 20:48:03 -04:00
import db from "@server/db";
2025-03-23 17:11:48 -04:00
import { users } from "@server/db/schemas";
2024-10-01 20:48:03 -04:00
import HttpCode from "@server/types/HttpCode";
2025-01-01 21:41:31 -05:00
import response from "@server/lib/response";
2024-10-01 20:48:03 -04:00
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";
2025-01-01 21:41:31 -05:00
import { verifyTotpCode } from "@server/auth/totp";
import config from "@server/lib/config";
import logger from "@server/logger";
2024-12-22 16:59:30 -05:00
import { verifyPassword } from "@server/auth/password";
2025-01-01 21:41:31 -05:00
import { verifySession } from "@server/auth/sessions/verifySession";
2024-10-01 20:48:03 -04:00
2024-12-22 16:59:30 -05:00
export const loginBodySchema = z
.object({
2025-01-21 18:36:50 -05:00
email: z
.string()
.email()
.transform((v) => v.toLowerCase()),
2024-12-22 16:59:30 -05:00
password: z.string(),
code: z.string().optional()
})
.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",
2024-12-22 16:59:30 -05:00
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) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-10-02 20:19:48 -04:00
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"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];
2024-12-22 16:59:30 -05:00
const validPassword = await verifyPassword(
2024-10-04 23:14:40 -04:00
password,
2024-12-22 16:59:30 -05:00
existingUser.passwordHash
2024-10-02 20:19:48 -04:00
);
2024-10-04 23:14:40 -04:00
if (!validPassword) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Username or password incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-10-02 20:19:48 -04:00
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"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",
2024-12-22 16:59:30 -05:00
status: HttpCode.ACCEPTED
2024-10-04 23:14:40 -04:00
});
}
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) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Two-factor code incorrect. Email: ${email}. IP: ${req.ip}.`
);
}
2024-10-04 23:14:40 -04:00
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"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();
const sess = await createSession(token, existingUser.userId);
const isSecure = req.protocol === "https";
const cookie = serializeSessionCookie(
token,
isSecure,
new Date(sess.expiresAt)
);
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.getRawConfig().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-12-22 16:59:30 -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",
2024-12-22 16:59:30 -05:00
status: HttpCode.OK
2024-10-04 23:14:40 -04:00
});
} 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
}