Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Auth0Strategy } from './strategies/auth0.strategy';
import { RolesGuard } from './guards/roles.guard';
import { AuthFacadeService } from './services/auth-facade.service';
import { AuthOAuthService } from './services/auth-oauth.service';
import { Auth0ManagementService } from './services/auth0-management.service';
import { UserAuthRepository } from './repositories/user-auth.repository';
import { AuthRepository } from './repositories/auth.repository';
import { TokenRedisRepository } from './repositories/token-redis.repository';
Expand Down Expand Up @@ -44,7 +45,18 @@ import { TokenRedisRepository } from './repositories/token-redis.repository';
RolesGuard,
AuthFacadeService,
AuthOAuthService,
Auth0ManagementService,
],
exports: [
AuthCredentialsService,
PasswordService,
TokenService,
JwtModule,
PassportModule,
RolesGuard,
TokenRedisRepository,
AuthRepository,
Auth0ManagementService,
],
exports: [AuthCredentialsService, PasswordService, TokenService, JwtModule, PassportModule, RolesGuard],
})
export class AuthModule {}
4 changes: 4 additions & 0 deletions src/modules/auth/repositories/auth.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ export class AuthRepository extends Repository<Auth> {
relations: ['user'],
});
}

async findByUserId(userId: string): Promise<Auth | null> {
return this.findOne({ where: { userId } });
}
}
111 changes: 111 additions & 0 deletions src/modules/auth/services/auth0-management.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppLogger } from '@/common/logger/app-logger';

interface Auth0ManagementToken {
access_token: string;
expires_at: number;
}

@Injectable()
export class Auth0ManagementService {
private readonly domain: string;
private readonly clientId: string;
private readonly clientSecret: string;
private readonly audience: string;

private cachedToken: Auth0ManagementToken | null = null;

constructor(
private readonly configService: ConfigService,
private readonly logger: AppLogger,
) {
this.logger.setLoggerContext(Auth0ManagementService.name);
this.domain = this.configService.getOrThrow<string>('AUTH0_DOMAIN');
this.clientId = this.configService.getOrThrow<string>('AUTH0_CLIENT_ID');
this.clientSecret = this.configService.getOrThrow<string>('AUTH0_CLIENT_SECRET');
this.audience = `https://${this.domain}/api/v2/`;
}

async deleteUser(auth0UserId: string): Promise<void> {
const token = await this.getManagementToken();

const url = `https://${this.domain}/api/v2/users/${encodeURIComponent(auth0UserId)}`;

const response = await fetch(url, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`,
},
});

if (!response.ok && response.status !== 204) {
const body = await response.text();
this.logger.error({ auth0UserId, status: response.status, body }, 'Failed to delete user from Auth0');
throw new InternalServerErrorException('Failed to delete user from Auth0');
}

this.logger.log({ auth0UserId }, 'User deleted from Auth0 successfully');
}

async updateUser(
auth0UserId: string,
data: { given_name?: string; family_name?: string; name?: string; picture?: string },
): Promise<void> {
const token = await this.getManagementToken();

const url = `https://${this.domain}/api/v2/users/${encodeURIComponent(auth0UserId)}`;

const response = await fetch(url, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});

if (!response.ok) {
const body = await response.text();
this.logger.error({ auth0UserId, status: response.status, body }, 'Failed to update user in Auth0');
throw new InternalServerErrorException('Failed to update user in Auth0');
}

this.logger.log({ auth0UserId, data }, 'User updated in Auth0 successfully');
}

private async getManagementToken(): Promise<string> {
const now = Date.now();

if (this.cachedToken && now < this.cachedToken.expires_at) {
return this.cachedToken.access_token;
}

const response = await fetch(`https://${this.domain}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
audience: this.audience,
}),
});

if (!response.ok) {
const body = await response.text();
this.logger.error({ status: response.status, body }, 'Failed to obtain Auth0 Management token');
throw new InternalServerErrorException('Failed to obtain Auth0 Management API token');
}

const data = (await response.json()) as { access_token: string; expires_in: number };

this.cachedToken = {
access_token: data.access_token,
expires_at: now + (data.expires_in - 60) * 1000,
};

this.logger.log('Auth0 Management token obtained and cached');
return this.cachedToken.access_token;
}
}
Loading
Loading