Skip to content

Instantly share code, notes, and snippets.

@masahirompp
Created February 13, 2016 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahirompp/235ed1d46330ec42a459 to your computer and use it in GitHub Desktop.
Save masahirompp/235ed1d46330ec42a459 to your computer and use it in GitHub Desktop.
json web token encode / decode sample.
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