import { Injectable } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { InjectRepository } from "@nestjs/typeorm"; import { Repository } from "typeorm"; import { AppConfig } from "../config/app.config"; import { durationSeconds } from "../common/interval"; import { PasswordService } from "./password.service"; import { RevokedTokenEntity } from "./revoked-token.entity"; import { UserEntity } from "./user.entity"; import { AuthFailure } from "./auth.error"; import { issueJwt, safeUser, tokenHash, verifyJwt } from "./jwt.helpers"; export interface SafeUser { id: string; username: string; createdAt: Date; updatedAt: Date; } export interface AuthSession { user: SafeUser; token: string; expiresAt: Date; } @Injectable() export class AuthService { constructor( @InjectRepository(UserEntity) private readonly users: Repository, @InjectRepository(RevokedTokenEntity) private readonly revokedTokens: Repository, private readonly config: ConfigService, private readonly passwords: PasswordService, ) {} get enabled(): boolean { return this.config.get("AUTH_ENABLED"); } get cookieName(): string { return this.config.get("AUTH_COOKIE_NAME"); } async login(username: string, password: string): Promise { if (!this.enabled) { throw new AuthFailure("disabled"); } const user = await this.users.findOneBy({ username }); const valid = user ? await this.passwords.verify(password, user.passwordHash) : false; if (!user || !valid) { throw new AuthFailure("invalid-credentials"); } return this.issueToken(user); } issueToken( user: Pick, ): AuthSession { if (!this.enabled) { throw new AuthFailure("disabled"); } const expiresIn = durationSeconds(this.config.get("AUTH_JWT_EXPIRES_IN")); if (expiresIn === null) { throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration."); } const { token, expiresAt } = issueJwt( user.id, expiresIn, this.config.get("AUTH_JWT_SECRET"), ); return { user: safeUser(user), token, expiresAt, }; } async authenticate(token: string): Promise { const payload = verifyJwt(token, this.config.get("AUTH_JWT_SECRET")); const digest = tokenHash(token); if (await this.revokedTokens.findOneBy({ tokenHash: digest })) { throw new AuthFailure("invalid-token"); } const user = await this.users.findOneBy({ id: payload.sub }); if (!user) throw new AuthFailure("invalid-token"); return { user: safeUser(user), token, expiresAt: new Date(payload.exp * 1000), }; } async revoke(session: AuthSession): Promise { await this.revokedTokens.save({ tokenHash: tokenHash(session.token), expiresAt: session.expiresAt, }); } }