{ "version": 3, "sources": ["apps/business-center-client/src/app/auth.service.ts"], "sourcesContent": ["import { HttpClient, HttpHeaders } from '@angular/common/http';\nimport { computed, inject, Injectable } from '@angular/core';\nimport { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';\nimport { Router } from '@angular/router';\nimport { Capacitor } from '@capacitor/core';\nimport { SessionService } from '@galaxy/core';\nimport { BasePersona, IAMService as IAMV1Service, PersonaType } from '@vendasta/iam';\nimport { IAMService as IAMV2Service, UserIdentifier } from '@vendasta/iamv2';\nimport { AuthActions, AuthService as CapacitorAuthService } from 'ionic-appauth';\nimport jwtDecode from 'jwt-decode';\nimport { catchError, filter, firstValueFrom, map, Observable, of, shareReplay, switchMap } from 'rxjs';\nimport { environment, partnerId } from '../globals';\n\nexport { User } from '@vendasta/iamv2';\n\nexport interface JWT {\n iss: string;\n exp?: number;\n sub?: string;\n temporary_subject?: {\n type: string;\n namespace?: string;\n };\n impersonatee?: string;\n user_id?: string;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class AuthService {\n private readonly httpClient = inject(HttpClient);\n private readonly capacitorAuthService = inject(CapacitorAuthService);\n private readonly router = inject(Router);\n\n readonly sessionId = this.sessionService.getSessionIdSignal();\n readonly sessionData = computed(() => this.decodeJWT(this.sessionId()));\n readonly isAuthed = computed(() => this.tokenIsValid(this.sessionData()));\n readonly isInPreviewMode = computed(() => !!this.sessionData()?.temporary_subject);\n readonly impersonatee = computed(() => this.sessionData()?.impersonatee);\n readonly isImpersonating = computed(() => !!this.impersonatee());\n readonly userId = computed(() => this.sessionData()?.user_id);\n readonly effectiveUserId = computed(() => (this.isImpersonating() ? this.impersonatee() : this.userId()));\n\n // Note - the temporary subject represents a user that HAS NOT logged-in. The user represented by the temporary\n // subject is real, but the user's identity HAS NOT been confirmed, so the temporary session SHOULD NOT be trusted and\n // SHOULD be used cautiously.\n private temporarySubject$ = this.getLoggedInSubject(PersonaType.account_group).pipe(\n catchError(() => of(null)),\n shareReplay({ refCount: true, bufferSize: 1 }),\n );\n temporarySubjectEmail$: Observable = this.temporarySubject$.pipe(\n map((subject) => (subject ? subject?.email : null)),\n );\n temporarySubjectUserId$: Observable = this.temporarySubject$.pipe(\n map((subject) => (subject ? subject?.userId : null)),\n );\n\n smbSubjectId$ = this.getLoggedInSubject(PersonaType.smb).pipe(\n catchError(() => of(null)),\n map((subject) => subject?.subjectId),\n shareReplay({ refCount: true, bufferSize: 1 }),\n );\n\n readonly currentUser$ = this.sessionService.getSessionId().pipe(\n filter((sessionId) => !!sessionId),\n switchMap((token) => this.iamV2.getUser(new UserIdentifier({ token })).pipe(catchError(() => of(null)))),\n shareReplay(1),\n );\n readonly currentUser = toSignal(this.currentUser$);\n readonly email = computed(() => this.currentUser()?.email);\n\n constructor(\n private iamV1: IAMV1Service,\n private iamV2: IAMV2Service,\n private sessionService: SessionService,\n ) {\n this.capacitorAuthService.events$\n .pipe(\n takeUntilDestroyed(),\n filter((e) => e.action === AuthActions.RefreshFailed),\n )\n .subscribe(() => {\n if (Capacitor.isNativePlatform()) {\n // failed to refresh token, redirect to login\n this.router.navigateByUrl('/landing');\n }\n });\n }\n\n async login(email: string, password: string) {\n const iamSession = await firstValueFrom(this.iamV1.login(email, password, null, partnerId));\n this.sessionService.setSessionId(iamSession);\n if (!Capacitor.isNativePlatform()) {\n await firstValueFrom(this.createVBCSession(iamSession, partnerId));\n }\n }\n\n // refreshAccessToken will refresh the app's access token if it is expired.\n // This method can only be used within a Capacitor app since access tokens are stored in the native storage.\n async refreshAccessToken(): Promise {\n if (!Capacitor.isNativePlatform() || this.tokenIsValid(this.sessionData())) return;\n await this.capacitorAuthService.refreshToken();\n const token = await firstValueFrom(this.capacitorAuthService.token$);\n this.sessionService.setSessionId(token.accessToken);\n }\n\n private decodeJWT(jwt: string): JWT | null {\n if (!jwt) {\n return null;\n }\n try {\n return jwtDecode(jwt);\n } catch (err) {\n console.error('Error decoding JWT', err);\n }\n return null;\n }\n\n private tokenIsValid(token: JWT): boolean {\n return (\n !!token && token.iss === `https://iam-${environment}.apigateway.co` && new Date() < new Date(token.exp * 1000)\n );\n }\n\n private getLoggedInSubject(personaType: PersonaType, partnerId?: string): Observable {\n return this.sessionService\n .getSessionId()\n .pipe(switchMap((sessionId: string | null) => this.iamV1.getSubjectBySession(sessionId, personaType, partnerId)));\n }\n\n public createVBCSession(iamSession: string, partnerId = 'VUNI') {\n const headers = new HttpHeaders({\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n });\n return this.httpClient.post('/ajax/v1/create-session/', `sessionId=${iamSession}&partnerId=${partnerId}`, {\n headers: headers,\n });\n }\n}\n"], "mappings": "4kBAAA,IA4BaA,GA5BbC,EAAAC,EAAA,KAAAC,IACAC,IACAC,IACAC,IACAC,IAEAC,IACAC,IACAC,IACAC,IACAC,IACAC,oBAiBab,IAAW,IAAA,CAAlB,MAAOA,CAAW,CA0CtBc,YACUC,EACAC,EACAC,EAA8B,CAF9B,KAAAF,MAAAA,EACA,KAAAC,MAAAA,EACA,KAAAC,eAAAA,EA5CO,KAAAC,WAAaC,EAAOC,CAAU,EAC9B,KAAAC,qBAAuBF,EAAOG,CAAoB,EAClD,KAAAC,OAASJ,EAAOK,CAAM,EAE9B,KAAAC,UAAY,KAAKR,eAAeS,mBAAkB,EAClD,KAAAC,YAAcC,EAAS,IAAM,KAAKC,UAAU,KAAKJ,UAAS,CAAE,CAAC,EAC7D,KAAAK,SAAWF,EAAS,IAAM,KAAKG,aAAa,KAAKJ,YAAW,CAAE,CAAC,EAC/D,KAAAK,gBAAkBJ,EAAS,IAAM,CAAC,CAAC,KAAKD,YAAW,GAAIM,iBAAiB,EACxE,KAAAC,aAAeN,EAAS,IAAM,KAAKD,YAAW,GAAIO,YAAY,EAC9D,KAAAC,gBAAkBP,EAAS,IAAM,CAAC,CAAC,KAAKM,aAAY,CAAE,EACtD,KAAAE,OAASR,EAAS,IAAM,KAAKD,YAAW,GAAIU,OAAO,EACnD,KAAAC,gBAAkBV,EAAS,IAAO,KAAK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XzG,EAAW0G,UAAAC,WADE,MAAM,CAAA,CAAA,SACnB3G,CAAW,GAAA", "names": ["AuthService", "init_auth_service", "__esmMin", "init_http", "init_core", "init_rxjs_interop", "init_router", "init_dist", "init_vendasta_iam", "init_vendasta_iamv2", "init_lib", "init_jwt_decode_esm", "init_esm", "init_globals", "constructor", "iamV1", "iamV2", "sessionService", "httpClient", "inject", "HttpClient", "capacitorAuthService", "CapacitorAuthService", "router", "Router", "sessionId", "getSessionIdSignal", "sessionData", "computed", "decodeJWT", "isAuthed", "tokenIsValid", "isInPreviewMode", "temporary_subject", "impersonatee", "isImpersonating", "userId", "user_id", "effectiveUserId", "temporarySubject$", "getLoggedInSubject", "PersonaType", "account_group", "pipe", "catchError", "of", "shareReplay", "refCount", "bufferSize", "temporarySubjectEmail$", "map", "subject", "email", "temporarySubjectUserId$", "smbSubjectId$", "smb", "subjectId", "currentUser$", "getSessionId", "filter", "switchMap", "token", "getUser", "UserIdentifier", "currentUser", "toSignal", "events$", "takeUntilDestroyed", "e", "action", "AuthActions", "RefreshFailed", "subscribe", "Capacitor", "isNativePlatform", "navigateByUrl", "login", "password", "__async", "iamSession", "firstValueFrom", "partnerId", "setSessionId", "createVBCSession", "refreshAccessToken", "refreshToken", "token$", "accessToken", "jwt", "jwtDecode", "err", "console", "error", "iss", "environment", "Date", "exp", "personaType", "getSubjectBySession", "headers", "HttpHeaders", "post", "\u0275\u0275inject", "IAMService", "SessionService", "factory", "\u0275fac", "providedIn"] }