From abe88e4261126b8d0348d94e2b630cd8ab66bfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Sat, 20 Dec 2025 12:48:22 +0100 Subject: [PATCH] Refactor: Extract OIDC linking logic into a separate method for better readability and maintainability --- apps/api/src/app/auth/auth.controller.ts | 74 ++++++++++++++---------- 1 file changed, 44 insertions(+), 30 deletions(-) diff --git a/apps/api/src/app/auth/auth.controller.ts b/apps/api/src/app/auth/auth.controller.ts index 7af6863a3..620bf314a 100644 --- a/apps/api/src/app/auth/auth.controller.ts +++ b/apps/api/src/app/auth/auth.controller.ts @@ -129,36 +129,12 @@ export class AuthController { const rootUrl = this.configurationService.get('ROOT_URL'); if (linkState) { - try { - await this.authService.linkOidcToUser({ - thirdPartyId, - userId: linkState.userId - }); - - response.redirect( - `${rootUrl}/${DEFAULT_LANGUAGE_CODE}/account?linkSuccess=true` - ); - } catch (error) { - const errorMessage = - error instanceof Error ? error.message : 'Unknown error'; - Logger.error( - `OIDC callback: Link failed - ${errorMessage}`, - 'AuthController' - ); - - let errorCode = 'unknown'; - if (error instanceof ConflictException) { - errorCode = error.message.includes('token authentication') - ? 'invalid-provider' - : 'already-linked'; - } else if (error instanceof NotFoundException) { - errorCode = 'invalid-session'; - } - - response.redirect( - `${rootUrl}/${DEFAULT_LANGUAGE_CODE}/account?linkError=${errorCode}` - ); - } + await this.handleOidcLinkFlow( + thirdPartyId, + linkState.userId, + rootUrl, + response + ); return; } @@ -208,4 +184,42 @@ export class AuthController { ); } } + + private async handleOidcLinkFlow( + thirdPartyId: string, + userId: string, + rootUrl: string, + response: Response + ): Promise { + try { + await this.authService.linkOidcToUser({ + thirdPartyId, + userId + }); + + response.redirect( + `${rootUrl}/${DEFAULT_LANGUAGE_CODE}/account?linkSuccess=true` + ); + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : 'Unknown error'; + Logger.error( + `OIDC callback: Link failed - ${errorMessage}`, + 'AuthController' + ); + + let errorCode = 'unknown'; + if (error instanceof ConflictException) { + errorCode = error.message.includes('token authentication') + ? 'invalid-provider' + : 'already-linked'; + } else if (error instanceof NotFoundException) { + errorCode = 'invalid-session'; + } + + response.redirect( + `${rootUrl}/${DEFAULT_LANGUAGE_CODE}/account?linkError=${errorCode}` + ); + } + } }