create invite and accept invite endpoints

This commit is contained in:
Milo Schwartz 2024-11-02 18:12:17 -04:00
parent a83a3e88bb
commit a6bb8f5bb1
No known key found for this signature in database
7 changed files with 333 additions and 48 deletions

View file

@ -0,0 +1,124 @@
import { verify } from "@node-rs/argon2";
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { roles, userInvites, userOrgs, users } from "@server/db/schema";
import { 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 { fromError } from "zod-validation-error";
const acceptInviteBodySchema = z.object({
token: z.string(),
inviteId: z.string(),
});
export type AcceptInviteResponse = {};
export async function acceptInvite(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = acceptInviteBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { token, inviteId } = parsedBody.data;
const existingInvite = await db
.select()
.from(userInvites)
.where(eq(userInvites.inviteId, inviteId))
.limit(1);
if (!existingInvite.length) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invite ID or token is invalid"
)
);
}
const validToken = await verify(existingInvite[0].tokenHash, token, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
if (!validToken) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invite ID or token is invalid"
)
);
}
const existingUser = await db
.select()
.from(users)
.where(eq(users.email, existingInvite[0].email))
.limit(1);
if (!existingUser.length) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User does not exist. Please create an account first."
)
);
}
let roleId: number;
// get the role to make sure it exists
const existingRole = await db
.select()
.from(roles)
.where(eq(roles.roleId, existingInvite[0].roleId))
.limit(1);
if (existingRole.length) {
roleId = existingRole[0].roleId;
} else {
// TODO: use the default role on the org instead of failing
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Role does not exist. Please contact an admin."
)
);
}
// add the user to the org
await db.insert(userOrgs).values({
userId: existingUser[0].userId,
orgId: existingInvite[0].orgId,
roleId: existingInvite[0].roleId,
});
// delete the invite
await db.delete(userInvites).where(eq(userInvites.inviteId, inviteId));
return response<AcceptInviteResponse>(res, {
data: {},
success: true,
error: false,
message: "Invite accepted",
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -3,3 +3,5 @@ export * from "./removeUserOrg";
export * from "./addUserOrg";
export * from "./listUsers";
export * from "./setUserRole";
export * from "./inviteUser";
export * from "./acceptInvite";

View file

@ -0,0 +1,133 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { 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 { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
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";
const inviteUserParamsSchema = z.object({
orgId: z.string(),
});
const inviteUserBodySchema = z.object({
email: z.string().email(),
roleId: z.number(),
validHours: z.number().gt(0).lte(168),
});
export type InviteUserResponse = {
inviteLink: string;
expiresAt: number;
};
export async function inviteUser(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = inviteUserParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = inviteUserBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const { email, validHours, roleId } = parsedBody.data;
const hasPermission = await checkUserActionPermission(
ActionsEnum.inviteUser,
req
);
if (!hasPermission) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action"
)
);
}
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,
"User is already a member of this organization"
)
);
}
const inviteId = generateRandomString(
10,
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(
and(eq(userInvites.email, email), eq(userInvites.orgId, orgId))
)
.execute();
await db.insert(userInvites).values({
inviteId,
orgId,
email,
expiresAt,
tokenHash,
roleId,
});
const inviteLink = `${config.app.base_url}/invite/${inviteId}-${token}`;
return response<InviteUserResponse>(res, {
data: {
inviteLink,
expiresAt,
},
success: true,
error: false,
message: "User invited successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}