Skip to content

Auth Service (src/auth/auth.service.ts)

Overview

The AuthService is the core service responsible for user authentication, JWT token management, and token validation in the BidScript backend. It provides methods for authenticating users, generating JWT tokens, validating tokens, and handling token refresh.

Dependencies

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from '../types/interfaces/user.interface';

Methods

validateUser

async validateUser(username: string, password: string): Promise<User | null>

Validates user credentials against the database. Returns the user if valid, null otherwise.

Parameters: - username: string - The username to validate - password: string - The password to validate (will be hashed and compared)

Returns: - User | null: The user object if valid, null if credentials are invalid

Example:

const user = await this.authService.validateUser('admin', 'password123');
if (user) {
  // User is authenticated
} else {
  // Invalid credentials
}

login

async login(user: User): Promise<{ access_token: string, user: User }>

Generates a JWT token for an authenticated user and returns it along with the user data.

Parameters: - user: User - The authenticated user

Returns: - { access_token: string, user: User }: Object containing the JWT token and user data

Example:

const result = await this.authService.login(user);
// result = { access_token: 'jwt-token', user: { id: '1', username: 'admin', ... } }

validateToken

async validateToken(token: string): Promise<User>

Validates a JWT token and returns the user associated with it.

Parameters: - token: string - The JWT token to validate

Returns: - User: The user associated with the token

Throws: - UnauthorizedException: If the token is invalid or expired

Example:

try {
  const user = await this.authService.validateToken(token);
  // Token is valid, user is authenticated
} catch (error) {
  // Token is invalid or expired
}

refreshToken

async refreshToken(token: string): Promise<{ access_token: string }>

Generates a new JWT token based on an existing valid token.

Parameters: - token: string - The existing JWT token

Returns: - { access_token: string }: Object containing the new JWT token

Throws: - UnauthorizedException: If the token is invalid or expired

Example:

try {
  const result = await this.authService.refreshToken(oldToken);
  // result = { access_token: 'new-jwt-token' }
} catch (error) {
  // Token refresh failed
}

Implementation Details

Token Generation

private generateToken(payload: { sub: string, username: string, roles: string[] }): string {
  return this.jwtService.sign(payload);
}

Generates a JWT token with user ID, username, and roles.

User Role Verification

verifyRoles(user: User, requiredRoles: string[]): boolean {
  return requiredRoles.some(role => user.roles.includes(role));
}

Verifies if a user has the required roles for access control.

Error Handling

The service throws appropriate exceptions for different authentication scenarios:

if (!user) {
  throw new UnauthorizedException('Invalid credentials');
}

if (token.exp < Math.floor(Date.now() / 1000)) {
  throw new UnauthorizedException('Token expired');
}

Integration with JWT Module

The service uses the NestJS JWT module configured in auth.module.ts:

JwtModule.register({
  secret: process.env.JWT_SECRET,
  signOptions: { expiresIn: process.env.JWT_EXPIRATION || '8h' },
})

Security Considerations

  • The service never returns or logs raw passwords
  • Passwords are hashed and salted before comparison
  • Tokens have configurable expiration times
  • Token validation includes signature verification