|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { ConfigService } from '@nestjs/config'; |
| 3 | +import { HttpService } from '@nestjs/axios'; |
| 4 | +import { firstValueFrom } from 'rxjs'; |
| 5 | + |
| 6 | +interface Auth0TokenResponse { |
| 7 | + access_token: string; |
| 8 | + token_type: string; |
| 9 | + expires_in: number; |
| 10 | +} |
| 11 | + |
| 12 | +interface Auth0TokenCache { |
| 13 | + token: string; |
| 14 | + expiresAt: number; |
| 15 | +} |
| 16 | + |
| 17 | +@Injectable() |
| 18 | +export class Auth0Service { |
| 19 | + private readonly logger = new Logger(Auth0Service.name); |
| 20 | + private readonly auth0Url: string; |
| 21 | + private readonly clientId: string; |
| 22 | + private readonly clientSecret: string; |
| 23 | + private readonly audience: string; |
| 24 | + private tokenCache: Auth0TokenCache | null = null; |
| 25 | + |
| 26 | + constructor( |
| 27 | + private readonly httpService: HttpService, |
| 28 | + private readonly configService: ConfigService, |
| 29 | + ) { |
| 30 | + this.auth0Url = this.configService.get<string>('auth0.url') || ''; |
| 31 | + this.clientId = this.configService.get<string>('auth0.clientId') || ''; |
| 32 | + this.clientSecret = |
| 33 | + this.configService.get<string>('auth0.clientSecret') || ''; |
| 34 | + this.audience = this.configService.get<string>('auth0.audience') || ''; |
| 35 | + |
| 36 | + if ( |
| 37 | + !this.auth0Url || |
| 38 | + !this.clientId || |
| 39 | + !this.clientSecret || |
| 40 | + !this.audience |
| 41 | + ) { |
| 42 | + this.logger.error( |
| 43 | + 'Missing required Auth0 configuration. Please check AUTH0_URL, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, and AUTH0_AUDIENCE environment variables.', |
| 44 | + ); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + async getAccessToken(): Promise<string> { |
| 49 | + // Check if we have a valid cached token |
| 50 | + if (this.tokenCache && Date.now() < this.tokenCache.expiresAt) { |
| 51 | + this.logger.debug('Using cached Auth0 token'); |
| 52 | + return this.tokenCache.token; |
| 53 | + } |
| 54 | + |
| 55 | + try { |
| 56 | + this.logger.log('Requesting new Auth0 M2M token'); |
| 57 | + |
| 58 | + const tokenUrl = this.auth0Url; // Use the full URL from config |
| 59 | + const body = { |
| 60 | + client_id: this.clientId, |
| 61 | + client_secret: this.clientSecret, |
| 62 | + audience: this.audience, |
| 63 | + grant_type: 'client_credentials', |
| 64 | + }; |
| 65 | + |
| 66 | + const response = await firstValueFrom( |
| 67 | + this.httpService.post<Auth0TokenResponse>(tokenUrl, body, { |
| 68 | + headers: { |
| 69 | + 'Content-Type': 'application/json', |
| 70 | + }, |
| 71 | + timeout: 10000, |
| 72 | + }), |
| 73 | + ); |
| 74 | + |
| 75 | + const { access_token, expires_in } = response.data; |
| 76 | + |
| 77 | + // Cache the token with a buffer (subtract 60 seconds to ensure we refresh before expiry) |
| 78 | + const expiresAt = Date.now() + (expires_in - 60) * 1000; |
| 79 | + this.tokenCache = { |
| 80 | + token: access_token, |
| 81 | + expiresAt, |
| 82 | + }; |
| 83 | + |
| 84 | + this.logger.log('Successfully obtained new Auth0 M2M token'); |
| 85 | + return access_token; |
| 86 | + } catch (error) { |
| 87 | + const err = error as Error; |
| 88 | + this.logger.error( |
| 89 | + `Failed to obtain Auth0 M2M token: ${err.message}`, |
| 90 | + err.stack, |
| 91 | + ); |
| 92 | + throw new Error('Failed to obtain Auth0 access token'); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + clearTokenCache(): void { |
| 97 | + this.logger.log('Clearing Auth0 token cache'); |
| 98 | + this.tokenCache = null; |
| 99 | + } |
| 100 | +} |
0 commit comments