-
Notifications
You must be signed in to change notification settings - Fork 546
Expand file tree
/
Copy pathauth.service.spec.ts
More file actions
688 lines (613 loc) · 23.3 KB
/
auth.service.spec.ts
File metadata and controls
688 lines (613 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
import { CommonModule } from '@angular/common';
import {
TestBed,
waitForAsync,
} from '@angular/core/testing';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { APP_CONFIG } from '@dspace/config/app-config.interface';
import {
Store,
StoreModule,
} from '@ngrx/store';
import {
MockStore,
provideMockStore,
} from '@ngrx/store/testing';
import { TranslateService } from '@ngx-translate/core';
import { cold } from 'jasmine-marbles';
import {
Observable,
of,
} from 'rxjs';
import { REQUEST } from '../../../express.tokens';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { ClientCookieService } from '../cookies/client-cookie.service';
import { CookieService } from '../cookies/cookie.service';
import { CoreState } from '../core-state.model';
import { RemoteData } from '../data/remote-data';
import { EPersonDataService } from '../eperson/eperson-data.service';
import { EPerson } from '../eperson/models/eperson.model';
import { NotificationsService } from '../notification-system/notifications.service';
import { HardRedirectService } from '../services/hard-redirect.service';
import { RouteService } from '../services/route.service';
import {
NativeWindowRef,
NativeWindowService,
} from '../services/window.service';
import { ActivatedRouteStub } from '../testing/active-router.stub';
import { AuthRequestServiceStub } from '../testing/auth-request-service.stub';
import { authMethodsMock } from '../testing/auth-service.stub';
import { EPersonMock } from '../testing/eperson.mock';
import { NotificationsServiceStub } from '../testing/notifications-service.stub';
import { routeServiceStub } from '../testing/route-service.stub';
import { RouterStub } from '../testing/router.stub';
import {
SpecialGroupDataMock,
SpecialGroupDataMock$,
} from '../testing/special-group.mock';
import { getMockTranslateService } from '../testing/translate.service.mock';
import { createSuccessfulRemoteDataObject$ } from '../utilities/remote-data.utils';
import {
SetUserAsIdleAction,
UnsetUserAsIdleAction,
} from './auth.actions';
import { authReducer } from './auth.reducer';
import {
AuthService,
IMPERSONATING_COOKIE,
} from './auth.service';
import { AuthRequestService } from './auth-request.service';
import { AuthMethod } from './models/auth.method';
import { AuthStatus } from './models/auth-status.model';
import { AuthTokenInfo } from './models/auth-token-info.model';
import {
getAuthenticationToken,
isAuthenticated,
isIdle,
} from './selectors';
describe('AuthService test', () => {
const mockEpersonDataService: any = {
findByHref(href: string): Observable<RemoteData<EPerson>> {
return createSuccessfulRemoteDataObject$(EPersonMock);
},
};
let mockStore: MockStore<CoreState>;
let authService: AuthService;
let routeServiceMock: RouteService;
let authRequest;
let window;
let routerStub;
let routeStub;
let storage: CookieService;
let token: AuthTokenInfo;
let authenticatedState;
let unAuthenticatedState;
let idleState;
let linkService;
let hardRedirectService;
const dateOfTest = Date.now();
const envConfig = {
auth: {
rest: {
timeLeftBeforeTokenRefresh: 20000, // 20 sec
},
},
};
const initialState: any = {
core: {
auth: {
authenticated: true,
loaded: true,
loading: false,
authToken: undefined,
user: undefined,
idle: false,
},
},
};
const AuthStatusWithSpecialGroups = Object.assign(new AuthStatus(), {
uuid: 'test',
authenticated: true,
okay: true,
specialGroups: SpecialGroupDataMock$,
});
function init() {
window = new NativeWindowRef();
routerStub = new RouterStub();
token = new AuthTokenInfo('test_token');
token.expires = dateOfTest + (1000 * 60 * 60);
authenticatedState = {
authenticated: true,
loaded: true,
loading: false,
authToken: token,
user: EPersonMock,
idle: false,
};
unAuthenticatedState = {
authenticated: false,
loaded: true,
loading: false,
authToken: undefined,
user: undefined,
idle: false,
};
idleState = {
authenticated: true,
loaded: true,
loading: false,
authToken: token,
user: EPersonMock,
idle: true,
};
authRequest = new AuthRequestServiceStub();
routeStub = new ActivatedRouteStub();
linkService = {
resolveLinks: {},
};
hardRedirectService = jasmine.createSpyObj('hardRedirectService', ['redirect']);
spyOn(linkService, 'resolveLinks').and.returnValue({ authenticated: true, eperson: of({ payload: {} }) });
}
describe('', () => {
beforeEach(() => {
init();
initialState.core.auth = authenticatedState;
TestBed.configureTestingModule({
imports: [
CommonModule,
StoreModule.forRoot({ authReducer }, {
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
},
}),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthRequestService, useValue: authRequest },
{ provide: NativeWindowService, useValue: window },
{ provide: REQUEST, useValue: {} },
{ provide: APP_CONFIG, useValue: envConfig },
{ provide: Router, useValue: routerStub },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: EPersonDataService, useValue: mockEpersonDataService },
{ provide: HardRedirectService, useValue: hardRedirectService },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: TranslateService, useValue: getMockTranslateService() },
CookieService,
AuthService,
],
});
authService = TestBed.inject(AuthService);
mockStore = TestBed.inject(Store) as MockStore<CoreState>;
mockStore.setState(initialState);
});
it('should return the authentication status object when user credentials are correct', () => {
authService.authenticate('user', 'password').subscribe((status: AuthStatus) => {
expect(status).toBeDefined();
});
});
it('should throw an error when user credentials are wrong', () => {
expect(authService.authenticate.bind(null, 'user', 'passwordwrong')).toThrow();
});
it('should return the authenticated user href when user token is valid', () => {
authService.authenticatedUser(new AuthTokenInfo('test_token')).subscribe((userHref: string) => {
expect(userHref).toBeDefined();
});
});
it('should return the authenticated user', () => {
authService.retrieveAuthenticatedUserByHref(EPersonMock._links.self.href).subscribe((user: EPerson) => {
expect(user).toBeDefined();
});
});
it('should throw an error when user credentials when user token is not valid', () => {
expect(authService.authenticatedUser.bind(null, new AuthTokenInfo('test_token_expired'))).toThrow();
});
it('should return a valid refreshed token', () => {
authService.refreshAuthenticationToken(new AuthTokenInfo('test_token')).subscribe((tokenState: AuthTokenInfo) => {
expect(tokenState).toBeDefined();
});
});
it('should throw an error when is not possible to refresh token', () => {
expect(authService.refreshAuthenticationToken.bind(null, new AuthTokenInfo('test_token_expired'))).toThrow();
});
it('should return true when logout succeeded', () => {
authService.logout().subscribe((status: boolean) => {
expect(status).toBe(true);
});
});
it('should throw an error when logout is not succeeded', () => {
expect(authService.logout.bind(null)).toThrow();
});
it('should return the authentication status object to check an Authentication Cookie', () => {
authService.checkAuthenticationCookie().subscribe((status: AuthStatus) => {
expect(status).toBeDefined();
});
});
it('should return the authentication methods available', () => {
const authStatus = new AuthStatus();
authService.retrieveAuthMethodsFromAuthStatus(authStatus).subscribe((authMethods: AuthMethod[]) => {
expect(authMethods).toBeDefined();
expect(authMethods.length).toBe(0);
});
authStatus.authMethods = authMethodsMock;
authService.retrieveAuthMethodsFromAuthStatus(authStatus).subscribe((authMethods: AuthMethod[]) => {
expect(authMethods).toBeDefined();
expect(authMethods.length).toBe(2);
});
});
describe('setIdle true', () => {
it('store should dispatch SetUserAsIdleAction', () => {
spyOn(mockStore, 'dispatch');
authService.setIdle(true);
expect(mockStore.dispatch as jasmine.Spy).toHaveBeenCalledWith(new SetUserAsIdleAction());
});
});
describe('setIdle false', () => {
it('store should dispatch UnsetUserAsIdleAction', () => {
spyOn(mockStore, 'dispatch');
authService.setIdle(false);
expect(mockStore.dispatch as jasmine.Spy).toHaveBeenCalledWith(new UnsetUserAsIdleAction());
});
});
});
describe('', () => {
beforeEach(waitForAsync(() => {
init();
initialState.core.auth = authenticatedState;
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({ authReducer }, {
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
},
}),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthRequestService, useValue: authRequest },
{ provide: NativeWindowService, useValue: window },
{ provide: REQUEST, useValue: {} },
{ provide: APP_CONFIG, useValue: envConfig },
{ provide: Router, useValue: routerStub },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: EPersonDataService, useValue: mockEpersonDataService },
{ provide: HardRedirectService, useValue: hardRedirectService },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: TranslateService, useValue: getMockTranslateService() },
CookieService,
AuthService,
],
}).compileComponents();
}));
beforeEach(() => {
mockStore = TestBed.inject(MockStore);
authService = TestBed.inject(AuthService);
mockStore.overrideSelector(getAuthenticationToken, token);
mockStore.overrideSelector(isAuthenticated, true);
mockStore.refreshState();
storage = (authService as any).storage;
storage.get = jasmine.createSpy().and.returnValue(null);
});
it('should return true when user is logged in', (done) => {
authService.isAuthenticated().subscribe((status: boolean) => {
expect(status).toBe(true);
done();
});
});
it('should return the shortlived token when user is logged in', (done) => {
authService.getShortlivedToken().subscribe((shortlivedToken: string) => {
expect(shortlivedToken).toEqual(authRequest.mockShortLivedToken);
done();
});
});
it('should return token object when it is valid', (done) => {
authService.hasValidAuthenticationToken().subscribe((tokenState: AuthTokenInfo) => {
expect(tokenState).toEqual(token);
done();
});
});
it('should return a token object', () => {
const result = authService.getToken();
expect(result).toEqual(token);
});
it('should return false when token is not expired', () => {
const result = authService.isTokenExpired();
expect(result).toBe(false);
});
it('should return true when authentication is loaded', (done) => {
authService.isAuthenticationLoaded().subscribe((status: boolean) => {
expect(status).toBe(true);
done();
});
});
it('isUserIdle should return false when user is not yet idle', (done) => {
authService.isUserIdle().subscribe((status: boolean) => {
expect(status).toBe(false);
done();
});
});
});
describe('', () => {
beforeEach(waitForAsync(() => {
init();
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({ authReducer }, {
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
},
}),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthRequestService, useValue: authRequest },
{ provide: NativeWindowService, useValue: window },
{ provide: REQUEST, useValue: {} },
{ provide: APP_CONFIG, useValue: envConfig },
{ provide: Router, useValue: routerStub },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: EPersonDataService, useValue: mockEpersonDataService },
{ provide: HardRedirectService, useValue: hardRedirectService },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: TranslateService, useValue: getMockTranslateService() },
{ provide: RemoteDataBuildService, useValue: linkService },
CookieService,
AuthService,
ClientCookieService,
],
}).compileComponents();
}));
beforeEach(() => {
mockStore = TestBed.inject(MockStore);
authService = TestBed.inject(AuthService);
storage = (authService as any).storage;
routeServiceMock = TestBed.inject(RouteService);
routerStub = TestBed.inject(Router);
storage.get = jasmine.createSpy().and.returnValue(null);
storage.remove = jasmine.createSpy().and.returnValue(null);
storage.set = jasmine.createSpy().and.returnValue(null);
const expiredToken: AuthTokenInfo = new AuthTokenInfo('test_token_expired');
expiredToken.expires = dateOfTest - (1000 * 60 * 60);
mockStore.overrideSelector(getAuthenticationToken, expiredToken);
mockStore.refreshState();
});
it('should throw false when token is not valid', () => {
expect(authService.hasValidAuthenticationToken.bind(null)).toThrow();
});
it('should return true when token is expired', () => {
const result = authService.isTokenExpired();
expect(result).toBe(true);
});
it('should save token into storage', () => {
authService.storeToken(token);
expect(storage.set).toHaveBeenCalled();
});
it('should remove token from storage', () => {
authService.removeToken();
expect(storage.remove).toHaveBeenCalled();
});
it('should redirect to reload with redirect url', () => {
authService.navigateToRedirectUrl('/collection/123');
// Reload with redirect URL set to /collection/123
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*\\?redirect=' + encodeURIComponent('/collection/123'))));
});
it('should redirect to reload with /home', () => {
authService.navigateToRedirectUrl('/home');
// Reload with redirect URL set to /home
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*\\?redirect=' + encodeURIComponent('/home'))));
});
it('should redirect to regular reload and not to /login', () => {
authService.navigateToRedirectUrl('/login');
// Reload without a redirect URL
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$')));
});
it('should redirect to regular reload when no redirect url is found', () => {
authService.navigateToRedirectUrl(undefined);
// Reload without a redirect URL
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$')));
});
describe('impersonate', () => {
const userId = 'testUserId';
beforeEach(() => {
spyOn(authService, 'refreshAfterLogout');
authService.impersonate(userId);
});
it('should impersonate user', () => {
expect(storage.set).toHaveBeenCalledWith(IMPERSONATING_COOKIE, userId);
});
it('should call refreshAfterLogout', () => {
expect(authService.refreshAfterLogout).toHaveBeenCalled();
});
});
describe('stopImpersonating', () => {
beforeEach(() => {
authService.stopImpersonating();
});
it('should impersonate user', () => {
expect(storage.remove).toHaveBeenCalledWith(IMPERSONATING_COOKIE);
});
});
describe('stopImpersonatingAndRefresh', () => {
beforeEach(() => {
spyOn(authService, 'refreshAfterLogout');
authService.stopImpersonatingAndRefresh();
});
it('should impersonate user', () => {
expect(storage.remove).toHaveBeenCalledWith(IMPERSONATING_COOKIE);
});
it('should call refreshAfterLogout', () => {
expect(authService.refreshAfterLogout).toHaveBeenCalled();
});
});
describe('getImpersonateID', () => {
beforeEach(() => {
authService.getImpersonateID();
});
it('should impersonate user', () => {
expect(storage.get).toHaveBeenCalledWith(IMPERSONATING_COOKIE);
});
});
describe('isImpersonating', () => {
const userId = 'testUserId';
let result: boolean;
describe('when the cookie doesn\'t contain a value', () => {
beforeEach(() => {
result = authService.isImpersonating();
});
it('should return false', () => {
expect(result).toBe(false);
});
});
describe('when the cookie contains a value', () => {
beforeEach(() => {
storage.get = jasmine.createSpy().and.returnValue(userId);
result = authService.isImpersonating();
});
it('should return true', () => {
expect(result).toBe(true);
});
});
});
describe('isImpersonatingUser', () => {
const userId = 'testUserId';
let result: boolean;
describe('when the cookie doesn\'t contain a value', () => {
beforeEach(() => {
result = authService.isImpersonatingUser(userId);
});
it('should return false', () => {
expect(result).toBe(false);
});
});
describe('when the cookie contains the right value', () => {
beforeEach(() => {
storage.get = jasmine.createSpy().and.returnValue(userId);
result = authService.isImpersonatingUser(userId);
});
it('should return true', () => {
expect(result).toBe(true);
});
});
describe('when the cookie contains the wrong value', () => {
beforeEach(() => {
storage.get = jasmine.createSpy().and.returnValue('wrongValue');
result = authService.isImpersonatingUser(userId);
});
it('should return false', () => {
expect(result).toBe(false);
});
});
});
describe('refreshAfterLogout', () => {
it('should call navigateToRedirectUrl with no url', () => {
spyOn(authService as any, 'navigateToRedirectUrl').and.stub();
authService.refreshAfterLogout();
expect((authService as any).navigateToRedirectUrl).toHaveBeenCalled();
});
});
describe('getSpecialGroupsFromAuthStatus', () => {
beforeEach(() => {
spyOn(authRequest, 'getRequest').and.returnValue(createSuccessfulRemoteDataObject$(AuthStatusWithSpecialGroups));
});
it('should call navigateToRedirectUrl with no url', () => {
const expectRes = cold('(a|)', {
a: SpecialGroupDataMock,
});
expect(authService.getSpecialGroupsFromAuthStatus()).toBeObservable(expectRes);
});
});
});
describe('when user is not logged in', () => {
beforeEach(waitForAsync(() => {
init();
initialState.core.auth = unAuthenticatedState;
spyOn(authRequest, 'getShortlivedToken').and.returnValue(of(null));
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({ authReducer }, {
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
},
}),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthRequestService, useValue: authRequest },
{ provide: NativeWindowService, useValue: window },
{ provide: REQUEST, useValue: {} },
{ provide: APP_CONFIG, useValue: envConfig },
{ provide: Router, useValue: routerStub },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: EPersonDataService, useValue: mockEpersonDataService },
{ provide: HardRedirectService, useValue: hardRedirectService },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: TranslateService, useValue: getMockTranslateService() },
{ provide: RemoteDataBuildService, useValue: linkService },
CookieService,
AuthService,
],
}).compileComponents();
authService = TestBed.inject(AuthService);
}));
it('should return null for the shortlived token', () => {
authService.getShortlivedToken().subscribe((shortlivedToken: string) => {
expect(shortlivedToken).toBeNull();
});
});
});
describe('when user is idle', () => {
beforeEach(waitForAsync(() => {
init();
initialState.core.auth = idleState;
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({ authReducer }, {
runtimeChecks: {
strictStateImmutability: false,
strictActionImmutability: false,
},
}),
],
providers: [
provideMockStore({ initialState }),
{ provide: AuthRequestService, useValue: authRequest },
{ provide: NativeWindowService, useValue: window },
{ provide: REQUEST, useValue: {} },
{ provide: APP_CONFIG, useValue: envConfig },
{ provide: Router, useValue: routerStub },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: EPersonDataService, useValue: mockEpersonDataService },
{ provide: HardRedirectService, useValue: hardRedirectService },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: TranslateService, useValue: getMockTranslateService() },
{ provide: RemoteDataBuildService, useValue: linkService },
CookieService,
AuthService,
],
}).compileComponents();
}));
beforeEach(() => {
mockStore = TestBed.inject(MockStore);
authService = TestBed.inject(AuthService);
mockStore.overrideSelector(isIdle, true);
mockStore.refreshState();
});
it('isUserIdle should return true when user is idle', () => {
authService.isUserIdle().subscribe((status: boolean) => {
expect(status).toBe(true);
});
});
});
});