redirect to previous state.url (#2615)

This commit is contained in:
Cilibiu Bogdan 2017-11-07 01:47:17 +02:00 committed by Eugenio Romano
parent 406b2833bb
commit 834b8a98a2
11 changed files with 127 additions and 24 deletions

View File

@ -66,7 +66,7 @@ describe('AuthGuardService BPM', () => {
return true; return true;
}; };
expect(auth.canActivate()).toBeTruthy(); expect(auth.canActivate(null, { url: '' })).toBeTruthy();
expect(router.navigate).not.toHaveBeenCalled(); expect(router.navigate).not.toHaveBeenCalled();
})) }))
); );
@ -80,9 +80,21 @@ describe('AuthGuardService BPM', () => {
return false; return false;
}; };
expect(auth.canActivate()).toBeFalsy(); expect(auth.canActivate(null, { url: '' })).toBeFalsy();
expect(router.navigate).toHaveBeenCalled(); expect(router.navigate).toHaveBeenCalled();
})) }))
); );
it('should set redirect url',
async(inject([AuthGuardBpm, Router, AuthenticationService], (auth, router, authService) => {
const state = { url: 'some-url' };
spyOn(router, 'navigate');
spyOn(authService, 'setRedirectUrl');
auth.canActivate(null , state);
expect(authService.setRedirectUrl).toHaveBeenCalledWith(state.url);
}))
);
}); });

View File

@ -29,24 +29,20 @@ export class AuthGuardBpm implements CanActivate, CanActivateChild {
constructor(private authService: AuthenticationService, private router: Router) {} constructor(private authService: AuthenticationService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// let url: string = state.url; return this.checkLogin(state.url);
return this.checkLogin();
} }
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state); return this.canActivate(route, state);
} }
checkLogin(): boolean { checkLogin(redirectUrl: string): boolean {
if (this.authService.isBpmLoggedIn()) { if (this.authService.isBpmLoggedIn()) {
return true; return true;
} }
// Store the attempted URL for redirecting this.authService.setRedirectUrl(redirectUrl);
// this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']); this.router.navigate(['/login']);
return false; return false;
} }

View File

@ -19,6 +19,7 @@ import { async, inject, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { AlfrescoApiService } from './alfresco-api.service'; import { AlfrescoApiService } from './alfresco-api.service';
import { AuthGuardEcm } from './auth-guard-ecm.service'; import { AuthGuardEcm } from './auth-guard-ecm.service';
import { AuthenticationService } from './authentication.service';
class RouterProvider { class RouterProvider {
navigate: Function = jasmine.createSpy('RouterProviderNavigate'); navigate: Function = jasmine.createSpy('RouterProviderNavigate');
@ -60,9 +61,14 @@ class AlfrescoApiServiceProvider {
} }
} }
class AuthenticationServiceProvider {
setRedirectUrl: Function = jasmine.createSpy('setRedirectUrl');
}
class TestConfig { class TestConfig {
router: any; router: any;
guard: any; guard: any;
auth: any;
private settings: any = { private settings: any = {
validateTicket: true, validateTicket: true,
@ -76,13 +82,15 @@ class TestConfig {
providers: [ providers: [
this.routerProvider, this.routerProvider,
this.alfrescoApiServiceProvider, this.alfrescoApiServiceProvider,
this.authenticationProvider,
AuthGuardEcm AuthGuardEcm
] ]
}); });
inject([ AuthGuardEcm, Router ], (guard: AuthGuardEcm, router: Router) => { inject([ AuthGuardEcm, Router, AuthenticationService ], (guard: AuthGuardEcm, router: Router, auth: AuthenticationService) => {
this.guard = guard; this.guard = guard;
this.router = router; this.router = router;
this.auth = auth;
})(); })();
} }
@ -93,6 +101,13 @@ class TestConfig {
}; };
} }
private get authenticationProvider() {
return {
provide: AuthenticationService,
useValue: new AuthenticationServiceProvider()
};
}
private get alfrescoApiServiceProvider () { private get alfrescoApiServiceProvider () {
const { validateTicket, isLoggedIn } = this.settings; const { validateTicket, isLoggedIn } = this.settings;
@ -119,7 +134,7 @@ describe('CanActivateLoggedIn', () => {
const { guard, router } = this.test; const { guard, router } = this.test;
guard.canActivate().then((activate) => { guard.canActivate(null, { url: '' }).then((activate) => {
this.activate = activate; this.activate = activate;
this.navigateSpy = router.navigate; this.navigateSpy = router.navigate;
}); });
@ -143,7 +158,7 @@ describe('CanActivateLoggedIn', () => {
const { guard, router } = this.test; const { guard, router } = this.test;
guard.canActivate().then((activate) => { guard.canActivate(null, { url: '' }).then((activate) => {
this.activate = activate; this.activate = activate;
this.navigateSpy = router.navigate; this.navigateSpy = router.navigate;
}); });
@ -167,7 +182,7 @@ describe('CanActivateLoggedIn', () => {
const { guard, router } = this.test; const { guard, router } = this.test;
guard.canActivate().then((activate) => { guard.canActivate(null, { url: '' }).then((activate) => {
this.activate = activate; this.activate = activate;
this.navigateSpy = router.navigate; this.navigateSpy = router.navigate;
}); });
@ -181,4 +196,22 @@ describe('CanActivateLoggedIn', () => {
expect(this.navigateSpy).not.toHaveBeenCalled(); expect(this.navigateSpy).not.toHaveBeenCalled();
}); });
}); });
describe('redirect url', () => {
beforeEach(async(() => {
this.test = new TestConfig({
isLoggedIn: false
});
const { guard, auth } = this.test;
guard.canActivate(null, { url: 'some-url' }).then((activate) => {
this.auth = auth;
});
}));
it('should set redirect url', () => {
expect(this.auth.setRedirectUrl).toHaveBeenCalledWith('some-url');
});
});
}); });

View File

@ -16,13 +16,14 @@
*/ */
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AlfrescoApiService } from './alfresco-api.service'; import { AlfrescoApiService } from './alfresco-api.service';
import { AuthenticationService } from './authentication.service';
@Injectable() @Injectable()
export class AuthGuardEcm implements CanActivate { export class AuthGuardEcm implements CanActivate {
constructor( constructor(
private authService: AuthenticationService,
private apiService: AlfrescoApiService, private apiService: AlfrescoApiService,
private router: Router) { private router: Router) {
} }
@ -42,9 +43,11 @@ export class AuthGuardEcm implements CanActivate {
.catch(() => false); .catch(() => false);
} }
canActivate(): Promise<boolean> { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
return this.isLoggedIn().then(isLoggedIn => { return this.isLoggedIn().then(isLoggedIn => {
if (!isLoggedIn) { if (!isLoggedIn) {
this.authService.setRedirectUrl(state.url);
this.router.navigate([ '/login' ]); this.router.navigate([ '/login' ]);
} }

View File

@ -33,6 +33,7 @@ import { AlfrescoTranslateLoader } from './translate-loader.service';
import { UserPreferencesService } from './user-preferences.service'; import { UserPreferencesService } from './user-preferences.service';
describe('AuthGuardService', () => { describe('AuthGuardService', () => {
let state;
beforeEach(async(() => { beforeEach(async(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
@ -59,6 +60,10 @@ describe('AuthGuardService', () => {
}).compileComponents(); }).compileComponents();
})); }));
beforeEach(() => {
state = { url: '' };
});
it('if the alfresco js api is logged in should canActivate be true', it('if the alfresco js api is logged in should canActivate be true',
async(inject([AuthGuard, Router, AlfrescoSettingsService, StorageService, AuthenticationService], (auth, router, settingsService, storage, authService) => { async(inject([AuthGuard, Router, AlfrescoSettingsService, StorageService, AuthenticationService], (auth, router, settingsService, storage, authService) => {
spyOn(router, 'navigate'); spyOn(router, 'navigate');
@ -67,7 +72,7 @@ describe('AuthGuardService', () => {
return true; return true;
}; };
expect(auth.canActivate()).toBeTruthy(); expect(auth.canActivate(null, state)).toBeTruthy();
expect(router.navigate).not.toHaveBeenCalled(); expect(router.navigate).not.toHaveBeenCalled();
})) }))
); );
@ -81,9 +86,21 @@ describe('AuthGuardService', () => {
return false; return false;
}; };
expect(auth.canActivate()).toBeFalsy(); expect(auth.canActivate(null, state)).toBeFalsy();
expect(router.navigate).toHaveBeenCalled(); expect(router.navigate).toHaveBeenCalled();
})) }))
); );
it('should set redirect url',
async(inject([AuthGuard, Router, AuthenticationService], (auth, router, authService) => {
state.url = 'some-url';
spyOn(router, 'navigate');
spyOn(authService, 'setRedirectUrl');
auth.canActivate(null , state);
expect(authService.setRedirectUrl).toHaveBeenCalledWith(state.url);
}))
);
}); });

View File

@ -29,24 +29,22 @@ export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthenticationService, private router: Router) {} constructor(private authService: AuthenticationService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// let url: string = state.url; const redirectUrl = state.url;
return this.checkLogin(); return this.checkLogin(redirectUrl);
} }
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state); return this.canActivate(route, state);
} }
checkLogin(): boolean { checkLogin(redirectUrl: string): boolean {
if (this.authService.isLoggedIn()) { if (this.authService.isLoggedIn()) {
return true; return true;
} }
// Store the attempted URL for redirecting this.authService.setRedirectUrl(redirectUrl);
// this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']); this.router.navigate(['/login']);
return false; return false;
} }

View File

@ -464,4 +464,10 @@ describe('AuthenticationService', () => {
}); });
}); });
}); });
it('should set/get redirectUrl', () => {
authService.setRedirectUrl('some-url');
expect(authService.getRedirectUrl()).toBe('some-url');
});
}); });

View File

@ -28,6 +28,7 @@ const REMEMBER_ME_UNTIL = 1000 * 60 * 60 * 24 * 30 ;
@Injectable() @Injectable()
export class AuthenticationService { export class AuthenticationService {
private redirectUrl: string = '';
onLogin: Subject<any> = new Subject<any>(); onLogin: Subject<any> = new Subject<any>();
onLogout: Subject<any> = new Subject<any>(); onLogout: Subject<any> = new Subject<any>();
@ -228,6 +229,14 @@ export class AuthenticationService {
return this.alfrescoApi.getInstance().bpmAuth.username; return this.alfrescoApi.getInstance().bpmAuth.username;
} }
setRedirectUrl(url: string) {
this.redirectUrl = url;
}
getRedirectUrl(): string {
return this.redirectUrl;
}
/** /**
* The method write the error in the console browser * The method write the error in the console browser
* @param error * @param error

View File

@ -19,6 +19,15 @@ import { Observable } from 'rxjs/Rx';
// TODO: should be extending AlfrescoAuthenticationService // TODO: should be extending AlfrescoAuthenticationService
export class AuthenticationMock /*extends AlfrescoAuthenticationService*/ { export class AuthenticationMock /*extends AlfrescoAuthenticationService*/ {
private redirectUrl: string = '';
setRedirectUrl(url: string) {
this.redirectUrl = url;
}
getRedirectUrl(): string {
return this.redirectUrl;
}
// TODO: real auth service returns Observable<string> // TODO: real auth service returns Observable<string>
login(username: string, password: string): Observable<{ type: string, ticket: any }> { login(username: string, password: string): Observable<{ type: string, ticket: any }> {

View File

@ -114,6 +114,17 @@ describe('LoginComponent', () => {
expect(router.navigate).toHaveBeenCalledWith([redirect]); expect(router.navigate).toHaveBeenCalledWith([redirect]);
}); });
it('should redirect to previous route state on successful login', () => {
const redirect = '/home';
component.successRoute = redirect;
authService.setRedirectUrl('redirect-url');
spyOn(router, 'navigate');
loginWithCredentials('fake-username', 'fake-password');
expect(router.navigate).toHaveBeenCalledWith(['redirect-url']);
});
it('should update user preferences upon login', (done) => { it('should update user preferences upon login', (done) => {
spyOn(userPreferences, 'setStoragePrefix').and.callThrough(); spyOn(userPreferences, 'setStoragePrefix').and.callThrough();

View File

@ -183,9 +183,18 @@ export class LoginComponent implements OnInit {
this.authService.login(values.username, values.password, this.rememberMe) this.authService.login(values.username, values.password, this.rememberMe)
.subscribe( .subscribe(
(token: any) => { (token: any) => {
const redirectUrl = this.authService.getRedirectUrl();
this.actualLoginStep = LoginSteps.Welcome; this.actualLoginStep = LoginSteps.Welcome;
this.userPreferences.setStoragePrefix(values.username); this.userPreferences.setStoragePrefix(values.username);
this.success.emit(new LoginSuccessEvent(token, values.username, values.password)); this.success.emit(new LoginSuccessEvent(token, values.username, values.password));
if (redirectUrl) {
this.authService.setRedirectUrl(null);
this.router.navigate([redirectUrl]);
return false;
}
if (this.successRoute) { if (this.successRoute) {
this.router.navigate([this.successRoute]); this.router.navigate([this.successRoute]);
} }