This commit is contained in:
dahyeon committed 2026-04-24 13:40:39 -07:00
1 parent a197185ad0
commit 30dfb7ce58
27 files changed
+1584 -45

No files matched your search

@@ -0,0 +1,21 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
import { UserDocument } from '../global/database/schema';
import { AuthService } from './auth.service';
declare module 'express' {
interface Request {
user?: UserDocument;
}
}
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private readonly authService: AuthService) {}
public async use(req: Request, _res: Response, next: NextFunction) {
const user = await this.authService.resolveUserFromRequest(req);
if (user) req.user = user;
next();
}
}
+15
View File
@@ -0,0 +1,15 @@
import { Global, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AuthMiddleware } from './auth.middleware';
import { AuthService } from './auth.service';
import { RolesGuard } from './roles.guard';
@Global()
@Module({
providers: [AuthService, RolesGuard],
exports: [AuthService, RolesGuard],
})
export class AuthModule implements NestModule {
public configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('*');
}
}
+23
View File
@@ -0,0 +1,23 @@
import { Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { UserDocument } from '../global/database/schema';
@Injectable()
export class AuthService {
constructor(private readonly connectionService: ConnectionService) {}
// 로그인/세션 구현 전까지는 `X-Auth-User-Id` 헤더로 유저를 식별.
// OAuth 도입 시 이 메서드만 교체하면 됨.
public async resolveUserFromRequest(
req: Request,
): Promise<UserDocument | null> {
const header = req.headers['x-auth-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
if (!userId || !mongoose.isValidObjectId(userId)) return null;
const UserModel = await this.connectionService.getModel('user');
return UserModel.findById(userId).exec();
}
}
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { UserDocument } from '../global/database/schema';
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
const req = ctx.switchToHttp().getRequest<{ user?: UserDocument }>();
return req.user;
},
);
+35
View File
@@ -0,0 +1,35 @@
import { CommunityRole } from '../global/database/schema';
export type Permission =
| 'community:edit'
| 'community:delete'
| 'community:transfer'
| 'user:role:manage'
| 'match:create'
| 'match:edit'
| 'match:delete'
| 'auction:manage';
type PermissionSet = readonly Permission[] | readonly ['*'];
export const ROLE_PERMISSIONS: Record<CommunityRole, PermissionSet> = {
owner: ['*'] as const,
admin: [
'community:edit',
'user:role:manage',
'match:create',
'match:edit',
'match:delete',
'auction:manage',
] as const,
member: [] as const,
};
export function roleHasPermission(
role: CommunityRole,
permission: Permission,
): boolean {
const perms = ROLE_PERMISSIONS[role];
if (perms.length === 1 && perms[0] === '*') return true;
return (perms as readonly Permission[]).includes(permission);
}
@@ -0,0 +1,7 @@
import { SetMetadata } from '@nestjs/common';
import { CommunityRole } from '../global/database/schema';
export const ROLES_KEY = 'lolympus:roles';
export const Roles = (...roles: CommunityRole[]) =>
SetMetadata(ROLES_KEY, roles);
+32
View File
@@ -0,0 +1,32 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
public canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<CommunityRole[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined;
if (!user) throw new UnauthorizedException('Authentication required.');
if (!requiredRoles.includes(user.role)) {
throw new ForbiddenException('Insufficient role.');
}
return true;
}
}