Skip to content

AuthService

reference
2 min readUpdated

Kind: Service

Source: atloria-monorepo/apps/api/src/auth/auth.service.ts

AuthService encapsulates the API's authentication lifecycle, including registration, email verification, password recovery, credential login, token refresh, and logout. It coordinates user validation and user-profile retrieval while returning DTOs suitable for authentication controllers and API consumers. In the NestJS backend, it serves as the central business-logic layer between auth endpoints, user persistence, and token/email integrations.

Methods

MethodSignatureReturnsDescription
registerregister(registerDto: RegisterDto)Promise<AuthResponseDto>Register a new user
verifyEmailverifyEmail(token: string)Promise<{ verified: boolean; email: string }>Verify a user's email address using the emailed token.
resendVerificationresendVerification(userId: string)Promise<{ sent: boolean; alreadyVerified?: boolean }>Re-send the verification email for a logged-in, unverified user.
forgotPasswordforgotPassword(email: string)Promise<{ message: string }>Start a password reset.
resetPasswordresetPassword(token: string, newPassword: string)Promise<{ success: boolean }>Complete a password reset with a valid, unexpired token.
loginlogin(loginDto: LoginDto)Promise<AuthResponseDto>Login user
refreshrefresh(refreshToken: string)Promise<AuthResponseDto>Refresh access token
logoutlogout(userId: string)Promise<void>Logout user
getMegetMe(userId: string)Promise<UserResponseDto>Get current user
validateUservalidateUser(email: string, password: string)`Promise<Usernull>`
issueTokensForUserissueTokensForUser(user: User)Promise<AuthResponseDto>A1 SSO: mint the SAME access+refresh token pair as a password login for an already-authenticated user (e.g.
revokeAllForUserrevokeAllForUser(userId: string)Promise<void>A2 deprovisioning: revoke every active session for a user by clearing their refresh token in Redis.

Dependencies

  • PrismaService
  • RedisService
  • JwtService
  • ConfigService
  • EmailService
  • AuditService (optional)

Where it refuses work

  • AuthService stops the work with UnauthorizedException when !user — “User not found”, in 2 places.
  • AuthService stops the work with ConflictException when existingUser — “User with this email already exists”.
  • AuthService stops the work with BadRequestException when !token — “Verification token is required”.
  • AuthService stops the work with BadRequestException when !user — “Invalid or already-used verification token”.
  • AuthService stops the work with BadRequestException when !user — “User not found”.
  • AuthService stops the work with BadRequestException when !token — “Reset token is required”.

When something fails

  • AuthService handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1.

Diagram

mermaid
sequenceDiagram
    participant Client
    participant AuthController
    participant AuthService
    participant UsersService
    participant TokenService
    participant EmailService

    Client->>AuthController: register(credentials)
    AuthController->>AuthService: register()
    AuthService->>UsersService: create user
    AuthService->>TokenService: generate auth tokens
    AuthService->>EmailService: send verification email
    AuthService-->>AuthController: AuthResponseDto
    AuthController-->>Client: authentication response

    Client->>AuthController: login(credentials)
    AuthController->>AuthService: login()
    AuthService->>AuthService: validateUser()
    AuthService->>TokenService: generate auth tokens
    AuthService-->>Client: AuthResponseDto

    Client->>AuthController: refresh(refreshToken)
    AuthController->>AuthService: refresh()
    AuthService->>TokenService: validate and rotate token
    AuthService-->>Client: AuthResponseDto

Usage

ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class SessionFacade {
  constructor(private readonly authService: AuthService) {}

  async signIn(email: string, password: string) {
    const user = await this.authService.validateUser(email, password);

    if (!user) {
      throw new UnauthorizedException('Invalid email or password');
    }

    return this.authService.login(user);
  }

  async registerAccount(registerDto: {
    email: string;
    password: string;
    firstName: string;
    lastName: string;
  }) {
    return this.authService.register(registerDto);
  }

  async refreshSession(refreshToken: string) {
    return this.authService.refresh(refreshToken);
  }

  async requestPasswordReset(email: string) {
    return this.authService.forgotPassword(email);
  }
}

AI Coding Instructions

  • Keep authentication business logic in AuthService; controllers should only validate request DTOs, extract request context, and delegate to service methods.
  • Use validateUser() before issuing credentials through login(); never expose whether a password specifically failed in public error responses.
  • Preserve the AuthResponseDto and UserResponseDto response contracts when changing token payloads or user fields.
  • Ensure email verification, password-reset, and refresh-token flows validate token expiry and ownership before modifying user state.
  • When adding auth providers or token strategies, integrate them through the existing user lookup, token generation, and logout/refresh lifecycle rather than duplicating session logic.

Relationships

  • DEPENDS_ON → PrismaService
  • DEPENDS_ON → RedisService
  • DEPENDS_ON → jwtservice
  • DEPENDS_ON → configservice
  • DEPENDS_ON → EmailService
  • DEPENDS_ON → AuditService

Referenced By

  • AuthController (DEPENDS_ON)
  • AuthModule (MODULE_PROVIDES)
  • AuthModule (MODULE_EXPORTS)
  • SamlController (DEPENDS_ON)
  • ScimService (DEPENDS_ON)

Was this page helpful?

Download as PDF