| import { EVENTS, ERROR_CODE, defineAbilityFor } from '@music-together/shared' |
| import type { Actions, Subjects, UserRole } from '@music-together/shared' |
| import type { HandlerContext, TypedServer } from './types.js' |
| import { createWithRoom } from './withRoom.js' |
| import { userRepo } from '../repositories/userRepository.js' |
|
|
| |
| export function defineAbilityForRoomUser(userId: string, roomRole: UserRole) { |
| return defineAbilityFor(userRepo.isServerAdmin(userId) ? 'owner' : roomRole) |
| } |
|
|
| |
| |
| |
| |
| export function createWithPermission(io: TypedServer) { |
| const withRoom = createWithRoom(io) |
|
|
| return function withPermission<T = void>( |
| action: Actions, |
| subject: Subjects, |
| handler: (ctx: HandlerContext, data: T) => void | Promise<void>, |
| ) { |
| return withRoom<T>((ctx, data) => { |
| const ability = defineAbilityForRoomUser(ctx.user.id, ctx.user.role) |
| if (!ability.can(action, subject)) { |
| ctx.socket.emit(EVENTS.ROOM_ERROR, { |
| code: ERROR_CODE.NO_PERMISSION, |
| message: '你没有权限执行此操作', |
| }) |
| return |
| } |
| return handler(ctx, data) |
| }) |
| } |
| } |
|
|
| |
| |
| |
| |
| export function createWithOwnerOnly(io: TypedServer) { |
| const withRoom = createWithRoom(io) |
|
|
| return function withOwnerOnly<T = void>(handler: (ctx: HandlerContext, data: T) => void | Promise<void>) { |
| return withRoom<T>((ctx, data) => { |
| if (ctx.user.role !== 'owner' && !userRepo.isServerAdmin(ctx.user.id)) { |
| ctx.socket.emit(EVENTS.ROOM_ERROR, { |
| code: ERROR_CODE.NO_PERMISSION, |
| message: '只有房主可以操作', |
| }) |
| return |
| } |
| return handler(ctx, data) |
| }) |
| } |
| } |
|
|