Guest User

Untitled

a guest
Jan 9th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. authSuccess(resp) {
  2. const response = resp.json();
  3. const expiredAt = new Date();
  4. expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
  5. response.expires_at = expiredAt.getTime();
  6. this.$localStorage.store('authenticationToken', response);
  7. if (this.refreshSubcription !== null) {
  8. // cancel previous refresh
  9. this.refreshSubcription.unsubscribe();
  10. }
  11.  
  12. // refresh token 5 seconds before expiration
  13. this.refreshSubcription = Observable
  14. .timer((response.expires_in - 5) * 1000 )
  15. .take(1)
  16. .subscribe(() => this.refresh());
  17.  
  18. return response;
  19. }
  20.  
  21. refresh() {
  22. const data = 'refresh_token=' + this.getToken().refresh_token + '&grant_type=refresh_token&scope=read%20write&' +
  23. 'client_secret=<SECRET-TOKEN>&client_id=<CLIENT-ID>';
  24. const headers = new Headers({
  25. 'Content-Type': 'application/x-www-form-urlencoded',
  26. 'Accept': 'application/json',
  27. 'Authorization': 'Bearer ' + this.getToken().access_token
  28. });
  29.  
  30. this.http
  31. .post('oauth/token', data, {headers})
  32. .map(this.authSuccess.bind(this))
  33. .subscribe();
  34. }
  35.  
  36. login(credentials): Observable<any> {
  37. const data = 'username=' + encodeURIComponent(credentials.username) + '&password=' +
  38. encodeURIComponent(credentials.password) + '&grant_type=password&scope=read%20write&' +
  39. '<SECRET-TOKEN>&client_id=<CLIENT-ID>';
  40. const headers = new Headers({
  41. 'Content-Type': 'application/x-www-form-urlencoded',
  42. 'Accept': 'application/json',
  43. 'Authorization': 'Basic ' + this.base64.encode('<CLIENT-ID>' + ':' + '<SECRET-TOKEN>')
  44. });
  45.  
  46. return this.http
  47. .post('oauth/token', data, {headers})
  48. .map(this.authSuccess.bind(this));
  49. }
  50.  
  51. logout(): Observable<any> {
  52. if (this.refreshSubcription !== null) {
  53. // cancel previous refresh
  54. this.refreshSubcription.unsubscribe();
  55. }
  56. return new Observable((observer) => {
  57. this.http.post('api/logout', {});
  58. this.$localStorage.clear('authenticationToken');
  59. observer.complete();
  60. });
  61. }
Add Comment
Please, Sign In to add comment