-
Notifications
You must be signed in to change notification settings - Fork 930
WEB-956: share auth session across tabs and preserve deep links #3598
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jonattan-infante
wants to merge
1
commit into
openMF:dev
Choose a base branch
from
jonattan-infante:WEB-956/preserve-deep-link
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /** | ||
| * Copyright since 2025 Mifos Initiative | ||
| * | ||
| * This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
| */ | ||
|
|
||
| import { TestBed } from '@angular/core/testing'; | ||
| import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router'; | ||
|
|
||
| import { AuthenticationGuard } from './authentication.guard'; | ||
| import { AuthenticationService } from './authentication.service'; | ||
|
|
||
| describe('AuthenticationGuard', () => { | ||
| let guard: AuthenticationGuard; | ||
| let authServiceMock: jest.Mocked<Pick<AuthenticationService, 'isAuthenticated' | 'logout'>>; | ||
| let routerMock: jest.Mocked<Pick<Router, 'navigate'>>; | ||
|
|
||
| const buildState = (url: string): RouterStateSnapshot => ({ url }) as RouterStateSnapshot; | ||
| const emptyRoute = {} as ActivatedRouteSnapshot; | ||
|
|
||
| beforeEach(() => { | ||
| authServiceMock = { | ||
| isAuthenticated: jest.fn(), | ||
| logout: jest.fn() | ||
| }; | ||
| routerMock = { navigate: jest.fn() }; | ||
|
|
||
| TestBed.configureTestingModule({ | ||
| providers: [ | ||
| AuthenticationGuard, | ||
| { provide: AuthenticationService, useValue: authServiceMock }, | ||
| { provide: Router, useValue: routerMock }] | ||
| }); | ||
|
|
||
| guard = TestBed.inject(AuthenticationGuard); | ||
| }); | ||
|
|
||
| it('allows the route when user is authenticated', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(true); | ||
| const result = guard.canActivate(emptyRoute, buildState('/clients')); | ||
| expect(result).toBe(true); | ||
| expect(routerMock.navigate).not.toHaveBeenCalled(); | ||
| expect(authServiceMock.logout).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('redirects to /login with returnUrl when target is a deep link', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| const result = guard.canActivate(emptyRoute, buildState('/clients/1/general')); | ||
| expect(result).toBe(false); | ||
| expect(authServiceMock.logout).toHaveBeenCalledTimes(1); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { | ||
| queryParams: { returnUrl: '/clients/1/general' }, | ||
| replaceUrl: true | ||
| }); | ||
| }); | ||
|
|
||
| it('redirects to /login WITHOUT returnUrl when target is "/" (default landing)', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| guard.canActivate(emptyRoute, buildState('/')); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { queryParams: {}, replaceUrl: true }); | ||
| }); | ||
|
|
||
| it('redirects to /login WITHOUT returnUrl when target is already /login (avoids loops)', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| guard.canActivate(emptyRoute, buildState('/login')); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { queryParams: {}, replaceUrl: true }); | ||
| }); | ||
|
|
||
| it('redirects to /login WITHOUT returnUrl when target is /login with stale params', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| guard.canActivate(emptyRoute, buildState('/login?returnUrl=/foo')); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { queryParams: {}, replaceUrl: true }); | ||
| }); | ||
|
|
||
| it('preserves complex URLs with query params and fragments', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| const target = '/loans/42?tab=schedule#repayment'; | ||
| guard.canActivate(emptyRoute, buildState(target)); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { | ||
| queryParams: { returnUrl: target }, | ||
| replaceUrl: true | ||
| }); | ||
| }); | ||
|
|
||
| it('preserves /login-history as a returnUrl (does not match the exact /login route)', () => { | ||
| authServiceMock.isAuthenticated.mockReturnValue(false); | ||
| guard.canActivate(emptyRoute, buildState('/login-history')); | ||
| expect(routerMock.navigate).toHaveBeenCalledWith(['/login'], { | ||
| queryParams: { returnUrl: '/login-history' }, | ||
| replaceUrl: true | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
191 changes: 191 additions & 0 deletions
191
src/app/core/authentication/authentication.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| /** | ||
| * Copyright since 2025 Mifos Initiative | ||
| * | ||
| * This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
| */ | ||
|
|
||
| import { TestBed } from '@angular/core/testing'; | ||
| import { HttpClient } from '@angular/common/http'; | ||
| import { OAuthService } from 'angular-oauth2-oidc'; | ||
| import { TranslateService } from '@ngx-translate/core'; | ||
| import { BehaviorSubject } from 'rxjs'; | ||
|
|
||
| import { AuthenticationService } from './authentication.service'; | ||
| import { AuthenticationInterceptor } from './authentication.interceptor'; | ||
| import { AlertService } from '../alert/alert.service'; | ||
| import { AuthMode } from './oauth.config'; | ||
| import { environment } from '../../../environments/environment'; | ||
|
|
||
| /** | ||
| * Cross-cutting tests for the storage / cross-tab behaviour added by | ||
| * WEB-956. These exercise the code paths that differ per `AuthMode` | ||
| * (Basic, OAuth2, OIDC, +2FA) without requiring a live backend. | ||
| * | ||
| * The cross-tab logout listener and the `initializeOAuthService()` | ||
| * storage choice are the parts of the fix that only fire in non-Basic | ||
| * modes; testing them here lets us prove correctness for OAuth2/OIDC | ||
| * without needing a Keycloak / Zitadel / mock-oauth2-server. | ||
| */ | ||
| describe('AuthenticationService — cross-mode storage & cross-tab logout', () => { | ||
| let oauthService: jest.Mocked< | ||
| Pick< | ||
| OAuthService, | ||
| | 'configure' | ||
| | 'setStorage' | ||
| | 'logOut' | ||
| | 'loadDiscoveryDocumentAndTryLogin' | ||
| | 'setupAutomaticSilentRefresh' | ||
| | 'events' | ||
| | 'hasValidAccessToken' | ||
| | 'getAccessToken' | ||
| | 'getRefreshToken' | ||
| | 'refreshToken' | ||
| > | ||
| >; | ||
| let interceptor: jest.Mocked< | ||
| Pick< | ||
| AuthenticationInterceptor, | ||
| 'setAuthorizationToken' | 'removeAuthorization' | 'removeTwoFactorAuthorization' | 'setTwoFactorAccessToken' | ||
| > | ||
| >; | ||
| let alertService: jest.Mocked<Pick<AlertService, 'alert' | 'alertEvent'>>; | ||
| let translate: jest.Mocked<Pick<TranslateService, 'instant'>>; | ||
| let http: jest.Mocked<Pick<HttpClient, 'post' | 'put'>>; | ||
|
|
||
| beforeEach(() => { | ||
| localStorage.clear(); | ||
| sessionStorage.clear(); | ||
| // Reset auth mode flags before each test so they don't leak between cases. | ||
| (environment.OIDC as any).oidcServerEnabled = false; | ||
| (environment.oauth as any).enabled = false; | ||
|
|
||
| oauthService = { | ||
| configure: jest.fn(), | ||
| setStorage: jest.fn(), | ||
| logOut: jest.fn(), | ||
| loadDiscoveryDocumentAndTryLogin: jest.fn().mockResolvedValue(true), | ||
| setupAutomaticSilentRefresh: jest.fn(), | ||
| events: new BehaviorSubject({ type: 'idle' }) as any, | ||
| hasValidAccessToken: jest.fn().mockReturnValue(false), | ||
| getAccessToken: jest.fn().mockReturnValue(''), | ||
| getRefreshToken: jest.fn().mockReturnValue(''), | ||
| refreshToken: jest.fn().mockResolvedValue({}) | ||
| } as any; | ||
|
|
||
| interceptor = { | ||
| setAuthorizationToken: jest.fn(), | ||
| removeAuthorization: jest.fn(), | ||
| removeTwoFactorAuthorization: jest.fn(), | ||
| setTwoFactorAccessToken: jest.fn() | ||
| } as any; | ||
|
|
||
| alertService = { | ||
| alert: jest.fn(), | ||
| alertEvent: new BehaviorSubject({} as any) | ||
| } as any; | ||
|
|
||
| translate = { | ||
| instant: jest.fn((k: string) => k) | ||
| } as any; | ||
|
|
||
| http = { | ||
| post: jest.fn(), | ||
| put: jest.fn() | ||
| } as any; | ||
|
|
||
| TestBed.configureTestingModule({ | ||
| providers: [ | ||
| AuthenticationService, | ||
| { provide: OAuthService, useValue: oauthService }, | ||
| { provide: AuthenticationInterceptor, useValue: interceptor }, | ||
| { provide: AlertService, useValue: alertService }, | ||
| { provide: TranslateService, useValue: translate }, | ||
| { provide: HttpClient, useValue: http }] | ||
| }); | ||
| }); | ||
|
|
||
| describe('initializeOAuthService — storage choice', () => { | ||
| it('uses localStorage as OAuth tokens store (independent of enableRememberMe)', async () => { | ||
| // Force non-Basic mode so initializeOAuthService runs in the constructor. | ||
| (environment.OIDC as any).oidcServerEnabled = true; | ||
| // Instantiate the service (TestBed.inject does this lazily). | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| // setStorage should be called once with localStorage in init. | ||
| const calls = oauthService.setStorage.mock.calls; | ||
| expect(calls.length).toBeGreaterThanOrEqual(1); | ||
| expect(calls[0][0]).toBe(localStorage); | ||
| }); | ||
| }); | ||
|
|
||
| describe('listenForCrossTabAuthEvents — Basic mode logout', () => { | ||
| it('clears credentials + 2FA token + headers when a logout broadcast arrives (Basic)', () => { | ||
| // Basic mode is the default — no environment overrides needed. | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| // Seed both stores to simulate a logged-in tab with 2FA. | ||
| localStorage.setItem('mifosXCredentials', JSON.stringify({ username: 'mifos', rememberMe: true })); | ||
| sessionStorage.setItem('mifosXCredentials', JSON.stringify({ username: 'mifos', rememberMe: false })); | ||
| localStorage.setItem('mifosXTwoFactorAuthenticationToken', JSON.stringify({ token: 'abc' })); | ||
| sessionStorage.setItem('mifosXTwoFactorAuthenticationToken', JSON.stringify({ token: 'abc' })); | ||
| // Mark this tab as logged-in so the listener acts on the broadcast. | ||
| (svc as any).userLoggedIn$.next(true); | ||
| (svc as any).handleCrossTabAuthEvent({ data: { type: 'logout' } }); | ||
|
|
||
| expect(interceptor.removeAuthorization).toHaveBeenCalledTimes(1); | ||
| expect(interceptor.removeTwoFactorAuthorization).toHaveBeenCalledTimes(1); | ||
| expect(localStorage.getItem('mifosXCredentials')).toBeFalsy(); | ||
| expect(sessionStorage.getItem('mifosXCredentials')).toBeFalsy(); | ||
| expect(localStorage.getItem('mifosXTwoFactorAuthenticationToken')).toBeFalsy(); | ||
| expect(sessionStorage.getItem('mifosXTwoFactorAuthenticationToken')).toBeFalsy(); | ||
| // Basic mode → MUST NOT call oauthService.logOut (no OAuth tokens to clear). | ||
| expect(oauthService.logOut).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('listenForCrossTabAuthEvents — OAuth2 / OIDC mode logout', () => { | ||
| it('additionally clears OAuth library tokens via oauthService.logOut(true) (OIDC)', () => { | ||
| (environment.OIDC as any).oidcServerEnabled = true; | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| (svc as any).userLoggedIn$.next(true); | ||
|
|
||
| (svc as any).handleCrossTabAuthEvent({ data: { type: 'logout' } }); | ||
|
|
||
| // Critical: passive tab must call logOut(true) so library-managed tokens | ||
| // (access_token / id_token / refresh_token) don't linger. | ||
| expect(oauthService.logOut).toHaveBeenCalledWith(true); | ||
| }); | ||
|
|
||
| it('additionally clears OAuth library tokens via oauthService.logOut(true) (OAuth2)', () => { | ||
| (environment.oauth as any).enabled = true; | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| (svc as any).userLoggedIn$.next(true); | ||
|
|
||
| (svc as any).handleCrossTabAuthEvent({ data: { type: 'logout' } }); | ||
|
|
||
| expect(oauthService.logOut).toHaveBeenCalledWith(true); | ||
| }); | ||
| }); | ||
|
|
||
| describe('listenForCrossTabAuthEvents — login broadcast', () => { | ||
| it('does nothing when current tab is already logged-in (avoids re-broadcast loops)', () => { | ||
| // Basic mode is the default — no environment overrides needed. | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| (svc as any).userLoggedIn$.next(true); | ||
|
|
||
| (svc as any).handleCrossTabAuthEvent({ data: { type: 'login' } }); | ||
|
|
||
| // No restoreSession side-effects when we're already logged-in. | ||
| expect(interceptor.setAuthorizationToken).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('storage envelope', () => { | ||
| it('default storage field is localStorage (no per-tab fragmentation)', () => { | ||
| // Basic mode is the default — no environment overrides needed. | ||
| const svc = TestBed.inject(AuthenticationService); | ||
| // Direct private field access via `any` — explicit cross-mode invariant. | ||
| expect((svc as any).storage).toBe(localStorage); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.