This repository was archived by the owner on Apr 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathusers.service.ts
More file actions
196 lines (178 loc) · 6.9 KB
/
users.service.ts
File metadata and controls
196 lines (178 loc) · 6.9 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
import {Injectable} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {AngularFireDatabase, AngularFireObject} from 'angularfire2/database';
import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {GoogleAnalyticsService} from './google-analytics.service';
import {FullStoryService} from './fullstory.service';
import {User} from './models/user';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class UsersService implements CanActivate {
private adminSubscription: Subscription;
private userSubscription: Subscription;
public authState: firebase.User;
public isLoggedIn: boolean = false;
public isAdmin: boolean = false;
public currentUser: User;
private userBehaviorSubject: BehaviorSubject<User>;
public firebaseUserObservable: Observable<User>;
public firebaseUser: AngularFireObject<User>;
constructor(public db: AngularFireDatabase,
private fbAuth: AngularFireAuth,
private gaService: GoogleAnalyticsService,
private fullStoryService: FullStoryService) {
this.userBehaviorSubject = new BehaviorSubject(null);
this.handleRedirect();
this.fbAuth.authState.subscribe((authState: firebase.User) => {
this.authState = authState;
if (authState) {
this.setCurrentLoggedInUser(this.authState);
} else {
this.fbAuth.auth.signInAnonymously().catch((error) => console.error(error));
}
});
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.isLoggedIn) {
// Firebase can take a couple seconds to renew tokens and get the user logged in
// Don't prompt the user to login unless Firebase wasn't able to log them back in.
setTimeout(() => {
if (!this.isLoggedIn) {
this.login();
}
}, 2000);
}
return this.isLoggedIn;
}
login(): void {
this.gaService.sendEvent('accounts', 'login');
if (this.authState && this.authState.isAnonymous) {
this.fbAuth.auth.currentUser.linkWithRedirect(new firebase.auth.GoogleAuthProvider())
.catch((error: any) => {
if (error.credential) {
this.signInWithCredential(error.credential);
} else {
console.error(`linkWithRedirect failed: ${JSON.stringify(error)}`);
this.gaService.sendEvent('accounts', 'linkWithRedirect_failure');
}
});
} else {
this.fbAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider())
.catch((error) => {
console.error(`signInWithRedirect failed: ${JSON.stringify(error)}`);
this.gaService.sendEvent('accounts', 'signInWithRedirect_failure');
});
}
}
handleRedirect(): void {
this.fbAuth.auth.getRedirectResult().then((result) => {
this.setCurrentLoggedInUser(result.user);
// As this API can be used for sign-in, linking and reauthentication,
// check the operationType to determine what triggered this redirect operation.
this.gaService.sendEvent('accounts', result.operationType);
})
.catch((error) => {
if (error.credential) {
this.signInWithCredential(error.credential);
} else if (error.code) {
console.error(`getRedirectResult failed: ${JSON.stringify(error)}`);
this.gaService.sendEvent('accounts', 'getRedirectResult_failure');
}
});
}
signInWithCredential(credential: firebase.auth.AuthCredential): void {
this.fbAuth.auth.signInWithCredential(credential)
.catch((signInError) => {
console.error(`signInWithCredential failed: ${JSON.stringify(signInError)}`);
this.gaService.sendEvent('accounts', 'signInWithCredential_failure');
});
}
private setCurrentLoggedInUser(authState: firebase.User) {
this.isLoggedIn = !!authState && !authState.isAnonymous;
this.gaService.setUserId(authState.uid);
this.fullStoryService.setUser(authState.uid,
authState.displayName || 'Anonymous', authState.email || 'anonymous@marketamplified.com');
if (!authState.isAnonymous) {
this.firebaseUser = this.db.object<User>('/users/' + authState.uid);
this.firebaseUserObservable = this.firebaseUser.valueChanges();
// Add the authData to Firebase if this is the first time the user is logging in
this.userSubscription = this.firebaseUserObservable.subscribe((data: User) => {
this.userBehaviorSubject.next(data);
if (!data || !data.provider) {
const providerData = authState.providerData[0];
this.currentUser = {
provider: providerData.providerId,
photoURL: providerData.photoURL,
displayName: providerData.displayName,
email: providerData.email,
refreshToken: authState.refreshToken,
uid: authState.uid,
providerUids: [providerData.uid]
};
this.getPermissions(this.currentUser);
this.firebaseUser.update(this.currentUser)
.then(() => {
this.gaService.sendEvent('accounts', 'creation');
})
.catch((error) => {
this.gaService.sendEvent('accounts', 'creation_failed');
console.error(`Updating user ${this.currentUser.displayName} failed: ${JSON.stringify(error)}`);
});
} else {
this.currentUser = {
provider: data.provider,
photoURL: data.photoURL,
displayName: data.displayName,
email: data.email,
refreshToken: data.refreshToken,
uid: data.uid,
providerUids: data.providerUids
};
this.getPermissions(this.currentUser);
}
});
}
}
getUser(): BehaviorSubject<User> {
return this.userBehaviorSubject;
}
updateUser(user: User): void {
this.firebaseUser.update(user).catch((error) => {
console.error(`Updating user ${this.currentUser.displayName} failed: ${error}`);
});
}
logout(): void {
this.fbAuth.auth.signOut().then(() => {
this.gaService.sendEvent('accounts', 'logout');
this.cancelSubscriptions();
this.currentUser = undefined;
this.userBehaviorSubject.next(null);
});
}
cancelSubscriptions(): void {
if (this.adminSubscription) {
this.adminSubscription.unsubscribe();
}
if (this.userSubscription) {
this.userSubscription.unsubscribe();
}
}
getPermissions(user: User) {
const isAdminObservable: Observable<any> = this.db.object('/admins/' + user.uid).valueChanges();
this.adminSubscription = isAdminObservable.subscribe(
data => {
if (data) {
this.isAdmin = true;
} else {
this.isAdmin = false;
}
},
err => {
console.error('Failed to read from ' + '/admins/' + user.uid + ': ' + err);
}
);
}
}