forked from mtusi2026/mtusi2026lab2
feat: add basic auth
This commit is contained in:
@@ -1,26 +0,0 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { PrismaService } from '../../db/prisma.service';
|
||||
import { toUser } from '../../users/users.service';
|
||||
import { ApiError } from '../filters/api-error';
|
||||
import { validate as isUuid } from '../uuid';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const header = request.headers['x-user-id'];
|
||||
const userId = Array.isArray(header) ? header[0] : header;
|
||||
if (!userId || !isUuid(userId)) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
const row = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!row) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
request.currentUser = toUser(row);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from '../domain';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
}
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): User => {
|
||||
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
|
||||
if (!request.currentUser) {
|
||||
throw new Error('CurrentUser used without AuthGuard');
|
||||
}
|
||||
return request.currentUser;
|
||||
},
|
||||
);
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthGuard } from './auth/auth.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuthGuard],
|
||||
exports: [AuthGuard],
|
||||
})
|
||||
export class CommonModule {}
|
||||
@@ -27,6 +27,7 @@ export class ApiError extends HttpException {
|
||||
constructor(
|
||||
public readonly code: ErrorCode,
|
||||
message: string,
|
||||
public readonly headers: Record<string, string> = {},
|
||||
) {
|
||||
super(message, STATUS_BY_CODE[code]);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,9 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
||||
);
|
||||
}
|
||||
|
||||
if (exception instanceof ApiError) {
|
||||
reply.headers(exception.headers);
|
||||
}
|
||||
reply
|
||||
.code(status)
|
||||
.header('x-request-id', requestId)
|
||||
|
||||
Reference in New Issue
Block a user