-
Notifications
You must be signed in to change notification settings - Fork 291
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #302 from lelylan/feature/access-token-refactor
[access-token-refactor] Refactor access token parsing functionality
- Loading branch information
Showing
2 changed files
with
49 additions
and
32 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
'use strict'; | ||
|
||
const debug = require('debug')('simple-oauth2:access-token'); | ||
const isDate = require('date-fns/isDate'); | ||
const parseISO = require('date-fns/parseISO'); | ||
const addSeconds = require('date-fns/addSeconds'); | ||
|
||
const EXPIRES_AT_PROPERTY_NAME = 'expires_at'; | ||
const EXPIRES_IN_PROPERTY_NAME = 'expires_in'; | ||
|
||
function getExpirationDate(expiresIn) { | ||
return addSeconds(new Date(), Number.parseInt(expiresIn, 10)); | ||
} | ||
|
||
function parseExpirationDate(expirationDate) { | ||
if (isDate(expirationDate)) { | ||
return expirationDate; | ||
} | ||
|
||
// UNIX timestamp | ||
if (typeof expirationDate === 'number') { | ||
return new Date(expirationDate * 1000); | ||
} | ||
|
||
// ISO 8601 string | ||
return parseISO(expirationDate); | ||
} | ||
|
||
function parseToken(token) { | ||
const tokenProperties = {}; | ||
|
||
if (EXPIRES_AT_PROPERTY_NAME in token) { | ||
tokenProperties[EXPIRES_AT_PROPERTY_NAME] = parseExpirationDate(token[EXPIRES_AT_PROPERTY_NAME]); | ||
} else if (EXPIRES_IN_PROPERTY_NAME in token) { | ||
tokenProperties[EXPIRES_AT_PROPERTY_NAME] = getExpirationDate(token[EXPIRES_IN_PROPERTY_NAME]); | ||
} else { | ||
debug('No token expiration property was found. Ignoring date parsing'); | ||
} | ||
|
||
return Object.assign({}, token, tokenProperties); | ||
} | ||
|
||
module.exports = { parseToken }; |