Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. import * as _ from 'underscore';
  2. import * as moment from 'moment';
  3. import * as jwt from 'jwt-simple';
  4. import * as config from 'config';
  5. import * as Log from './Log';
  6.  
  7. /**
  8. * エンコードする
  9. * 有効期限を付与する
  10. * @param data
  11. * @return {string}
  12. */
  13. export function encode(data) {
  14. const expires = moment().add(6, 'hours').valueOf();
  15. return jwt.encode(_.extend({}, data, { expires }), config.jwt.secret);
  16. }
  17.  
  18. /**
  19. * デコードする
  20. * @param token
  21. * @return {any}
  22. * @desc 呼び出し元でtokenのnullチェックを行う
  23. */
  24. export function decode(token) {
  25. try {
  26. const decoded = jwt.decode(token, config.jwt.secret);
  27. if (decoded) {
  28. if (_.isNumber(decoded.expires) && decoded.expires > Date.now()) {
  29. return decoded;
  30. }
  31. Log.access.warn('expired', decoded);
  32. } else {
  33. Log.access.error('invalid token', token);
  34. }
  35. } catch (err) {
  36. Log.access.error('decode error', token, err.stack || err.message || err);
  37. }
  38. return null;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement