cbp-lib
Version:
Libraries for cbp
80 lines (69 loc) • 1.96 kB
JavaScript
'use strict'
import {ArgumentError, Validation} from '../_helpers/custom-error'
import jwtDecode from 'jwt-decode'
const parseToken = (token) => {
if (typeof token === 'string') {
return JSON.parse(token)
}
else if (typeof token === 'object') {
return token
}
else {
throw new ArgumentError('parse error. invalid token')
}
}
export class TokenManager {
constructor(options) {
this.store = options.store
this.token = parseToken(this.store.getItem('token')) || {
access_token: '',
id_token: '',
refresh_token: '',
token_type: '',
expires_in: ''
}
}
getAccessToken() {
if (Validation.isEmpty(this.token) &&
Validation.isEmpty(this.token['access_token'])) {
return;
}
return this.token['access_token']
}
getIDToken() {
if (Validation.isEmpty(this.token) &&
Validation.isEmpty(this.token['id_token'])) {
return;
}
return this.token['id_token']
}
getRefreshToken() {
if (Validation.isEmpty(this.token) &&
Validation.isEmpty(this.token['refresh_token'])) {
return;
}
return this.token['refresh_token']
}
removeToken() {
return this.store.removeItem('token')
}
getTokenType() {
if (Validation.isEmpty(this.token) &&
Validation.isEmpty(this.token['token_type'])) {
return;
}
return this.token['token_type']
}
getTokenExpiration() {
if (Validation.isEmpty(this.token) &&
Validation.isEmpty(this.token['expires_in'])) {
return;
}
return this.token['expires_in']
}
decodeToken(token) {
//Decode token
let decoded = jwtDecode(token);
return Promise.resolve(decoded);
}
}