.
This commit is contained in:
1 parent
5af2c80cd1
commit
f7ee34da4f
78 files changed
+9016
-150
No files matched your search
@@ -0,0 +1,7 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED =
|
||||
'lolympus:allow_public_access';
|
||||
|
||||
export const AllowPublicAccess = () =>
|
||||
SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { JWTHeaderParameters, JWTPayload } from 'jose';
|
||||
import type {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import type { IdentityProviderName } from './jwt.service';
|
||||
|
||||
declare module 'express' {
|
||||
interface Request {
|
||||
tokenPayload?: JWTPayload;
|
||||
tokenHeader?: JWTHeaderParameters;
|
||||
identityProvider?: IdentityProviderName;
|
||||
identity?: IdentityDocument;
|
||||
user?: UserDocument;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,18 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
import './auth-request';
|
||||
|
||||
@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;
|
||||
const fallback = await this.authService.resolveDevFallbackFromRequest(req);
|
||||
if (fallback) {
|
||||
req.user = fallback.user;
|
||||
req.identity = fallback.identity;
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,32 @@
|
||||
import { Global, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { AuthMiddleware } from './auth.middleware';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { AuthService } from './auth.service';
|
||||
import { IdentityResolverGuard } from './identity-resolver.guard';
|
||||
import { IdentityService } from './identity.service';
|
||||
import { JwtAuthGuard } from './jwt.guard';
|
||||
import { JwtService } from './jwt.service';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { UserResolverInterceptor } from './user-resolver.interceptor';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [AuthService, RolesGuard],
|
||||
exports: [AuthService, RolesGuard],
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
JwtAuthGuard,
|
||||
IdentityResolverGuard,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
||||
],
|
||||
exports: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
RolesGuard,
|
||||
UserResolverInterceptor,
|
||||
],
|
||||
})
|
||||
export class AuthModule implements NestModule {
|
||||
public configure(consumer: MiddlewareConsumer) {
|
||||
consumer.apply(AuthMiddleware).forRoutes('*');
|
||||
}
|
||||
}
|
||||
export class AuthModule {}
|
||||
@@ -2,22 +2,61 @@ 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';
|
||||
import {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import './auth-request';
|
||||
|
||||
interface DevFallbackResult {
|
||||
user: UserDocument;
|
||||
identity?: IdentityDocument;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly secretService: SecretService,
|
||||
) {}
|
||||
|
||||
// 로그인/세션 구현 전까지는 `X-Auth-User-Id` 헤더로 유저를 식별.
|
||||
// OAuth 도입 시 이 메서드만 교체하면 됨.
|
||||
public async resolveUserFromRequest(
|
||||
public async resolveDevFallbackFromRequest(
|
||||
req: Request,
|
||||
): Promise<UserDocument | null> {
|
||||
): Promise<DevFallbackResult | null> {
|
||||
if (!(await this.isDevHeaderEnabled())) return null;
|
||||
const header = req.headers['x-auth-user-id'];
|
||||
const userId = Array.isArray(header) ? header[0] : header;
|
||||
if (!userId || !mongoose.isValidObjectId(userId)) return null;
|
||||
return this.resolveDevUserById(userId);
|
||||
}
|
||||
|
||||
public async resolveDevUserById(
|
||||
userId: unknown,
|
||||
): Promise<DevFallbackResult | null> {
|
||||
if (!(await this.isDevHeaderEnabled())) return null;
|
||||
if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findById(userId).exec();
|
||||
const user = await UserModel.findById(userId).exec();
|
||||
if (!user) return null;
|
||||
|
||||
const result: DevFallbackResult = { user };
|
||||
if (user.identityId) {
|
||||
const IdentityModel = await this.connectionService.getModel('identity');
|
||||
const identity = await IdentityModel.findById(user.identityId).exec();
|
||||
if (identity) result.identity = identity;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private async isDevHeaderEnabled(): Promise<boolean> {
|
||||
if (process.env.NODE_ENV === 'prod') return false;
|
||||
const value = await this.secretService.get<string>(
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
process.env.AUTH_DEV_HEADER_ENABLED ?? 'false',
|
||||
);
|
||||
return value === 'true';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { IdentityDocument } from '../global/database/schema';
|
||||
import './auth-request';
|
||||
|
||||
export const CurrentIdentity = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): IdentityDocument | undefined => {
|
||||
const req = ctx.switchToHttp().getRequest<Request>();
|
||||
return req.identity;
|
||||
},
|
||||
);
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { UserDocument } from '../global/database/schema';
|
||||
import './auth-request';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
|
||||
const req = ctx.switchToHttp().getRequest<{ user?: UserDocument }>();
|
||||
const req = ctx.switchToHttp().getRequest<Request>();
|
||||
return req.user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { IdentityService } from './identity.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class IdentityResolverGuard implements CanActivate {
|
||||
constructor(private readonly identityService: IdentityService) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
if (request.identity || !request.tokenPayload) return true;
|
||||
|
||||
const entraOid = stringClaim(request.tokenPayload.oid);
|
||||
if (!entraOid) {
|
||||
throw new UnauthorizedException('Token is missing oid claim.');
|
||||
}
|
||||
|
||||
request.identity = await this.identityService.findOrCreateByOid({
|
||||
entraOid,
|
||||
tenantId: stringClaim(request.tokenPayload.tid),
|
||||
email:
|
||||
stringClaim(request.tokenPayload.preferred_username) ??
|
||||
stringClaim(request.tokenPayload.email),
|
||||
displayName: stringClaim(request.tokenPayload.name),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function stringClaim(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Injectable, InternalServerErrorException } from '@nestjs/common';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { IdentityDocument } from '../global/database/schema';
|
||||
|
||||
interface IdentityInput {
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class IdentityService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async findOrCreateByOid(
|
||||
input: IdentityInput,
|
||||
): Promise<IdentityDocument> {
|
||||
const IdentityModel = await this.connectionService.getModel('identity');
|
||||
const identity = await IdentityModel.findOneAndUpdate(
|
||||
{ entraOid: input.entraOid },
|
||||
{
|
||||
$set: {
|
||||
tenantId: input.tenantId,
|
||||
email: input.email,
|
||||
displayName: input.displayName,
|
||||
lastSignInAt: new Date(),
|
||||
},
|
||||
$setOnInsert: { entraOid: input.entraOid },
|
||||
},
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).exec();
|
||||
|
||||
if (!identity) {
|
||||
throw new InternalServerErrorException('Failed to resolve identity.');
|
||||
}
|
||||
return identity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { decodeJwt } from 'jose';
|
||||
import type { Request } from 'express';
|
||||
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
|
||||
import { AuthService } from './auth.service';
|
||||
import { IdentityProviderName, JwtService } from './jwt.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(
|
||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
const authz = request.headers?.authorization;
|
||||
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
|
||||
|
||||
if (!authzHeader) {
|
||||
const fallback =
|
||||
await this.authService.resolveDevFallbackFromRequest(request);
|
||||
if (fallback) {
|
||||
request.user = fallback.user;
|
||||
request.identity = fallback.identity;
|
||||
return true;
|
||||
}
|
||||
if (isPublicAccessAllowed) return true;
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
if (!authzHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException(
|
||||
'Missing or invalid Authorization header',
|
||||
);
|
||||
}
|
||||
|
||||
const token = authzHeader.slice('Bearer '.length).trim();
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Empty bearer token');
|
||||
}
|
||||
|
||||
const identityProvider = this.pickIdPFromToken(token);
|
||||
|
||||
try {
|
||||
const verifyResult = await this.jwtService.verify(
|
||||
token,
|
||||
identityProvider,
|
||||
);
|
||||
request.tokenPayload = verifyResult.payload;
|
||||
request.tokenHeader = verifyResult.protectedHeader;
|
||||
request.identityProvider = identityProvider;
|
||||
return true;
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'JWT verification failed';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private pickIdPFromToken(token: string): IdentityProviderName {
|
||||
try {
|
||||
const { iss } = decodeJwt(token) as { iss?: string };
|
||||
if (!iss) {
|
||||
throw new Error('Token has no issuer (iss) claim');
|
||||
}
|
||||
const lower = iss.toLowerCase();
|
||||
if (lower.includes('login.microsoftonline.com')) {
|
||||
return 'MICROSOFT_ENTRAID';
|
||||
}
|
||||
throw new Error(`Unknown issuer: ${iss}`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Unable to decode token';
|
||||
throw new UnauthorizedException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
createRemoteJWKSet,
|
||||
jwtVerify,
|
||||
JWTPayload,
|
||||
JWTVerifyGetKey,
|
||||
JWTVerifyResult,
|
||||
} from 'jose';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
|
||||
export type IdentityProviderName = 'MICROSOFT_ENTRAID';
|
||||
|
||||
interface EntraConfig {
|
||||
tenantId: string;
|
||||
audience: string;
|
||||
issuer: string;
|
||||
allowedAlgs: string[];
|
||||
jwks: JWTVerifyGetKey;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtService {
|
||||
private entraConfig?: EntraConfig;
|
||||
private readonly clockTolerance = Number(
|
||||
process.env.JWT_CLOCK_TOLERANCE || 5,
|
||||
);
|
||||
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
public async verify(
|
||||
token: string,
|
||||
identityProvider: IdentityProviderName,
|
||||
): Promise<JWTVerifyResult<JWTPayload>> {
|
||||
if (!token) {
|
||||
throw new Error('Empty token');
|
||||
}
|
||||
|
||||
if (identityProvider !== 'MICROSOFT_ENTRAID') {
|
||||
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
||||
}
|
||||
|
||||
const provider = await this.getEntraConfig();
|
||||
const result = await jwtVerify(token, provider.jwks, {
|
||||
issuer: provider.issuer,
|
||||
audience: provider.audience,
|
||||
algorithms: provider.allowedAlgs,
|
||||
clockTolerance: this.clockTolerance,
|
||||
});
|
||||
|
||||
const { payload, protectedHeader } = result;
|
||||
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
|
||||
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
||||
}
|
||||
if (payload.ver && payload.ver !== '2.0') {
|
||||
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
|
||||
}
|
||||
if (payload.tid && payload.tid !== provider.tenantId) {
|
||||
throw new Error(`Unexpected tenant: ${payload.tid}`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async getEntraConfig(): Promise<EntraConfig> {
|
||||
if (this.entraConfig) return this.entraConfig;
|
||||
|
||||
await this.secretService.ready();
|
||||
const [audience, tenantId, allowedAlgsRaw] = await Promise.all([
|
||||
this.secretService.get<string>('JWT_CLAIM_AUDIENCE'),
|
||||
this.secretService.get<string>('MICROSOFT_ENTRAID_TENANT_ID'),
|
||||
this.secretService.get<string>('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'),
|
||||
]);
|
||||
|
||||
const allowedAlgs = allowedAlgsRaw
|
||||
.split(',')
|
||||
.map((alg) => alg.trim())
|
||||
.filter(Boolean);
|
||||
if (allowedAlgs.length === 0) {
|
||||
allowedAlgs.push('RS256');
|
||||
}
|
||||
|
||||
const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
|
||||
const jwks = createRemoteJWKSet(
|
||||
new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'),
|
||||
{
|
||||
cooldownDuration: 30_000,
|
||||
timeoutDuration: 10_000,
|
||||
},
|
||||
);
|
||||
|
||||
this.entraConfig = {
|
||||
tenantId,
|
||||
audience,
|
||||
issuer,
|
||||
allowedAlgs,
|
||||
jwks,
|
||||
};
|
||||
return this.entraConfig;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Reflector } from '@nestjs/core';
|
||||
import type { Request } from 'express';
|
||||
import { CommunityRole, UserDocument } from '../global/database/schema';
|
||||
import { ROLES_KEY } from './roles.decorator';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
@@ -23,6 +24,9 @@ export class RolesGuard implements CanActivate {
|
||||
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const user = req.user as UserDocument | undefined;
|
||||
if (!user && req.identity) {
|
||||
throw new ForbiddenException('No membership in this community.');
|
||||
}
|
||||
if (!user) throw new UnauthorizedException('Authentication required.');
|
||||
if (!requiredRoles.includes(user.role)) {
|
||||
throw new ForbiddenException('Insufficient role.');
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { Observable } from 'rxjs';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class UserResolverInterceptor implements NestInterceptor {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Promise<Observable<unknown>> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const communityId = request.params?.communityId;
|
||||
|
||||
if (
|
||||
!request.user &&
|
||||
request.identity &&
|
||||
typeof communityId === 'string' &&
|
||||
mongoose.isValidObjectId(communityId)
|
||||
) {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findOne({
|
||||
communityId: new mongoose.Types.ObjectId(communityId),
|
||||
identityId: request.identity._id,
|
||||
}).exec();
|
||||
if (user) request.user = user;
|
||||
}
|
||||
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user