fosrl.pangolin/server/routers/user/inviteUser.ts

186 lines
5.5 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
2024-11-03 17:28:12 -05:00
import { orgs, userInvites, userOrgs, users } from "@server/db/schema";
import { and, eq } from "drizzle-orm";
import response from "@server/utils/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { alphabet, generateRandomString } from "oslo/crypto";
import { createDate, TimeSpan } from "oslo";
import config from "@server/config";
import { hashPassword } from "@server/auth/password";
import { fromError } from "zod-validation-error";
2024-11-03 17:28:12 -05:00
import { sendEmail } from "@server/emails";
import SendInviteLink from "@server/emails/templates/SendInviteLink";
2024-12-21 21:01:12 -05:00
const inviteUserParamsSchema = z
.object({
orgId: z.string()
})
.strict();
const inviteUserBodySchema = z
.object({
email: z.string().email(),
roleId: z.number(),
validHours: z.number().gt(0).lte(168),
sendEmail: z.boolean().optional()
})
.strict();
2024-11-02 23:46:08 -04:00
export type InviteUserBody = z.infer<typeof inviteUserBodySchema>;
export type InviteUserResponse = {
inviteLink: string;
expiresAt: number;
};
2024-11-03 17:28:12 -05:00
const inviteTracker: Record<string, { timestamps: number[] }> = {};
export async function inviteUser(
req: Request,
res: Response,
2024-12-21 21:01:12 -05:00
next: NextFunction
): Promise<any> {
try {
const parsedParams = inviteUserParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = inviteUserBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
2024-12-21 21:01:12 -05:00
const {
email,
validHours,
roleId,
sendEmail: doEmail
} = parsedBody.data;
2024-11-03 17:28:12 -05:00
const currentTime = Date.now();
const oneHourAgo = currentTime - 3600000;
if (!inviteTracker[email]) {
inviteTracker[email] = { timestamps: [] };
}
inviteTracker[email].timestamps = inviteTracker[
email
].timestamps.filter((timestamp) => timestamp > oneHourAgo); // TODO: this could cause memory increase over time if the object is never deleted
2024-11-03 17:28:12 -05:00
if (inviteTracker[email].timestamps.length >= 3) {
return next(
createHttpError(
HttpCode.TOO_MANY_REQUESTS,
2024-12-21 21:01:12 -05:00
"User has already been invited 3 times in the last hour"
)
2024-11-03 17:28:12 -05:00
);
}
inviteTracker[email].timestamps.push(currentTime);
const org = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, orgId))
.limit(1);
if (!org.length) {
return next(
2024-12-21 21:01:12 -05:00
createHttpError(HttpCode.NOT_FOUND, "Organization not found")
2024-11-03 17:28:12 -05:00
);
}
const existingUser = await db
.select()
.from(users)
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
.where(eq(users.email, email))
.limit(1);
if (existingUser.length && existingUser[0].userOrgs?.orgId === orgId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-21 21:01:12 -05:00
"User is already a member of this organization"
)
);
}
const inviteId = generateRandomString(
10,
2024-12-21 21:01:12 -05:00
alphabet("a-z", "A-Z", "0-9")
);
const token = generateRandomString(32, alphabet("a-z", "A-Z", "0-9"));
const expiresAt = createDate(new TimeSpan(validHours, "h")).getTime();
const tokenHash = await hashPassword(token);
// delete any existing invites for this email
await db
.delete(userInvites)
.where(
2024-12-21 21:01:12 -05:00
and(eq(userInvites.email, email), eq(userInvites.orgId, orgId))
)
.execute();
await db.insert(userInvites).values({
inviteId,
orgId,
email,
expiresAt,
tokenHash,
2024-12-21 21:01:12 -05:00
roleId
});
2024-11-02 23:46:08 -04:00
const inviteLink = `${config.app.base_url}/invite?token=${inviteId}-${token}`;
2024-12-21 21:01:12 -05:00
if (doEmail) {
await sendEmail(
SendInviteLink({
email,
inviteLink,
expiresInDays: (validHours / 24).toString(),
orgName: org[0].name || orgId,
inviterName: req.user?.email
}),
{
to: email,
from: config.email?.no_reply,
subject: "You're invited to join a Fossorial organization"
}
);
}
2024-11-25 23:07:21 -05:00
return response<InviteUserResponse>(res, {
data: {
inviteLink,
2024-12-21 21:01:12 -05:00
expiresAt
},
success: true,
error: false,
message: "User invited successfully",
2024-12-21 21:01:12 -05:00
status: HttpCode.OK
});
} catch (error) {
2024-12-21 21:01:12 -05:00
logger.error(error);
return next(
2024-12-21 21:01:12 -05:00
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}