2024-03-20 03:37:01 +00:00
|
|
|
import { eq } from 'drizzle-orm';
|
2024-03-21 19:27:32 +00:00
|
|
|
import db from '$lib/drizzle';
|
2024-03-20 03:37:01 +00:00
|
|
|
import { roles, user_roles } from '../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({
|
|
|
|
|
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-03-21 19:27:32 +00:00
|
|
|
return db.insert(user_roles).values({
|
2024-02-08 01:16:17 +00:00
|
|
|
user_id,
|
2024-03-20 03:37:01 +00:00
|
|
|
role_id: role.id,
|
|
|
|
|
primary
|
2023-06-16 06:28:49 +00:00
|
|
|
});
|
|
|
|
|
}
|