- Extract auth DTOs, cookie/JWT helpers and the generic duration parser. - Configure the session cookie and map domain auth failures to HTTP responses. - Add typed Swagger responses and focused regression coverage.
103 lines
2.9 KiB
TypeScript
103 lines
2.9 KiB
TypeScript
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<UserEntity>,
|
|
@InjectRepository(RevokedTokenEntity)
|
|
private readonly revokedTokens: Repository<RevokedTokenEntity>,
|
|
private readonly config: ConfigService<AppConfig, true>,
|
|
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<AuthSession> {
|
|
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<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
|
): 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<AuthSession> {
|
|
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<void> {
|
|
await this.revokedTokens.save({
|
|
tokenHash: tokenHash(session.token),
|
|
expiresAt: session.expiresAt,
|
|
});
|
|
}
|
|
}
|