2024-03-20 03:37:01 +00:00
|
|
|
import { eq } from 'drizzle-orm';
|
2024-05-08 00:19:13 +00:00
|
|
|
import db from '../db';
|
2024-07-12 22:37:05 +00:00
|
|
|
import { roles, userRoles } from '$db/schema';
|
2023-06-16 06:28:49 +00:00
|
|
|
|
2024-03-20 03:37:01 +00:00
|
|
|
export async function add_user_to_role(user_id: string, role_name: string, primary = false) {
|
2023-06-16 06:28:49 +00:00
|
|
|
// Find the role by its name
|
2024-02-08 01:16:17 +00:00
|
|
|
const role = await db.query.roles.findFirst({
|
2024-05-08 00:19:13 +00:00
|
|
|
where: eq(roles.name, role_name),
|
2023-06-16 06:28:49 +00:00
|
|
|
});
|
|
|
|
|
|
2024-02-08 01:16:17 +00:00
|
|
|
if (!role || !role.id) {
|
2023-06-20 18:54:47 +00:00
|
|
|
throw new Error(`Role with name ${role_name} not found`);
|
2023-06-16 06:28:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a UserRole entry linking the user and the role
|
2024-07-12 22:37:05 +00:00
|
|
|
return db.insert(userRoles).values({
|
2024-02-08 01:16:17 +00:00
|
|
|
user_id,
|
2024-03-20 03:37:01 +00:00
|
|
|
role_id: role.id,
|
2024-05-08 00:19:13 +00:00
|
|
|
primary,
|
2023-06-16 06:28:49 +00:00
|
|
|
});
|
|
|
|
|
}
|