forked from neroniaky/angular-token
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular2-token.service.ts
423 lines (337 loc) · 12.7 KB
/
angular2-token.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
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
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import {
Http,
Response,
Headers,
Request,
RequestMethod,
RequestOptions
} from '@angular/http';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {
UserType,
AuthData,
Angular2TokenOptions
} from './angular2-token.model';
@Injectable()
export class Angular2TokenService implements CanActivate {
get currentUserType(): string {
if (this._currentUserType != null)
return this._currentUserType.name;
else
return null;
}
get currentUserData(): string {
return this._currentUserData;
}
private _options: Angular2TokenOptions;
private _currentUserType: UserType;
private _currentAuthData: AuthData;
private _currentUserData: any;
constructor(
private _http: Http,
private _activatedRoute: ActivatedRoute
) { }
canActivate() {
if (this._currentUserData)
return true;
else
return false;
}
// Inital configuration
init(options?: Angular2TokenOptions) {
let defaultOptions: Angular2TokenOptions = {
apiPath: null,
signInPath: 'auth/sign_in',
signOutPath: 'auth/sign_out',
validateTokenPath: 'auth/validate_token',
registerAccountPath: 'auth',
deleteAccountPath: 'auth',
registerAccountCallback: window.location.href,
updatePasswordPath: 'auth',
resetPasswordPath: 'auth/password',
resetPasswordCallback: window.location.href,
userTypes: null,
oAuthPaths: {
github: 'auth/github'
}
};
this._options = Object.assign(defaultOptions, options);
this._tryLoadAuthData();
}
// Register request
registerAccount(email: string, password: string, passwordConfirmation: string, userType?: string): Observable<Response> {
if (userType == null)
this._currentUserType = null;
else
this._currentUserType = this._getUserTypeByName(userType);
let body = JSON.stringify({
email: email,
password: password,
password_confirmation: passwordConfirmation,
confirm_success_url: this._options.registerAccountCallback
});
return this.post(this._constructUserPath() + this._options.registerAccountPath, body);
}
// Delete Account
deleteAccount(): Observable<Response> {
return this.delete(this._constructUserPath() + this._options.deleteAccountPath);
}
// Sign in request and set storage
signIn(email: string, password: string, userType?: string): Observable<Response> {
if (userType == null)
this._currentUserType = null;
else
this._currentUserType = this._getUserTypeByName(userType);
let body = JSON.stringify({
email: email,
password: password
});
let observ = this.post(this._constructUserPath() + this._options.signInPath, body);
observ.subscribe(res => this._currentUserData = res.json().data, error => null);
return observ;
}
signInOAuth(oAuthType: string) {
let oAuthPath: string;
if (oAuthType == 'github') {
oAuthPath = this._options.oAuthPaths.github
}
window.open(this._constructUserPath() + oAuthPath);
}
// Sign out request and delete storage
signOut(): Observable<Response> {
let observ = this.delete(this._constructUserPath() + this._options.signOutPath);
localStorage.clear();
this._currentAuthData = null;
this._currentUserType = null;
this._currentUserData = null;
return observ;
}
// Validate token request
validateToken(): Observable<Response> {
let observ = this.get(this._constructUserPath() + this._options.validateTokenPath);
observ.subscribe(res => this._currentUserData = res.json().data, error => null);
return observ;
}
// Update password request
updatePassword(password: string, passwordConfirmation: string, currentPassword?: string, userType?: string): Observable<Response> {
if (userType != null)
this._currentUserType = this._getUserTypeByName(userType);
let body: string;
if (currentPassword == null) {
body = JSON.stringify({
password: password,
password_confirmation: passwordConfirmation
});
} else {
body = JSON.stringify({
current_password: currentPassword,
password: password,
password_confirmation: passwordConfirmation
});
}
return this.put(this._constructUserPath() + this._options.updatePasswordPath, body);
}
// Reset password request
resetPassword(email: string, userType?: string): Observable<Response> {
if (userType == null)
this._currentUserType = null;
else
this._currentUserType = this._getUserTypeByName(userType);
let body = JSON.stringify({
email: email,
redirect_url: this._options.resetPasswordCallback
});
return this.post(this._constructUserPath() + this._options.resetPasswordPath, body);
}
// Standard HTTP requests
get(path: string): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Get,
url: this._constructApiPath() + path
}));
}
post(path: string, data: any): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Post,
url: this._constructApiPath() + path,
body: data
}));
}
put(path: string, data: any): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Put,
url: this._constructApiPath() + path,
body: data
}));
}
delete(path: string): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Delete,
url: this._constructApiPath() + path
}));
}
patch(path: string, data: any): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Patch,
url: this._constructApiPath() + path,
body: data
}));
}
head(path: string): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Head,
url: this._constructApiPath() + path
}));
}
options(path: string): Observable<Response> {
return this.sendHttpRequest(new RequestOptions({
method: RequestMethod.Options,
url: this._constructApiPath() + path
}));
}
// Construct and send Http request
sendHttpRequest(requestOptions: RequestOptions): Observable<Response> {
let headers: Headers;
let baseRequestOptions: RequestOptions;
let mergedRequestOptions: RequestOptions;
// Set Headers
if (this._currentAuthData != null)
headers = new Headers({
'Content-Type': 'application/json', // ToDo: Add to RequestOptions if available
'Accept': 'application/json',
'access-token': this._currentAuthData.accessToken,
'client': this._currentAuthData.client,
'expiry': this._currentAuthData.expiry,
'token-type': this._currentAuthData.tokenType,
'uid': this._currentAuthData.uid
});
else
headers = new Headers({
'Content-Type': 'application/json', // ToDo: Add to RequestOptions if available
'Accept': 'application/json'
});
// Construct Default Request Options
baseRequestOptions = new RequestOptions({
headers: headers
})
// Merge standard and custom RequestOptions
mergedRequestOptions = baseRequestOptions.merge(requestOptions);
let response = this._http.request(new Request(mergedRequestOptions)).share();
this._handleResponse(response);
return response;
}
// Check if response is complete and newer, then update storage
private _handleResponse(response: Observable<Response>) {
response.subscribe(res => {
this._parseAuthHeadersFromResponse(<any>res);
}, error => {
this._parseAuthHeadersFromResponse(<any>error);
console.log('Session Service: Error Fetching Response');
});
}
private _parseAuthHeadersFromResponse(data: any){
let headers = data.headers;
let authData: AuthData = {
accessToken: headers.get('access-token'),
client: headers.get('client'),
expiry: headers.get('expiry'),
tokenType: headers.get('token-type'),
uid: headers.get('uid')
};
this._setAuthData(authData);
}
// Try to get auth data from storage.
private _getAuthDataFromStorage() {
let authData: AuthData = {
accessToken: localStorage.getItem('accessToken'),
client: localStorage.getItem('client'),
expiry: localStorage.getItem('expiry'),
tokenType: localStorage.getItem('tokenType'),
uid: localStorage.getItem('uid')
};
if (this._checkIfComplete(authData))
this._currentAuthData = authData;
}
// Try to get auth data from url parameters.
private _getAuthDataFromParams() {
this._activatedRoute.queryParams.subscribe(queryParams => {
let authData: AuthData = {
accessToken: queryParams['token'],
client: queryParams['client_id'],
expiry: queryParams['expiry'],
tokenType: 'Bearer',
uid: queryParams['uid']
};
if (this._checkIfComplete(authData))
this._currentAuthData = authData;
});
}
// Write auth data to storage
private _setAuthData(authData: AuthData) {
if (this._checkIfComplete(authData) && this._checkIfNewer(authData)) {
this._currentAuthData = authData;
localStorage.setItem('accessToken', authData.accessToken);
localStorage.setItem('client', authData.client);
localStorage.setItem('expiry', authData.expiry);
localStorage.setItem('tokenType', authData.tokenType);
localStorage.setItem('uid', authData.uid);
if (this._currentUserType != null)
localStorage.setItem('userType', this._currentUserType.name);
}
}
// Check if auth data complete
private _checkIfComplete(authData: AuthData): boolean {
if (
authData.accessToken != null &&
authData.client != null &&
authData.expiry != null &&
authData.tokenType != null &&
authData.uid != null
) {
return true;
} else {
return false;
}
}
// Check if response token is newer
private _checkIfNewer(authData: AuthData): boolean {
if (this._currentAuthData != null)
return authData.expiry >= this._currentAuthData.expiry;
else
return true;
}
// Try to load user config from storage
private _tryLoadAuthData() {
let userType = this._getUserTypeByName(localStorage.getItem('userType'));
this._getAuthDataFromStorage();
this._getAuthDataFromParams();
if (this._currentAuthData != null)
this.validateToken();
if (userType != null)
this._currentUserType = userType;
}
// Match user config by user config name
private _getUserTypeByName(name: string): UserType {
if (name == null || this._options.userTypes == null)
return null;
return this._options.userTypes.find(
userType => userType.name === name
);
}
private _constructUserPath(): string {
if (this._currentUserType == null)
return '';
else
return this._currentUserType.path + '/';
}
private _constructApiPath(): string {
if (this._options.apiPath == null)
return '';
else
return this._options.apiPath + '/';
}
}