import { Body, ConflictException, Controller, ForbiddenException, Get, HttpCode, Inject, Param, ParseUUIDPipe, Post, Put, Req, Res, UnauthorizedException, UseGuards, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { Throttle } from '@nestjs/throttler'; import type { Request, Response } from 'express'; import type { PublicUser } from '../domain/models'; import { AuthService } from './auth.service'; import { SessionService } from './session.service'; import { ChangePasswordDto, CreateUserDto, CredentialsDto, RegisterDto, ResetUserPasswordDto, SetRoleDto, } from './auth.dto'; import { CurrentUser, Public } from './auth.decorators'; import { AdminGuard } from './admin.guard'; import { OidcService } from './oidc.service'; import { AUTH_PROVIDERS, SESSION_COOKIE, allowSignup, authDisabled, sessionIdFrom, sessionTtlDays, } from './auth.constants'; import type { AuthProviderInfo } from './auth-provider'; // Auth endpoints. All are @Public() (the global guard would otherwise 401 the // login itself); @CurrentUser() still resolves from any present session so // /me and /status can report who you are. @Controller('api/auth') @Public() export class AuthController { constructor( private readonly auth: AuthService, private readonly sessions: SessionService, private readonly oidc: OidcService, @Inject(AUTH_PROVIDERS) private readonly providers: AuthProviderInfo[], ) {} // Bootstrap/login state for the frontend gate. The SSO provider appears // once an admin configured and enabled it. @Get('status') async status() { const sso = this.oidc.providerInfo(); return { configured: await this.auth.isConfigured(), authDisabled: authDisabled(), allowSignup: allowSignup(), providers: sso ? [...this.providers, sso] : this.providers, }; } // Who am I? null when unauthenticated (rather than 401) so the SPA can // decide whether to show the login screen without treating it as an error. @Get('me') me(@CurrentUser() user: PublicUser | undefined) { return { user: user ?? null }; } // One-time first-admin creation. Closed once any account exists. // A tighter limit on the login and register routes, so password guessing is // slow and can't tie up the server checking one wrong password after another. @Throttle({ default: { ttl: 60_000, limit: 10 } }) @Post('register') @HttpCode(201) async register(@Body() dto: RegisterDto, @Res({ passthrough: true }) res: Response) { const user = await this.auth.bootstrapAdmin(dto.username, dto.password); const token = await this.startSession(res, user.id); return { user, token }; } // Open self-registration (role 'user'), only when the operator enabled // AUTH_ALLOW_SIGNUP. The first account still goes through /register so the // instance always starts with an admin. @Post('signup') @HttpCode(201) async signup(@Body() dto: RegisterDto, @Res({ passthrough: true }) res: Response) { if (!allowSignup()) throw new ForbiddenException('Self-registration is disabled'); if (!(await this.auth.isConfigured())) { throw new ConflictException('Use the first-run setup to create the first account'); } const user = await this.auth.createLocalUser(dto.username, dto.password, 'user'); const token = await this.startSession(res, user.id); return { user, token }; } // Local username/password login. AuthGuard('local') runs the LocalStrategy, // which puts the validated PublicUser on req.user. // A tighter limit on the login and register routes, so password guessing is // slow and can't tie up the server checking one wrong password after another. @Throttle({ default: { ttl: 60_000, limit: 10 } }) @Post('login/local') @HttpCode(200) @UseGuards(AuthGuard('local')) async loginLocal(@Req() req: Request, @Res({ passthrough: true }) res: Response) { const user = req.user as PublicUser | undefined; if (!user) throw new UnauthorizedException('Invalid username or password'); const token = await this.startSession(res, user.id); return { user, token }; } // Accepts credentials in the body but also guards against a not-yet-bootstrapped // instance so the error is a clean 401 rather than a strategy quirk. The // DTO exists so the ValidationPipe rejects a malformed body before Passport. // A tighter limit on the login and register routes, so password guessing is // slow and can't tie up the server checking one wrong password after another. @Throttle({ default: { ttl: 60_000, limit: 10 } }) @Post('login') @HttpCode(200) @UseGuards(AuthGuard('local')) login( @Body() _dto: CredentialsDto, @Req() req: Request, @Res({ passthrough: true }) res: Response, ) { return this.loginLocal(req, res); } // Single sign-on, when configured in the admin settings: this starts the // browser redirect to the identity provider... @Get('login/oidc') @UseGuards(AuthGuard('oidc')) loginOidc() { // AuthGuard('oidc') issues the redirect; this body never runs. } // ...and the provider sends the browser back here. The guard exchanges // the code, resolves the user, and the session starts like a local login. @Get('callback/oidc') @UseGuards(AuthGuard('oidc')) async callbackOidc(@Req() req: Request, @Res() res: Response) { const user = req.user as PublicUser | undefined; if (!user) throw new UnauthorizedException('Single sign-on failed'); await this.startSession(res, user.id); res.redirect('/'); } // Change the signed-in user's password. The controller is @Public() for // the login routes, so this route checks the session itself. All sessions // are revoked and the caller gets a fresh one. @Post('password') @HttpCode(200) async changePassword( @CurrentUser() user: PublicUser | undefined, @Body() dto: ChangePasswordDto, @Res({ passthrough: true }) res: Response, ) { if (!user) throw new UnauthorizedException('Not signed in'); await this.auth.changePassword(user.id, dto.currentPassword, dto.newPassword); await this.sessions.destroyAllForUser(user.id); const token = await this.startSession(res, user.id); return { user, token }; } @Post('logout') @HttpCode(204) async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) { await this.sessions.destroy(sessionIdFrom(req)); res.clearCookie(SESSION_COOKIE, cookieBaseOptions()); } // --- User management, admin only. Registration closes after the first // account; further accounts are created here. @Get('users') @UseGuards(AdminGuard) async listUsers() { return { users: await this.auth.listUsers() }; } @Post('users') @HttpCode(201) @UseGuards(AdminGuard) async createUser(@Body() dto: CreateUserDto) { const created = await this.auth.createLocalUser(dto.username, dto.password, dto.role ?? 'user'); return { user: created }; } // Promote/demote an account. The service refuses the caller's own account, // which guarantees at least one admin always remains. @Put('users/:id/role') @UseGuards(AdminGuard) async setUserRole( @CurrentUser() actor: PublicUser | undefined, @Param('id', ParseUUIDPipe) id: string, @Body() dto: SetRoleDto, ) { const user = await this.auth.adminSetRole(id, dto.role, actor?.id ?? null); return { user }; } // Reset another account's password. The target's sessions are revoked. @Post('users/:id/password') @HttpCode(200) @UseGuards(AdminGuard) async resetUserPassword( @Param('id', ParseUUIDPipe) id: string, @Body() dto: ResetUserPasswordDto, ) { const user = await this.auth.adminSetPassword(id, dto.password); await this.sessions.destroyAllForUser(id); return { user }; } // Mints a session and sets the signed, HttpOnly cookie. The session id is // also returned as an opaque token for clients that can't use cookies // (native shells send it back as an Authorization bearer header). private async startSession(res: Response, userId: string): Promise { const session = await this.sessions.create(userId); res.cookie(SESSION_COOKIE, session.id, { ...cookieBaseOptions(), signed: true, maxAge: sessionTtlDays() * 24 * 60 * 60 * 1000, }); return session.id; } } // Cookie flags shared by set and clear so they always match (clearCookie only // works when path/sameSite/etc. line up). Secure in production so the cookie // never rides over plain HTTP once TLS is in front. function cookieBaseOptions() { return { httpOnly: true, sameSite: 'strict' as const, secure: process.env.NODE_ENV === 'production', path: '/', }; }