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

163 lines
5.1 KiB
TypeScript
Raw Normal View History

2024-10-01 20:48:03 -04:00
import { NextFunction, Request, Response } from "express";
import db from "@server/db";
import { hash } from "@node-rs/argon2";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
2024-10-14 19:30:38 -04:00
import { userActions, users } from "@server/db/schema";
2024-10-01 20:48:03 -04:00
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
import response from "@server/utils/response";
import { SqliteError } from "better-sqlite3";
2024-12-21 21:01:12 -05:00
import { sendEmailVerificationCode } from "../../auth/sendEmailVerificationCode";
2024-10-05 22:31:30 -04:00
import { passwordSchema } from "@server/auth/passwordSchema";
2024-10-07 23:31:23 -04:00
import { eq } from "drizzle-orm";
import moment from "moment";
2024-10-13 17:13:47 -04:00
import {
createSession,
generateId,
generateSessionToken,
serializeSessionCookie,
} from "@server/auth";
2024-10-14 19:30:38 -04:00
import { ActionsEnum } from "@server/auth/actions";
import config from "@server/config";
2024-12-21 21:01:12 -05:00
import logger from "@server/logger";
2024-12-22 16:59:30 -05:00
import { hashPassword } from "@server/auth/password";
2024-10-01 20:48:03 -04:00
export const signupBodySchema = z.object({
email: z.string().email(),
2024-10-05 15:11:51 -04:00
password: passwordSchema,
2024-10-01 20:48:03 -04:00
});
export type SignUpBody = z.infer<typeof signupBodySchema>;
2024-10-04 23:14:40 -04:00
export type SignUpResponse = {
emailVerificationRequired?: boolean;
2024-10-04 23:14:40 -04:00
};
export async function signup(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-10-01 20:48:03 -04:00
const parsedBody = signupBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
2024-10-01 20:48:03 -04:00
);
}
const { email, password } = parsedBody.data;
2024-12-22 16:59:30 -05:00
const passwordHash = await hashPassword(password);
2024-10-01 20:48:03 -04:00
const userId = generateId(15);
try {
2024-10-07 23:31:23 -04:00
const existing = await db
.select()
.from(users)
.where(eq(users.email, email));
if (existing && existing.length > 0) {
if (!config.flags?.require_email_verification) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"A user with that email address already exists"
)
);
}
2024-10-07 23:31:23 -04:00
const user = existing[0];
// If the user is already verified, we don't want to create a new user
if (user.emailVerified) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"A user with that email address already exists"
)
2024-10-07 23:31:23 -04:00
);
}
const dateCreated = moment(user.dateCreated);
const now = moment();
const diff = now.diff(dateCreated, "hours");
if (diff < 2) {
// If the user was created less than 2 hours ago, we don't want to create a new user
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"A verification email was already sent to this email address. Please check your email for the verification code."
)
2024-10-07 23:31:23 -04:00
);
} else {
// If the user was created more than 2 hours ago, we want to delete the old user and create a new one
2024-10-13 17:13:47 -04:00
await db.delete(users).where(eq(users.userId, user.userId));
2024-10-07 23:31:23 -04:00
}
}
2024-10-01 20:48:03 -04:00
await db.insert(users).values({
2024-10-13 17:13:47 -04:00
userId: userId,
2024-10-01 20:48:03 -04:00
email: email,
passwordHash,
2024-10-07 23:31:23 -04:00
dateCreated: moment().toISOString(),
2024-10-01 20:48:03 -04:00
});
// give the user their default permissions:
2024-10-14 19:30:38 -04:00
// await db.insert(userActions).values({
// userId: userId,
// actionId: ActionsEnum.createOrg,
// orgId: null,
// });
2024-10-13 17:13:47 -04:00
const token = generateSessionToken();
await createSession(token, userId);
const cookie = serializeSessionCookie(token);
res.appendHeader("Set-Cookie", cookie);
2024-10-01 20:48:03 -04:00
if (config.flags?.require_email_verification) {
sendEmailVerificationCode(email, userId);
return response<SignUpResponse>(res, {
data: {
emailVerificationRequired: true,
},
success: true,
error: false,
message: `User created successfully. We sent an email to ${email} with a verification code.`,
status: HttpCode.OK,
});
}
2024-10-04 23:14:40 -04:00
return response<SignUpResponse>(res, {
data: {},
success: true,
error: false,
message: "User created successfully",
status: HttpCode.OK,
});
2024-10-01 20:48:03 -04:00
} catch (e) {
if (e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_UNIQUE") {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"A user with that email address already exists"
)
2024-10-01 20:48:03 -04:00
);
} else {
2024-12-21 21:01:12 -05:00
logger.error(e);
2024-10-01 20:48:03 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create user"
)
2024-10-01 20:48:03 -04:00
);
}
}
}