This repository has been archived by the owner on Sep 21, 2021. It is now read-only.
/
token.manager.ts
103 lines (93 loc) · 2.58 KB
/
token.manager.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
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
import { Storage, StorageType } from '../helpers/storage';
export interface IToken {
provider: string;
id_token?: string;
access_token?: string;
token_type?: string;
scope?: string;
state?: string;
expires_in?: string;
expires_at?: Date;
}
export interface ICode {
provider: string;
code: string;
scope?: string;
state?: string;
}
export interface IError {
error: string;
state?: string;
}
/**
* Helper for caching and managing OAuth Tokens.
*/
export class TokenStorage extends Storage<IToken> {
/**
* @constructor
*/
constructor(storageType = StorageType.LocalStorage) {
super('OAuth2Tokens', storageType);
}
/**
* Compute the expiration date based on the expires_in field in a OAuth token.
*/
static setExpiry(token: IToken) {
let expire = seconds => seconds == null ? null : new Date(new Date().getTime() + ~~seconds * 1000);
if (!(token == null) && token.expires_at == null) {
token.expires_at = expire(token.expires_in);
}
}
/**
* Check if an OAuth token has expired.
*/
static hasExpired(token: IToken): boolean {
if (token == null) {
return true;
}
if (token.expires_at == null) {
return false;
}
else {
// If the token was stored, it's Date type property was stringified, so it needs to be converted back to Date.
token.expires_at = token.expires_at instanceof Date ? token.expires_at : new Date(token.expires_at as any);
return token.expires_at.getTime() - new Date().getTime() < 0;
}
}
/**
* Extends Storage's default get method
* Gets an OAuth Token after checking its expiry
*
* @param {string} provider Unique name of the corresponding OAuth Token.
* @return {object} Returns the token or null if its either expired or doesn't exist.
*/
get(provider: string): IToken {
let token = super.get(provider);
if (token == null) {
return token;
}
let expired = TokenStorage.hasExpired(token);
if (expired) {
super.delete(provider);
return null;
}
else {
return token;
}
}
/**
* Extends Storage's default add method
* Adds a new OAuth Token after settings its expiry
*
* @param {string} provider Unique name of the corresponding OAuth Token.
* @param {object} config valid Token
* @see {@link IToken}.
* @return {object} Returns the added token.
*/
add(provider: string, value: IToken) {
value.provider = provider;
TokenStorage.setExpiry(value);
return super.set(provider, value);
}
}