Created
February 13, 2016 17:05
-
-
Save masahirompp/235ed1d46330ec42a459 to your computer and use it in GitHub Desktop.
json web token encode / decode sample.
This file contains hidden or 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
import * as _ from 'underscore'; | |
import * as moment from 'moment'; | |
import * as jwt from 'jwt-simple'; | |
import * as config from 'config'; | |
import * as Log from './Log'; | |
/** | |
* エンコードする | |
* 有効期限を付与する | |
* @param data | |
* @return {string} | |
*/ | |
export function encode(data) { | |
const expires = moment().add(6, 'hours').valueOf(); | |
return jwt.encode(_.extend({}, data, { expires }), config.jwt.secret); | |
} | |
/** | |
* デコードする | |
* @param token | |
* @return {any} | |
* @desc 呼び出し元でtokenのnullチェックを行う | |
*/ | |
export function decode(token) { | |
try { | |
const decoded = jwt.decode(token, config.jwt.secret); | |
if (decoded) { | |
if (_.isNumber(decoded.expires) && decoded.expires > Date.now()) { | |
return decoded; | |
} | |
Log.access.warn('expired', decoded); | |
} else { | |
Log.access.error('invalid token', token); | |
} | |
} catch (err) { | |
Log.access.error('decode error', token, err.stack || err.message || err); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment