documenso/packages/lib/server-only/user/create-user.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-03-07 07:30:22 +00:00
import { hash } from '@node-rs/bcrypt';
2025-02-13 09:21:23 +00:00
import type { User } from '@prisma/client';
2023-06-09 08:21:18 +00:00
import { prisma } from '@documenso/prisma';
import { SALT_ROUNDS } from '../../constants/auth';
2024-02-29 02:22:21 +00:00
import { AppError, AppErrorCode } from '../../errors/app-error';
2025-06-10 01:49:52 +00:00
import { createPersonalOrganisation } from '../organisation/create-organisation';
2023-06-09 08:21:18 +00:00
export interface CreateUserOptions {
name: string;
email: string;
password: string;
2023-09-01 09:46:44 +00:00
signature?: string | null;
2023-06-09 08:21:18 +00:00
}
2025-06-10 01:49:52 +00:00
export const createUser = async ({ name, email, password, signature }: CreateUserOptions) => {
2023-06-09 08:21:18 +00:00
const hashedPassword = await hash(password, SALT_ROUNDS);
const userExists = await prisma.user.findFirst({
where: {
email: email.toLowerCase(),
},
});
if (userExists) {
2024-12-06 07:01:24 +00:00
throw new AppError(AppErrorCode.ALREADY_EXISTS);
2023-06-09 08:21:18 +00:00
}
2025-01-02 04:33:37 +00:00
const user = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({
data: {
name,
email: email.toLowerCase(),
2025-02-19 05:07:04 +00:00
password: hashedPassword, // Todo: (RR7) Drop password.
2025-01-02 04:33:37 +00:00
signature,
},
});
2025-02-19 05:07:04 +00:00
// Todo: (RR7) Migrate to use this after RR7.
2025-02-14 08:22:11 +00:00
// await tx.account.create({
// data: {
// userId: user.id,
2025-02-19 05:07:04 +00:00
// type: 'emailPassword', // Todo: (RR7)
// provider: 'DOCUMENSO', // Todo: (RR7) Enums
2025-02-14 08:22:11 +00:00
// providerAccountId: user.id.toString(),
// password: hashedPassword,
// },
// });
2025-01-02 04:33:37 +00:00
return user;
2023-06-09 08:21:18 +00:00
});
2025-06-10 01:49:52 +00:00
// Not used at the moment, uncomment if required.
2025-02-13 09:21:23 +00:00
await onCreateUserHook(user).catch((err) => {
2025-02-19 05:07:04 +00:00
// Todo: (RR7) Add logging.
2025-02-13 09:21:23 +00:00
console.error(err);
});
return user;
};
/**
2025-06-10 01:49:52 +00:00
* Should be run after a user is created, example during email password signup or google sign in.
2025-02-13 09:21:23 +00:00
*
* @returns User
*/
export const onCreateUserHook = async (user: User) => {
2025-06-10 01:49:52 +00:00
await createPersonalOrganisation({ userId: user.id });
return user;
2023-06-09 08:21:18 +00:00
};