2023-09-02 12:13:50 +00:00
|
|
|
import { prisma } from './_client';
|
|
|
|
import bcryptjs from 'bcryptjs';
|
2023-09-02 19:49:20 +00:00
|
|
|
import { ROLES } from '../utils/const';
|
2023-09-02 12:13:50 +00:00
|
|
|
|
|
|
|
async function hashPassword(password: string) {
|
|
|
|
return await bcryptjs.hash(password, 10);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create User
|
|
|
|
*/
|
|
|
|
export async function createAdminUser(username: string, password: string) {
|
|
|
|
const count = await prisma.user.count();
|
|
|
|
|
|
|
|
if (count > 0) {
|
|
|
|
throw new Error('Create Admin User Just Only allow in non people exist');
|
|
|
|
}
|
|
|
|
|
|
|
|
await prisma.user.create({
|
|
|
|
data: {
|
|
|
|
username,
|
|
|
|
password: await hashPassword(password),
|
2023-09-02 19:49:20 +00:00
|
|
|
role: ROLES.admin,
|
|
|
|
workspaces: {
|
|
|
|
create: [
|
|
|
|
{
|
|
|
|
role: ROLES.owner,
|
|
|
|
workspace: {
|
|
|
|
create: {
|
|
|
|
name: username,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
},
|
2023-09-02 12:13:50 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function createUser(username: string, password: string) {
|
2023-09-02 19:49:20 +00:00
|
|
|
const existCount = await prisma.user.count({
|
|
|
|
where: {
|
|
|
|
username,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (existCount > 0) {
|
|
|
|
throw new Error('User already exists');
|
|
|
|
}
|
|
|
|
|
2023-09-02 12:13:50 +00:00
|
|
|
await prisma.user.create({
|
|
|
|
data: {
|
|
|
|
username,
|
|
|
|
password: await hashPassword(password),
|
2023-09-02 19:49:20 +00:00
|
|
|
role: ROLES.user,
|
|
|
|
workspaces: {
|
|
|
|
create: [
|
|
|
|
{
|
|
|
|
role: ROLES.owner,
|
|
|
|
workspace: {
|
|
|
|
create: {
|
|
|
|
name: username,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
},
|
2023-09-02 12:13:50 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function authUser(username: string, password: string) {
|
|
|
|
const user = await prisma.user.findFirstOrThrow({
|
|
|
|
where: {
|
|
|
|
username,
|
|
|
|
password: await hashPassword(password),
|
|
|
|
},
|
2023-09-02 19:49:20 +00:00
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
username: true,
|
|
|
|
role: true,
|
|
|
|
createdAt: true,
|
|
|
|
updatedAt: true,
|
|
|
|
deletedAt: true,
|
|
|
|
},
|
2023-09-02 12:13:50 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|
2023-09-02 17:01:55 +00:00
|
|
|
|
|
|
|
export async function findUser(userId: string) {
|
|
|
|
const user = await prisma.user.findFirst({
|
|
|
|
where: {
|
|
|
|
id: userId,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
username: true,
|
|
|
|
role: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|