/
authentication.service.ts
116 lines (89 loc) · 3.18 KB
/
authentication.service.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
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Rx";
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class AuthenticationService {
private authState: any;
private user: any;
constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase) { }
load() {
let promise = new Promise((resolve, reject) => {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth
resolve(true);
},
err => reject(err)
);
});
return promise;
}
createUserWithEmailAndPassword(name, email, password) {
let newUser = {
name: name
};
let newAuthTask = this.afAuth.auth.createUserWithEmailAndPassword(email, password);
let newUserTask = newAuthTask.then((user) => {
return this.db.object('/users/' + user.uid).set(newUser);
});
return Observable.fromPromise(newUserTask);
}
signInWithEmailAndPassword(email, password) {
let promise = this.afAuth.auth.signInWithEmailAndPassword(email, password);
return Observable.fromPromise(promise);
}
logout() {
return this.afAuth.auth.signOut();
}
retrieveUser(): any {
if(this.authenticated === undefined){
console.log('You need to authenticate first.');
return null;
}
this.user = this.db.object('/users/'+ this.userID)
.valueChanges()
.publishReplay(1)
.refCount();
return this.user;
}
get authenticated(): boolean {
return (this.authState !== null && this.authState !== undefined);
}
get userAuth(): any {
return this.authenticated ? this.authState : null;
}
get userID(): string {
return this.authenticated ? this.authState.uid : '';
}
get currentUserAnonymous(): boolean {
return this.authenticated ? this.authState.isAnonymous : false
}
get currentUserDisplayName(): string {
if (!this.authState)
return 'Guest';
if (this.currentUserAnonymous)
return 'Anonymous';
return (this.authState['displayName'] || 'User without a Name');
}
/*
signInWithGoogle(): firebase.Promise<any> {
return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then(response => {
this.db.object(`/users/${response.user.uid}`)
.subscribe(user => {
if (!user.$exists()) {
let {displayName, email, emailVerified, photoURL, uid} = response.user;
this.db.object(`/users/${response.user.uid}`).set({
displayName,
email,
emailVerified,
photoURL,
uid
})
}
});
})
.catch(err => console.log('ERRROR @ AuthService#signIn() :', err));
}
*/
}