-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(playground): automatic refresh token (#658)
This can be played in the playground with `NbAuthPasswordStrategy` as well, just replace in the ** playground** `auth-module.ts`: ``` login: { strategy: 'password', ...} ``` by ``` login: { strategy: 'email', ...} ```
- Loading branch information
1 parent
3a708dd
commit b4fc624
Showing
11 changed files
with
299 additions
and
35 deletions.
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 |
---|---|---|
@@ -0,0 +1,46 @@ | ||
function b64decode(str) { | ||
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; | ||
var output = ''; | ||
|
||
str = String(str).replace(/=+$/, ''); | ||
|
||
if (str.length % 4 === 1) { | ||
console.error("'atob' failed: The string to be decoded is not correctly encoded."); | ||
} | ||
|
||
for ( | ||
// initialize result and counters | ||
var bc=0, bs, buffer, idx= 0; | ||
// get next character | ||
buffer = str.charAt(idx++); | ||
// character found in table? initialize bit storage and add its ascii value; | ||
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, | ||
// and if not first of each 4 characters, | ||
// convert the first 8 bits to one ascii character | ||
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 | ||
) { | ||
// try to find character in table (0-63, not found => -1) | ||
buffer = chars.indexOf(buffer); | ||
} | ||
return output; | ||
} | ||
|
||
function b64DecodeUnicode(str) { | ||
return decodeURIComponent(Array.prototype.map.call(b64decode(str), function(c) { | ||
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); | ||
}).join('')); | ||
} | ||
|
||
module.exports.urlBase64Decode = function (str) { | ||
var output = str.replace(/-/g, '+').replace(/_/g, '/'); | ||
switch (output.length % 4) { | ||
case 0: { break; } | ||
case 2: { output += '=='; break; } | ||
case 3: { output += '='; break; } | ||
default: { | ||
throw new Error('Illegal base64url string!'); | ||
} | ||
} | ||
return b64DecodeUnicode(output); | ||
} | ||
|
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 |
---|---|---|
@@ -0,0 +1,33 @@ | ||
const moment = require('moment'); | ||
const jwt = require('jwt-simple'); | ||
const cfg = require('./config.js'); | ||
|
||
module.exports.permanentRefreshToken = 'eb4e15840117437cbfd7343f257c4aae'; | ||
|
||
module.exports.createAccessToken = function(user) { | ||
var payload = { | ||
sub: user.id, | ||
exp: moment().add(cfg.accessTokenExpiresIn, 'seconds').unix(), | ||
iat: moment().unix(), | ||
id: user.id, | ||
email: user.email, | ||
role: 'user', | ||
}; | ||
var token = jwt.encode(payload, cfg.jwtSecret); | ||
return token; | ||
} | ||
|
||
module.exports.createRefreshToken = function(user) { | ||
var refreshPayload = { | ||
sub: user.id, | ||
exp: moment().add(cfg.refreshTokenExpiresIn, 'seconds').unix(), | ||
iat: moment().unix(), | ||
id: user.id, | ||
email: user.email, | ||
role: 'REFRESH_TOKEN', | ||
}; | ||
var refreshToken = jwt.encode(refreshPayload, cfg.jwtSecret); | ||
return refreshToken; | ||
} | ||
|
||
module.exports |
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,22 @@ | ||
const wines = [ | ||
{ | ||
id: 1, | ||
name: 'Pommard 1er cru', | ||
region: 'Bourgogne', | ||
year: 2012, | ||
}, | ||
{ | ||
id: 2, | ||
name: 'Aloxe Corton Grand cru', | ||
region: 'Bourgogne', | ||
year: 2008, | ||
}, | ||
{ | ||
id: 3, | ||
name: 'Meursault 1er cru', | ||
region: 'Bourgogne', | ||
year: 1997, | ||
}, | ||
]; | ||
|
||
module.exports = wines; |
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,93 @@ | ||
/** | ||
* @license | ||
* Copyright Akveo. All Rights Reserved. | ||
* Licensed under the MIT License. See License.txt in the project root for license information. | ||
*/ | ||
|
||
import { Component, Inject } from '@angular/core'; | ||
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; | ||
import { Router } from '@angular/router'; | ||
import { Observable, of as observableOf } from 'rxjs'; | ||
import { catchError, delay } from 'rxjs/operators'; | ||
import { NbAuthResult, NbAuthService, NbAuthToken } from '../../../framework/auth/services'; | ||
import { NB_AUTH_OPTIONS } from '../../../framework/auth/auth.options'; | ||
import { getDeepFromObject } from '../../../framework/auth/helpers'; | ||
import { Wine } from './wine'; | ||
|
||
@Component({ | ||
selector: 'nb-playground-api-calls', | ||
template: ` | ||
<router-outlet></router-outlet> | ||
<nb-layout> | ||
<nb-layout-column> | ||
<nb-card> | ||
<nb-card-body> | ||
<h2>You are authenticated</h2> | ||
<p>You can call the secured API</p> | ||
<button nbButton status="primary" (click)="loadWines()">Call API</button> | ||
<button nbButton status="primary" (click)="logout()">Sign out</button> | ||
</nb-card-body> | ||
</nb-card> | ||
<nb-card *ngIf="(wines$ | async)?.length"> | ||
<nb-card-header> | ||
Alain'wines | ||
</nb-card-header> | ||
<nb-list> | ||
<nb-list-item *ngFor="let wine of wines$ | async"> | ||
{{ wine.region }}, {{ wine.name }} ({{ wine.year }}) | ||
</nb-list-item> | ||
</nb-list> | ||
</nb-card> | ||
</nb-layout-column> | ||
</nb-layout> | ||
`, | ||
}) | ||
|
||
export class NbPlaygroundApiCallsComponent { | ||
|
||
token: NbAuthToken; | ||
wines$: Observable<Wine[]>; | ||
redirectDelay: number = 0; | ||
strategy: string = ''; | ||
|
||
constructor(private authService: NbAuthService, | ||
private http: HttpClient, | ||
private router: Router, | ||
@Inject(NB_AUTH_OPTIONS) protected options = {}) { | ||
|
||
this.redirectDelay = this.getConfigValue('forms.logout.redirectDelay'); | ||
this.strategy = this.getConfigValue('forms.logout.strategy'); | ||
|
||
this.authService.onTokenChange() | ||
.subscribe((token: NbAuthToken) => { | ||
this.token = null; | ||
if (token && token.isValid()) { | ||
this.token = token; | ||
} | ||
}); | ||
} | ||
|
||
logout() { | ||
this.authService.logout(this.strategy) | ||
.pipe( | ||
delay(this.redirectDelay), | ||
) | ||
.subscribe((result: NbAuthResult) => this.router.navigate(['/auth/login'])); | ||
} | ||
|
||
loadWines() { | ||
this.wines$ = this.http.get<Wine[]>('http://localhost:4400/api/wines') | ||
.pipe( | ||
catchError(err => { | ||
if (err instanceof HttpErrorResponse && err.status === 401) { | ||
this.router.navigate(['/auth/login']); | ||
} | ||
return observableOf([]); | ||
}), | ||
); | ||
} | ||
|
||
getConfigValue(key: string): any { | ||
return getDeepFromObject(this.options, key, null); | ||
} | ||
} |
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,6 @@ | ||
export interface Wine { | ||
id: number; | ||
name: string; | ||
region: string; | ||
year: number | ||
} |
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.