2024-02-08 01:16:17 +00:00
|
|
|
import db from "$lib/drizzle";
|
|
|
|
|
import { eq } from "drizzle-orm";
|
|
|
|
|
import { roles, user_roles } from "../schema";
|
2023-06-16 06:28:49 +00:00
|
|
|
|
2023-06-20 18:54:47 +00:00
|
|
|
export async function add_user_to_role(user_id: string, role_name: string) {
|
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-02-08 01:16:17 +00:00
|
|
|
const userRole = await db.insert(user_roles).values({
|
|
|
|
|
user_id,
|
|
|
|
|
role_id: role.id
|
2023-06-16 06:28:49 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return userRole;
|
|
|
|
|
}
|