2024-08-10 17:03:30 +00:00
|
|
|
import {inject, injectable} from "tsyringe";
|
|
|
|
|
import {type CreateUserRole, UserRolesRepository} from "$lib/server/api/repositories/user_roles.repository";
|
|
|
|
|
import db from "$db";
|
|
|
|
|
import {RolesService} from "$lib/server/api/services/roles.service";
|
2024-08-13 22:19:57 +00:00
|
|
|
import { user_roles } from "../infrastructure/database/tables";
|
2024-08-10 17:03:30 +00:00
|
|
|
|
|
|
|
|
@injectable()
|
|
|
|
|
export class UserRolesService {
|
|
|
|
|
constructor(
|
|
|
|
|
@inject(UserRolesRepository) private readonly userRolesRepository: UserRolesRepository,
|
|
|
|
|
@inject(RolesService) private readonly rolesService: RolesService
|
|
|
|
|
) { }
|
|
|
|
|
|
|
|
|
|
async findOneById(id: string) {
|
|
|
|
|
return this.userRolesRepository.findOneById(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async findAllByUserId(userId: string) {
|
|
|
|
|
return this.userRolesRepository.findAllByUserId(userId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async create(data: CreateUserRole) {
|
|
|
|
|
return this.userRolesRepository.create(data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async addRoleToUser(userId: string, roleName: string, primary = false) {
|
|
|
|
|
// Find the role by its name
|
|
|
|
|
const role = await this.rolesService.findOneByNameOrThrow(roleName);
|
|
|
|
|
|
|
|
|
|
if (!role || !role.id) {
|
|
|
|
|
throw new Error(`Role with name ${roleName} not found`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a UserRole entry linking the user and the role
|
2024-08-13 22:19:57 +00:00
|
|
|
return db.insert(user_roles).values({
|
2024-08-10 17:03:30 +00:00
|
|
|
user_id: userId,
|
|
|
|
|
role_id: role.id,
|
|
|
|
|
primary,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|