Skip to main content

Overview

The AuthService handles all authentication operations including login, token refresh (for both web and mobile sessions), logout, and user profile retrieval. Location: src/app/core/services/http/auth.service.ts

Public Methods

login()

Authenticates a user with email/phone and password.
payload
LoginPayload
required
Login credentials and device information
httpOptions
object
Optional HTTP configuration
Returns: Observable<LoginResponse>
accessToken
string
JWT access token for API requests
sessionType
SessionType
Session type: ‘MOBILE’ or ‘WEB’
refreshToken
string
Refresh token (only present for MOBILE sessions)
accessTokenExpiresAt
number
Timestamp when access token expires
user
UserProfile
Authenticated user profile data
Example:
src/app/features/auth/login/login.component.ts
import { AuthService } from '@/app/core/services/http/auth.service';
import { inject } from '@angular/core';

export class LoginComponent {
  private authService = inject(AuthService);

  login(email: string, password: string) {
    const payload: LoginPayload = {
      email,
      password,
      appAudience: 'DRIVER_APP',
      userType: 'DRIVER'
    };

    this.authService.login(payload, { withCredentials: true })
      .subscribe({
        next: (response) => {
          console.log('Login successful:', response);
          // Store tokens and navigate to dashboard
        },
        error: (error) => {
          console.error('Login failed:', error.message);
        }
      });
  }
}

refresh()

Refreshes the access token using either a refresh token (mobile) or HTTP-only cookie (web).
refreshToken
string
Refresh token (required for mobile sessions)
Use HTTP-only cookie for refresh (default: false)
Returns: Observable<RefreshResponse>
For web sessions, the refresh token is stored in an HTTP-only cookie:
this.authService.refresh(undefined, true).subscribe({
  next: (response: RefreshResponseWeb) => {
    // Access token refreshed
    console.log('New access token:', response.accessToken);
  },
  error: (error) => {
    // Redirect to login
  }
});

logoutWeb()

Logs out a web session by clearing the HTTP-only refresh token cookie. Returns: Observable<void>
this.authService.logoutWeb().subscribe({
  next: () => {
    console.log('Logged out successfully');
    // Redirect to login page
  },
  error: (error) => {
    console.error('Logout failed:', error);
  }
});

logoutMobile()

Logs out a mobile session by invalidating the refresh token.
refreshToken
string
required
The refresh token to invalidate
Returns: Observable<void>
const refreshToken = localStorage.getItem('refreshToken');

this.authService.logoutMobile(refreshToken).subscribe({
  next: () => {
    // Clear local storage
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    // Redirect to login
  }
});

me()

Retrieves the authenticated user’s profile information.
Use HTTP-only cookie for authentication (default: true)
Returns: Observable<UserProfile>
this.authService.me(true).subscribe({
  next: (profile) => {
    console.log('User profile:', profile);
    this.displayName = profile.firstName + ' ' + profile.lastName;
  },
  error: (error) => {
    console.error('Failed to load profile:', error);
  }
});

Error Handling

All methods return normalized ApiError objects with the following structure:
interface ApiError {
  status?: number;           // HTTP status code
  message: string;           // Error message
  code?: string;            // Application error code
  validation?: any;         // Validation errors
  raw?: any;               // Original error object
  url?: string | null;     // Request URL
}
Example error handling:
this.authService.login(payload).subscribe({
  error: (error: ApiError) => {
    if (error.status === 401) {
      this.errorMessage = 'Invalid email or password';
    } else if (error.code === 'USER_SUSPENDED') {
      this.errorMessage = 'Your account has been suspended';
    } else {
      this.errorMessage = error.message || 'Login failed';
    }
  }
});

Best Practices

Session Type Selection: Use web sessions with HTTP-only cookies for browser-based apps, and mobile sessions with explicit token storage for native mobile apps.
Token Refresh: Implement automatic token refresh 30-60 seconds before expiration to ensure seamless user experience.
Security: Never store refresh tokens in localStorage for web sessions. Always use HTTP-only cookies to prevent XSS attacks.

Build docs developers (and LLMs) love