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

227 lines
7.2 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 HttpCode from "@server/types/HttpCode";
import { z } from "zod";
2025-01-01 21:41:31 -05:00
import { users } from "@server/db/schema";
2024-10-01 20:48:03 -04:00
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
2025-01-01 21:41:31 -05:00
import response from "@server/lib/response";
2024-10-01 20:48:03 -04:00
import { SqliteError } from "better-sqlite3";
2024-12-21 21:01:12 -05:00
import { sendEmailVerificationCode } from "../../auth/sendEmailVerificationCode";
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,
2024-12-25 15:54:32 -05:00
serializeSessionCookie
2025-01-01 21:41:31 -05:00
} from "@server/auth/sessions/app";
import config from "@server/lib/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-12-25 15:54:32 -05:00
import { checkValidInvite } from "@server/auth/checkValidInvite";
2025-01-01 21:41:31 -05:00
import { passwordSchema } from "@server/auth/passwordSchema";
2024-10-01 20:48:03 -04:00
export const signupBodySchema = z.object({
2025-01-27 22:43:32 -05:00
email: z
.string()
.email()
.transform((v) => v.toLowerCase()),
2024-10-05 15:11:51 -04:00
password: passwordSchema,
2024-12-25 15:54:32 -05:00
inviteToken: z.string().optional(),
inviteId: z.string().optional()
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
);
}
2024-12-25 15:54:32 -05:00
const { email, password, inviteToken, inviteId } = parsedBody.data;
logger.debug("signup", { email, password, inviteToken, inviteId });
2024-10-01 20:48:03 -04:00
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);
if (config.getRawConfig().flags?.disable_signup_without_invite) {
2024-12-25 15:54:32 -05:00
if (!inviteToken || !inviteId) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Signup blocked without invite. Email: ${email}. IP: ${req.ip}.`
);
}
2024-12-25 15:54:32 -05:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Signups are disabled without an invite code"
)
);
}
const { error, existingInvite } = await checkValidInvite({
token: inviteToken,
inviteId
});
if (error) {
return next(createHttpError(HttpCode.BAD_REQUEST, error));
}
if (!existingInvite) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Invite does not exist")
);
}
if (existingInvite.email !== email) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`User attempted to use an invite for another user. Email: ${email}. IP: ${req.ip}.`
);
}
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invite is not for this user"
)
);
}
2024-12-25 15:54:32 -05:00
}
2024-10-01 20:48:03 -04:00
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.getRawConfig().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
2024-12-25 15:54:32 -05:00
return response<SignUpResponse>(res, {
data: {
emailVerificationRequired: true
},
success: true,
error: false,
message: `A user with that email address already exists. We sent an email to ${email} with a verification code.`,
status: HttpCode.OK
});
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-12-25 15:54:32 -05: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();
const sess = await createSession(token, userId);
const isSecure = req.protocol === "https";
const cookie = serializeSessionCookie(
token,
isSecure,
new Date(sess.expiresAt)
);
2024-10-13 17:13:47 -04:00
res.appendHeader("Set-Cookie", cookie);
2024-10-01 20:48:03 -04:00
if (config.getRawConfig().flags?.require_email_verification) {
sendEmailVerificationCode(email, userId);
return response<SignUpResponse>(res, {
data: {
2024-12-25 15:54:32 -05:00
emailVerificationRequired: true
},
success: true,
error: false,
message: `User created successfully. We sent an email to ${email} with a verification code.`,
2024-12-25 15:54:32 -05:00
status: HttpCode.OK
});
}
2024-10-04 23:14:40 -04:00
return response<SignUpResponse>(res, {
data: {},
success: true,
error: false,
message: "User created successfully",
2024-12-25 15:54:32 -05:00
status: HttpCode.OK
});
2024-10-01 20:48:03 -04:00
} catch (e) {
if (e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_UNIQUE") {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Account already exists with that email. Email: ${email}. IP: ${req.ip}.`
);
}
2024-10-01 20:48:03 -04:00
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
);
}
}
}