Skip to content
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

NAS-132648 / 25.04 / query param handling for auth tokens #11080

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion src/app/core/guards/websocket-connection.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class WebSocketConnectionGuard {
private translate: TranslateService,
) {
this.wsManager.isClosed$.pipe(untilDestroyed(this)).subscribe((isClosed) => {
if (isClosed) {
if (isClosed && this.wsManager.hasOpenedOnce) {
this.resetUi();
// TODO: Test why manually changing close status is needed
// Test a shutdown function to see how UI acts when this isn't done
Expand Down
1 change: 1 addition & 0 deletions src/app/core/testing/utils/empty-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ export class EmptyAuthService {
logout = getMissingInjectionErrorFactory(AuthService.name);
refreshUser = getMissingInjectionErrorFactory(AuthService.name);
loginWithToken = getMissingInjectionErrorFactory(AuthService.name);
setQueryToken = getMissingInjectionErrorFactory(AuthService.name);
}
18 changes: 15 additions & 3 deletions src/app/pages/signin/store/signin.store.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Router } from '@angular/router';
import { ActivatedRoute, Router } from '@angular/router';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import { mockProvider } from '@ngneat/spectator/jest';
import { BehaviorSubject, firstValueFrom, of } from 'rxjs';
import { MockApiService } from 'app/core/testing/classes/mock-api.service';
import { getTestScheduler } from 'app/core/testing/utils/get-test-scheduler.utils';
import { mockCall, mockApi } from 'app/core/testing/utils/mock-api.utils';
import { mockApi, mockCall } from 'app/core/testing/utils/mock-api.utils';
import { FailoverDisabledReason } from 'app/enums/failover-disabled-reason.enum';
import { FailoverStatus } from 'app/enums/failover-status.enum';
import { LoginResult } from 'app/enums/login-result.enum';
Expand Down Expand Up @@ -66,6 +66,7 @@ describe('SigninStore', () => {
},
},
},
mockProvider(ActivatedRoute, { snapshot: { queryParamMap: { get: jest.fn(() => null) } } }),
],
});

Expand All @@ -82,6 +83,7 @@ describe('SigninStore', () => {
});
jest.spyOn(authService, 'loginWithToken').mockReturnValue(of(LoginResult.Success));
jest.spyOn(authService, 'clearAuthToken').mockReturnValue(null);
jest.spyOn(authService, 'setQueryToken').mockReturnValue(undefined);
});

describe('selectors', () => {
Expand Down Expand Up @@ -187,14 +189,24 @@ describe('SigninStore', () => {
expect(spectator.inject(Router).navigateByUrl).toHaveBeenCalledWith('/dashboard');
});

it('should not call "loginWithToken" if token is not within timeline and clear auth token', () => {
it('should not call "loginWithToken" if token is not within timeline and clear auth token and queryToken is null', () => {
isTokenWithinTimeline$.next(false);
spectator.service.init();

expect(authService.clearAuthToken).toHaveBeenCalled();
expect(authService.loginWithToken).not.toHaveBeenCalled();
expect(spectator.inject(Router).navigateByUrl).not.toHaveBeenCalled();
});

it('should call "loginWithToken" if queryToken is not null', () => {
isTokenWithinTimeline$.next(false);
const token = 'token';
const activatedRoute = spectator.inject(ActivatedRoute);
jest.spyOn(activatedRoute.snapshot.queryParamMap, 'get').mockImplementationOnce(() => token);
spectator.service.init();
expect(authService.setQueryToken).toHaveBeenCalledWith(token);
expect(authService.loginWithToken).toHaveBeenCalled();
});
});

describe('init - failover subscriptions', () => {
Expand Down
45 changes: 35 additions & 10 deletions src/app/pages/signin/store/signin.store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Inject, Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { ActivatedRoute, Router } from '@angular/router';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { ComponentStore } from '@ngrx/component-store';
import { Actions, ofType } from '@ngrx/effects';
Expand Down Expand Up @@ -68,6 +68,14 @@ export class SigninStore extends ComponentStore<SigninState> {
private failoverStatusSubscription: Subscription;
private disabledReasonsSubscription: Subscription;

private handleLoginResult = (loginResult: LoginResult): void => {
if (loginResult !== LoginResult.Success) {
this.authService.clearAuthToken();
} else {
this.handleSuccessfulLogin();
}
};

constructor(
private api: ApiService,
private translate: TranslateService,
Expand All @@ -81,6 +89,7 @@ export class SigninStore extends ComponentStore<SigninState> {
private authService: AuthService,
private updateService: UpdateService,
private actions$: Actions,
private activatedRoute: ActivatedRoute,
@Inject(WINDOW) private window: Window,
) {
super(initialState);
Expand All @@ -97,7 +106,14 @@ export class SigninStore extends ComponentStore<SigninState> {
this.updateService.hardRefreshIfNeeded(),
])),
tap(() => this.setLoadingState(false)),
switchMap(() => this.handleLoginWithToken()),
switchMap(() => {
const queryToken = this.activatedRoute.snapshot.queryParamMap.get('token');
if (queryToken) {
return this.handleLoginWithQueryToken(queryToken);
}

return this.handleLoginWithToken();
}),
));

handleSuccessfulLogin = this.effect((trigger$: Observable<void>) => trigger$.pipe(
Expand Down Expand Up @@ -239,8 +255,23 @@ export class SigninStore extends ComponentStore<SigninState> {
.subscribe((event) => this.setFailoverDisabledReasons(event.disabled_reasons));
}

private handleLoginWithQueryToken(token: string): Observable<LoginResult> {
this.authService.setQueryToken(token);

return this.authService.loginWithToken().pipe(
tap(this.handleLoginResult.bind(this)),
tapResponse(
() => {},
(error: unknown) => {
this.dialogService.error(this.errorHandler.parseError(error));
},
),
);
}

private handleLoginWithToken(): Observable<LoginResult> {
aervin marked this conversation as resolved.
Show resolved Hide resolved
return this.tokenLastUsedService.isTokenWithinTimeline$.pipe(take(1)).pipe(
return this.tokenLastUsedService.isTokenWithinTimeline$.pipe(
take(1),
filter((isTokenWithinTimeline) => {
if (!isTokenWithinTimeline) {
this.authService.clearAuthToken();
Expand All @@ -249,13 +280,7 @@ export class SigninStore extends ComponentStore<SigninState> {
return isTokenWithinTimeline;
}),
switchMap(() => this.authService.loginWithToken()),
tap((loginResult) => {
if (loginResult !== LoginResult.Success) {
this.authService.clearAuthToken();
} else {
this.handleSuccessfulLogin();
}
}),
tap(this.handleLoginResult.bind(this)),
tapResponse(
() => {},
(error: unknown) => {
Expand Down
8 changes: 4 additions & 4 deletions src/app/services/auth/auth-guard.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { WINDOW } from 'app/helpers/window.helper';
import { AuthService } from 'app/services/auth/auth.service';
Expand All @@ -20,13 +20,13 @@ export class AuthGuardService {
});
}

canActivate(_: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
canActivate({ queryParams }: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.isAuthenticated) {
return true;
}

this.window.sessionStorage.setItem('redirectUrl', state.url);
this.router.navigate(['/signin']);
this.window.sessionStorage.setItem('redirectUrl', state.url.split('?')[0]);
this.router.navigate(['/signin'], { queryParams });

return false;
}
Expand Down
8 changes: 8 additions & 0 deletions src/app/services/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@ export class AuthService {
);
}

setQueryToken(token: string | null): void {
if (!token || this.window.location.protocol !== 'https:') {
return;
}

this.token = token;
}

loginWithToken(): Observable<LoginResult> {
if (!this.token) {
return of(LoginResult.NoToken);
Expand Down
6 changes: 6 additions & 0 deletions src/app/services/websocket/websocket-handler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ export class WebSocketHandlerService {
return this.wsConnection.stream$ as Observable<IncomingApiMessage>;
}

private hasOpened = false;
get hasOpenedOnce(): boolean {
return this.hasOpened;
}

private readonly triggerNextCall$ = new Subject<void>();
private activeCalls = 0;
private readonly queuedCalls: { id: string; [key: string]: unknown }[] = [];
Expand Down Expand Up @@ -228,6 +233,7 @@ export class WebSocketHandlerService {
}

private onOpen(): void {
this.hasOpened = true;
if (this.reconnectTimerSubscription) {
this.wsConnection.close();
return;
Expand Down
5 changes: 1 addition & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import { MAT_SNACK_BAR_DEFAULT_OPTIONS, MatSnackBarConfig } from '@angular/mater
import { BrowserModule, bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import {
withPreloading,
provideRouter,
PreloadAllModules,
withComponentInputBinding,
withPreloading, provideRouter, PreloadAllModules, withComponentInputBinding,
} from '@angular/router';
import { provideEffects } from '@ngrx/effects';
import { provideRouterStore } from '@ngrx/router-store';
Expand Down
Loading