feat(api): add auth and users
This commit is contained in:
1 parent
afc1355221
commit
49035f3501
20 files changed
+756
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { AuthService } from './auth.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class AuthMiddleware implements NestMiddleware {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
public async use(req: Request, _res: Response, next: NextFunction) {
|
||||
const fallback = await this.authService.resolveDevFallbackFromRequest(req);
|
||||
if (fallback) {
|
||||
req.user = fallback.user;
|
||||
req.identity = fallback.identity;
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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 { UserResolverGuard } from './user-resolver.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
JwtAuthGuard,
|
||||
IdentityResolverGuard,
|
||||
UserResolverGuard,
|
||||
RolesGuard,
|
||||
{ provide: APP_GUARD, useClass: JwtAuthGuard },
|
||||
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
|
||||
{ provide: APP_GUARD, useClass: UserResolverGuard },
|
||||
],
|
||||
exports: [
|
||||
AuthService,
|
||||
JwtService,
|
||||
IdentityService,
|
||||
UserResolverGuard,
|
||||
RolesGuard,
|
||||
],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
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,
|
||||
private readonly secretService: SecretService,
|
||||
) {}
|
||||
|
||||
public async resolveDevFallbackFromRequest(
|
||||
req: Request,
|
||||
): 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;
|
||||
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');
|
||||
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;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +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<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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -0,0 +1,36 @@
|
||||
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';
|
||||
import './auth-request';
|
||||
|
||||
@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 && 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.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { IdentityDocument, UserDocument } from '../global/database/schema';
|
||||
import { UserResolverGuard } from './user-resolver.guard';
|
||||
import './auth-request';
|
||||
|
||||
function createContext(request: Record<string, unknown>): ExecutionContext {
|
||||
return {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => request,
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
}
|
||||
|
||||
describe('UserResolverGuard', () => {
|
||||
it('resolves the community membership before role guards run', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const identityId = new mongoose.Types.ObjectId();
|
||||
const user = { _id: new mongoose.Types.ObjectId() } as UserDocument;
|
||||
const findOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(user),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const request = {
|
||||
params: { communityId: communityId.toString() },
|
||||
identity: { _id: identityId } as IdentityDocument,
|
||||
};
|
||||
const guard = new UserResolverGuard(connectionService);
|
||||
|
||||
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||
|
||||
expect(findOne).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
identityId,
|
||||
});
|
||||
expect(request.user).toBe(user);
|
||||
});
|
||||
|
||||
it('skips lookup when there is no resolved identity', async () => {
|
||||
const connectionService = {
|
||||
getModel: jest.fn(),
|
||||
} as unknown as ConnectionService;
|
||||
const request = {
|
||||
params: { communityId: new mongoose.Types.ObjectId().toString() },
|
||||
};
|
||||
const guard = new UserResolverGuard(connectionService);
|
||||
|
||||
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
|
||||
|
||||
expect(connectionService.getModel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import './auth-request';
|
||||
|
||||
@Injectable()
|
||||
export class UserResolverGuard implements CanActivate {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const communityId = request.params?.communityId;
|
||||
|
||||
if (
|
||||
request.user ||
|
||||
!request.identity ||
|
||||
typeof communityId !== 'string' ||
|
||||
!mongoose.isValidObjectId(communityId)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
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 true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type {
|
||||
CommunityDocument,
|
||||
UserDocument,
|
||||
} from '../../global/database/schema';
|
||||
|
||||
export interface MeIdentityDto {
|
||||
id: string;
|
||||
entraOid: string;
|
||||
tenantId?: string;
|
||||
email?: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface MeMembershipDto {
|
||||
user: UserDocument;
|
||||
community: CommunityDocument | null;
|
||||
}
|
||||
|
||||
export interface MeResponseDto {
|
||||
identity: MeIdentityDto | null;
|
||||
memberships: MeMembershipDto[];
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { IsBoolean, IsIn, IsOptional } from 'class-validator';
|
||||
import { RIOT_PLATFORM_ROUTES } from '../../riot/riot.types';
|
||||
import type { RiotPlatformRoute } from '../../riot/riot.types';
|
||||
|
||||
export class RefreshRiotAccountDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
force?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(RIOT_PLATFORM_ROUTES)
|
||||
platform?: RiotPlatformRoute;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import '../auth/auth-request';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
IdentityDocument,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import type { MeResponseDto } from './dto/me-response.dto';
|
||||
import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto';
|
||||
|
||||
@Controller('me')
|
||||
export class UserController {
|
||||
constructor(
|
||||
private readonly enrichment: RiotAccountEnrichmentService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@AllowPublicAccess()
|
||||
public async me(@Req() req: Request): Promise<MeResponseDto> {
|
||||
if (req.identity) {
|
||||
return this.resolveMeByIdentity(req.identity);
|
||||
}
|
||||
if (req.user) {
|
||||
return {
|
||||
identity: null,
|
||||
memberships: [
|
||||
{
|
||||
user: req.user,
|
||||
community: await this.findCommunity(req.user),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { identity: null, memberships: [] };
|
||||
}
|
||||
|
||||
@Post('riot-accounts/:puuid/refresh')
|
||||
public async refreshRiotAccount(
|
||||
@CurrentUser() user: UserDocument | undefined,
|
||||
@Req() req: Request,
|
||||
@Param('puuid') puuid: string,
|
||||
@Body() body: RefreshRiotAccountDto,
|
||||
) {
|
||||
const resolvedUser =
|
||||
user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null);
|
||||
if (!resolvedUser) {
|
||||
throw new UnauthorizedException('Authentication required.');
|
||||
}
|
||||
if (!resolvedUser.riotAccounts.some((account) => account.puuid === puuid)) {
|
||||
throw new ForbiddenException('Riot account does not belong to user.');
|
||||
}
|
||||
|
||||
return this.enrichment.enrichRiotAccount({
|
||||
userId: resolvedUser._id,
|
||||
puuid,
|
||||
options: {
|
||||
force: body.force === true,
|
||||
platform: body.platform,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async resolveMeByIdentity(
|
||||
identity: IdentityDocument,
|
||||
): Promise<MeResponseDto> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const users = await UserModel.find({ identityId: identity._id }).exec();
|
||||
const communities = await CommunityModel.find({
|
||||
_id: { $in: users.map((user) => user.communityId) },
|
||||
}).exec();
|
||||
const communityById = new Map(
|
||||
communities.map((community) => [community._id.toString(), community]),
|
||||
);
|
||||
|
||||
return {
|
||||
identity: {
|
||||
id: identity._id.toString(),
|
||||
entraOid: identity.entraOid,
|
||||
tenantId: identity.tenantId,
|
||||
email: identity.email,
|
||||
displayName: identity.displayName,
|
||||
},
|
||||
memberships: users.map((user) => ({
|
||||
user,
|
||||
community: communityById.get(user.communityId.toString()) ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private async findCommunity(user: UserDocument) {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
return CommunityModel.findById(user.communityId).exec();
|
||||
}
|
||||
|
||||
private async findUserByIdentityAndPuuid(
|
||||
identity: IdentityDocument,
|
||||
puuid: string,
|
||||
): Promise<UserDocument | null> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.findOne({
|
||||
identityId: identity._id,
|
||||
'riotAccounts.puuid': puuid,
|
||||
}).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { UserController } from './user.controller';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule],
|
||||
controllers: [UserController],
|
||||
})
|
||||
export class UserModule {}
|
||||
Reference in new issue
Block a user