-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathauth.spec.ts
589 lines (512 loc) · 17.9 KB
/
auth.spec.ts
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
import { auth, initializeApp } from 'firebase';
import { ReflectiveInjector, provide, Provider } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { Observer } from 'rxjs/Observer';
import {
addProviders,
inject
} from '@angular/core/testing';
import 'rxjs/add/operator/do';
import {
defaultFirebase,
FIREBASE_PROVIDERS,
FirebaseApp,
FirebaseAppConfig,
FirebaseAuthState,
FirebaseConfig,
AngularFireAuth,
AuthMethods,
firebaseAuthConfig,
AuthProviders,
WindowLocation
} from '../angularfire2';
import { COMMON_CONFIG } from '../test-config';
import { AuthBackend } from './auth_backend';
import { FirebaseSdkAuthBackend } from './firebase_sdk_auth_backend';
// Set providers from firebase so no firebase.auth.GoogleProvider() necessary
const {
GoogleAuthProvider,
TwitterAuthProvider,
GithubAuthProvider
} = auth;
const authMethods = [
'getRedirectResult',
'signInWithCustomToken',
'signInAnonymously',
'signInWithEmailAndPassword',
'signInWithPopup',
'signInWithRedirect',
'signInWithCredential',
'signOut',
'onAuthStateChanged',
'createUserWithEmailAndPassword',
'changeEmail',
'removeUser',
'resetPassword'
];
const firebaseUser = <firebase.User> {
uid: '12345',
providerData: [{
'displayName': 'jeffbcross',
// TODO verify this property name
providerId: 'github.com'
}]
};
const anonymouseFirebaseUser = <firebase.User> {
uid: '12345',
isAnonymous: true,
providerData: []
}
const githubCredential = {
credential: {
provider: 'github.com'
},
user: firebaseUser
};
const googleCredential = {
credential: {},
user: firebaseUser
}
const AngularFireAuthState = {
provider: 0,
auth: firebaseUser,
uid: '12345',
github: {
displayName: 'FirebaseUser',
providerId: 'github.com'
} as firebase.UserInfo
} as FirebaseAuthState;
describe('Zones', () => {
it('should call operators and subscriber in the same zone as when service was initialized', (done) => {
// Initialize the app outside of the zone, to mimick real life behavior.
var app = initializeApp(COMMON_CONFIG, 'zoneapp');
let ngZone = Zone.current.fork({
name: 'ngZone'
});
ngZone.run(() => {
var afAuth = new AngularFireAuth(new FirebaseSdkAuthBackend(app), window.location);
afAuth
.take(1)
.do(_ => {
expect(Zone.current.name).toBe('ngZone');
})
.subscribe(() => {
expect(Zone.current.name).toBe('ngZone');
done()
}, done.fail);
});
});
});
describe('FirebaseAuth', () => {
let app: firebase.app.App;
let authData: any;
let authCb: any;
let backend: AuthBackend;
let afAuth: AngularFireAuth;
let authSpy: jasmine.Spy;
let fbAuthObserver: Observer<firebase.User>;
let windowLocation: any;
beforeEach(() => {
windowLocation = {
hash: '',
search: '',
pathname:'/',
port: '',
hostname:'localhost',
host:'localhost',
protocol:'https:',
origin:'localhost',
href:'https://localhost/'
};
addProviders([
FIREBASE_PROVIDERS,
defaultFirebase(COMMON_CONFIG),
{ provide: FirebaseApp,
useFactory: (config: FirebaseAppConfig) => {
var app = initializeApp(config);
(<any>app).auth = () => authSpy;
return app;
},
deps: [FirebaseConfig]
},
{ provide: WindowLocation, useValue: windowLocation }
]);
authSpy = jasmine.createSpyObj('auth', authMethods);
authSpy['createUserWithEmailAndPassword'].and.returnValue(Promise.resolve(firebaseUser));
authSpy['signInWithPopup'].and.returnValue(Promise.resolve(googleCredential));
authSpy['signInWithRedirect'].and.returnValue(Promise.resolve(AngularFireAuthState));
authSpy['signInWithCredential'].and.returnValue(Promise.resolve(firebaseUser));
authSpy['signInAnonymously'].and.returnValue(Promise.resolve(anonymouseFirebaseUser));
authSpy['signInWithCustomToken'].and.returnValue(Promise.resolve(firebaseUser));
authSpy['signInWithEmailAndPassword'].and.returnValue(Promise.resolve(firebaseUser));
authSpy['onAuthStateChanged']
.and.callFake((obs: Observer<firebase.User>) => {
fbAuthObserver = obs;
});
authSpy['getRedirectResult'].and.returnValue(Promise.resolve(null));
inject([FirebaseApp, AngularFireAuth], (_app: firebase.app.App, _afAuth: AngularFireAuth) => {
app = _app;
afAuth = _afAuth;
authData = null;
authCb = null;
backend = new FirebaseSdkAuthBackend(app);
})();
});
afterEach(done => {
app.delete().then(done, done.fail);
});
it('should be an observable', () => {
expect(afAuth instanceof Observable).toBe(true);
});
it('should emit auth updates', (done: any) => {
let count = 0;
fbAuthObserver.next(null);
// Check that the first value is null
afAuth
.take(1)
.do((authData) => {
expect(authData).toBe(null);
setTimeout(() => fbAuthObserver.next(firebaseUser));
})
.subscribe();
// Check the 2nd value emitted from the observable
afAuth
.skip(1)
.take(1)
.do((authData) => {
expect(authData.auth).toEqual(AngularFireAuthState.auth);
})
// Subsribes on next instead of complete to ensure a value is emitted
.subscribe(null, done.fail, done);
}, 10);
describe('AuthState', () => {
it('should asynchronously load firebase auth data', (done) => {
fbAuthObserver.next(firebaseUser);
afAuth
.take(1)
.subscribe((data) => {
expect(data.auth).toEqual(AngularFireAuthState.auth);
}, done.fail, done);
});
it('should be null if user is not authed', (done) => {
fbAuthObserver.next(null);
afAuth
.take(1)
.subscribe(authData => {
expect(authData).toBe(null);
}, done.fail, done);
});
});
describe('firebaseAuthConfig', () => {
it('should return a provider', () => {
expect(firebaseAuthConfig({ method: AuthMethods.Password }).provide).toBeTruthy()
});
it('should use config in login', () => {
let config = {
method: AuthMethods.Anonymous
};
afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login();
expect(app.auth().signInAnonymously).toHaveBeenCalled();
});
it('should be overridden by login\'s arguments', () => {
let config = {
method: AuthMethods.Anonymous
};
afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login({
method: AuthMethods.Popup,
provider: AuthProviders.Google
});
var spyArgs = (<jasmine.Spy>app.auth().signInWithPopup).calls.argsFor(0)[0];
var googleProvider = new GoogleAuthProvider();
expect(app.auth().signInWithPopup).toHaveBeenCalledWith(googleProvider);
});
it('should be merged with login\'s arguments', () => {
let config = {
method: AuthMethods.Popup,
provider: AuthProviders.Google,
scope: ['email']
};
afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login({
provider: AuthProviders.Github
});
var githubProvider = new GithubAuthProvider();
githubProvider.addScope('email');
expect(app.auth().signInWithPopup).toHaveBeenCalledWith(githubProvider);
});
});
describe('createUser', () => {
let credentials = { email: '[email protected]', password: 'password' };
it('should call createUser on the app reference', () => {
afAuth.createUser(credentials);
expect(app.auth().createUserWithEmailAndPassword)
.toHaveBeenCalledWith(credentials.email, credentials.password);
});
});
describe('login', () => {
it('should reject if password is used without credentials', (done: any) => {
let config = {
method: AuthMethods.Password
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login()
.then(done.fail, done);
});
it('should reject if custom token is used without credentials', (done: any) => {
let config = {
method: AuthMethods.CustomToken
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login()
.then(done.fail, done);
});
it('should reject if oauth token is used without credentials', (done: any) => {
let config = {
method: AuthMethods.OAuthToken
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login()
.then(done.fail, done);
});
it('should reject if popup is used without a provider', (done: any) => {
let config = {
method: AuthMethods.Popup
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login()
.then(done.fail, done);
});
it('should reject if redirect is used without a provider', (done: any) => {
let config = {
method: AuthMethods.Redirect
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login()
.then(done.fail, done);
});
describe('authWithCustomToken', () => {
let options = {
method: AuthMethods.CustomToken
};
let credentials = 'myToken';
it('passes custom token to underlying method', () => {
afAuth.login(credentials, options);
expect(app.auth().signInWithCustomToken)
.toHaveBeenCalledWith('myToken');
});
it('will reject the promise if authentication fails', (done: any) => {
authSpy['signInWithCustomToken'].and.returnValue(Promise.reject('error'));
afAuth.login(credentials, options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(credentials, options)
.then(result => {
expect(result.auth).toEqual(AngularFireAuthState.auth);
})
.then(done, done.fail);
});
});
describe('authAnonymously', () => {
let options = {
method: AuthMethods.Anonymous
};
it('passes options object to underlying method', () => {
afAuth.login(options);
expect(app.auth().signInAnonymously).toHaveBeenCalled();
});
it('will reject the promise if authentication fails', (done: any) => {
authSpy['signInAnonymously'].and.returnValue(Promise.reject('myError'));
afAuth.login(options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(options)
.then(result => {
expect(result.auth).toEqual(anonymouseFirebaseUser);
})
.then(done, done.fail);
});
});
describe('authWithPassword', () => {
let options = { remember: 'default', method: AuthMethods.Password };
let credentials = { email: 'myname', password: 'password' };
it('should login with password credentials', () => {
let config = {
method: AuthMethods.Password,
provider: AuthProviders.Password
};
const credentials = {
email: '[email protected]',
password: 'supersecretpassword'
};
let afAuth = new AngularFireAuth(backend, windowLocation, config);
afAuth.login(credentials);
expect(app.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(credentials.email, credentials.password);
});
it('passes options and credentials object to underlying method', () => {
afAuth.login(credentials, options);
expect(app.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(
credentials.email,
credentials.password);
});
it('will revoke the promise if authentication fails', (done: any) => {
authSpy['signInWithEmailAndPassword'].and.returnValue(Promise.reject('myError'));
afAuth.login(credentials, options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(credentials, options)
.then(result => {
expect(result.auth).toEqual(AngularFireAuthState.auth);
})
.then(done, done.fail);
});
});
describe('authWithOAuthPopup', function() {
let options = {
method: AuthMethods.Popup,
provider: AuthProviders.Github
};
beforeEach(() => {
authSpy['signInWithPopup'].and.returnValue(Promise.resolve(githubCredential));
})
it('passes provider and options object to underlying method', () => {
let customOptions = Object.assign({}, options);
customOptions['scope'] = ['email'];
afAuth.login(customOptions);
let githubProvider = new GithubAuthProvider();
githubProvider.addScope('email');
expect(app.auth().signInWithPopup).toHaveBeenCalledWith(githubProvider);
});
it('will reject the promise if authentication fails', (done: any) => {
authSpy['signInWithPopup'].and.returnValue(Promise.reject('myError'));
afAuth.login(options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(options)
.then(result => {
expect(result.auth).toEqual(AngularFireAuthState.auth);
})
.then(done, done.fail);
});
it('should include credentials in onAuth payload after logging in', (done) => {
afAuth
.take(1)
.do((user: FirebaseAuthState) => {
expect(user.github).toBe(githubCredential.credential);
})
.subscribe(done, done.fail);
afAuth.login(options)
.then(() => {
// Calling with undefined `github` value to mimick actual Firebase value
fbAuthObserver.next(firebaseUser);
});
}, 10);
xit('should not call getRedirectResult() if location.protocol is not http or https', (done) => {
windowLocation.protocol = 'file:';
afAuth
.take(1)
.do(() => {
expect(authSpy['getRedirectResult']).not.toHaveBeenCalled();
})
.subscribe(done, done.fail);
fbAuthObserver.next(firebaseUser);
});
});
describe('authWithOAuthRedirect', () => {
const options = {
method: AuthMethods.Redirect,
provider: AuthProviders.Github
};
it('passes provider and options object to underlying method', () => {
let customOptions = Object.assign({}, options);
customOptions['scope'] = ['email'];
afAuth.login(customOptions);
let githubProvider = new GithubAuthProvider();
expect(app.auth().signInWithRedirect).toHaveBeenCalledWith(githubProvider);
});
it('will reject the promise if authentication fails', (done: any) => {
authSpy['signInWithRedirect'].and.returnValue(Promise.reject('myError'));
afAuth.login(options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(options)
.then(result => {
expect(result).toEqual(AngularFireAuthState);
})
.then(done, done.fail);
});
it('should include credentials in onAuth payload after logging in', (done) => {
authSpy['getRedirectResult'].and.returnValue(Promise.resolve(githubCredential));
afAuth
.do((user: FirebaseAuthState) => {
expect(user.github).toBe(githubCredential.credential);
})
.take(2)
.subscribe(null, done.fail, done);
afAuth.login(options)
.then(() => {
// Calling with undefined `github` value to mimick actual Firebase value
fbAuthObserver.next(firebaseUser);
})
.then(() => {
// Call it twice to make sure it caches the result
fbAuthObserver.next(firebaseUser);
});
}, 10);
});
describe('authWithOAuthToken', () => {
const options = {
method: AuthMethods.OAuthToken,
provider: AuthProviders.Github,
scope: ['email']
};
const token = 'GITHUB_TOKEN';
const credentials = (<any> GithubAuthProvider).credential(token);
it('passes provider, token, and options object to underlying method', () => {
afAuth.login(credentials, options);
expect(app.auth().signInWithCredential).toHaveBeenCalledWith(credentials);
});
it('passes provider, OAuth credentials, and options object to underlying method', () => {
let customOptions = Object.assign({}, options);
customOptions.provider = AuthProviders.Twitter;
let credentials = (<any> TwitterAuthProvider).credential('<ACCESS-TOKEN>', '<ACCESS-TOKEN-SECRET>');
afAuth.login(credentials, customOptions);
expect(app.auth().signInWithCredential).toHaveBeenCalledWith(credentials);
});
it('will reject the promise if authentication fails', (done: any) => {
authSpy['signInWithCredential'].and.returnValue(Promise.reject('myError'));
afAuth.login(credentials, options)
.then(done.fail, done);
});
it('will resolve the promise upon authentication', (done: any) => {
afAuth.login(credentials, options)
.then(result => {
expect(result.auth).toEqual(AngularFireAuthState.auth);
})
.then(done, done.fail);
});
});
describe('unauth()', () => {
it('will call unauth() on the backing ref', () => {
afAuth.logout();
expect(app.auth().signOut).toHaveBeenCalled();
});
});
describe('getAuth()', () => {
it('should return null when no user is logged in', () => {
authSpy['currentUser'] = null;
expect(afAuth.getAuth()).toBe(null);
});
it('should return authState if user is logged in', () => {
authSpy['currentUser'] = firebaseUser;
expect(afAuth.getAuth().uid).toEqual(AngularFireAuthState.uid);
})
});
});
});