-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[DNCR-107] Add token refreshing #31
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,55 +1,74 @@ | ||
import 'rxjs/add/observable/of'; | ||
import { Injectable } from '@angular/core'; | ||
import { Observable } from 'rxjs/Observable'; | ||
import { Router } from '@angular/router'; | ||
import { LoginModel } from 'app/homepage/login'; | ||
import { CookieService } from 'angular2-cookie/core'; | ||
import { Response } from '@angular/http'; | ||
import { tokenNotExpired, AuthHttp } from 'angular2-jwt'; | ||
import 'rxjs/add/operator/toPromise'; | ||
import { tokenNotExpired, JwtHelper } from 'angular2-jwt'; | ||
import { Observable } from 'rxjs/Observable'; | ||
import * as moment from 'moment'; | ||
import 'rxjs/add/operator/do'; | ||
import { LoginModel } from 'app/homepage/login'; | ||
import { AuthHttp } from './http'; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
public KNOWN_USER = 'known_user'; | ||
private TOKEN = 'id_token'; | ||
|
||
private loggedIn = false; | ||
private storage: Storage; | ||
|
||
constructor(private router: Router, private cookies: CookieService, private http: AuthHttp) { | ||
this.storage = localStorage; | ||
this.loggedIn = tokenNotExpired(); | ||
} | ||
|
||
public login(model: LoginModel): Promise<Response> { | ||
let request = this.http.post('/api/authorize', model); | ||
request.subscribe( | ||
(response) => { | ||
this.storage.setItem(this.TOKEN, response.json().token); | ||
this.loggedIn = tokenNotExpired(); | ||
this.cookies.put(this.KNOWN_USER, 'true'); | ||
this.router.navigate(['/reception']); | ||
}, (error) => error | ||
); | ||
private static TOKEN = 'id_token'; | ||
private static KNOWN_USER = 'known_user'; | ||
private static refreshTimeoutId: any; | ||
|
||
return request.toPromise(); | ||
constructor(private cookies: CookieService, private http: AuthHttp) { | ||
this.scheduleTokenRefreshing(); | ||
} | ||
|
||
public logout() { | ||
this.http.post('/api/logout', {}).subscribe( | ||
() => { | ||
this.loggedIn = false; | ||
this.storage.removeItem(this.TOKEN); | ||
this.router.navigate(['/']); | ||
} | ||
); | ||
public static clear() { | ||
clearTimeout(AuthService.refreshTimeoutId); | ||
localStorage.removeItem(AuthService.TOKEN); | ||
} | ||
|
||
public login(model: LoginModel): Observable<Response> { | ||
return this.http.post('/api/authorize', model) | ||
.do((response) => this.saveToken(response)); | ||
} | ||
|
||
public logout(): Observable<Response> { | ||
return this.http.post('/api/logout', {}) | ||
.do(() => AuthService.clear()); | ||
} | ||
|
||
public check() { | ||
return Observable.of(this.loggedIn); | ||
public static isLoggedIn(): boolean { | ||
try { | ||
return tokenNotExpired(); | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
|
||
public isKnownUser(): boolean { | ||
return this.cookies.get(this.KNOWN_USER) === 'true'; | ||
return this.cookies.get(AuthService.KNOWN_USER) === 'true'; | ||
} | ||
|
||
private saveToken(response: Response) { | ||
localStorage.setItem(AuthService.TOKEN, response.json().token); | ||
this.cookies.put(AuthService.KNOWN_USER, 'true'); | ||
this.scheduleTokenRefreshing(); | ||
} | ||
|
||
private scheduleTokenRefreshing() { | ||
if (!AuthService.isLoggedIn()) { | ||
AuthService.clear(); | ||
return; | ||
} | ||
|
||
let token = localStorage.getItem(AuthService.TOKEN); | ||
let timeout = AuthService.getTokenTimeout(token); | ||
|
||
AuthService.refreshTimeoutId = setTimeout( | ||
() => this.http.post('/api/refresh-token', {}).subscribe((response) => this.saveToken(response)), timeout | ||
); | ||
} | ||
|
||
private static getTokenTimeout(token: string): number { | ||
let expiry = moment(new JwtHelper().getTokenExpirationDate(token)); | ||
let now = moment(); | ||
// Subtract 1 minute to be sure token is still valid | ||
return moment.duration(expiry.diff(now)).subtract(1, 'minute').asMilliseconds(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { Injectable } from '@angular/core'; | ||
import { Http, RequestOptions, Request, RequestOptionsArgs, Response } from '@angular/http'; | ||
import { AuthHttp as BasicAuthHttp, AuthConfig } from 'angular2-jwt'; | ||
import { Observable } from 'rxjs'; | ||
import 'rxjs/add/operator/do'; | ||
import { AuthService } from './auth.service'; | ||
|
||
@Injectable() | ||
export class AuthHttp extends BasicAuthHttp { | ||
constructor(options: AuthConfig, http: Http, defOpts?: RequestOptions) { | ||
super(options, http, defOpts); | ||
} | ||
|
||
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { | ||
return super.request(url, options) | ||
.catch((response: Response) => { | ||
if ([401, 403].indexOf(response.status) !== -1) { | ||
// TODO: Add notification about invalid response - logout | ||
AuthService.clear(); | ||
} | ||
if (response.status === 500) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this! till now we didn't log some 500 errors and this'll be helpful. and it's done just in one place, brilliant :). |
||
console.error(response); | ||
} | ||
return Observable.of(response); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export * from './auth-guard'; | ||
export * from './auth.service'; | ||
export * from './http'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Message to user is correct for both scenarios, but maybe error could be
auth.token_error
? seeingcreate
in error withrefresh
made me go and check error msgs. if you think it's not important you can leave it as it isThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is message also used by JWT library, I don't want to change it in any way.