check-token.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const _ = require('lodash');
  3. const jwt = require('jsonwebtoken');
  4. const { BusinessError, ErrorCode } = require('naf-core').Error;
  5. /**
  6. * 验证token
  7. * @param {Object} token token字符串
  8. * @param {String} secret jwt密码
  9. */
  10. const checkJwt = (token, secret) => {
  11. if (!token) throw new BusinessError(ErrorCode.ACCESS_DENIED, '缺少秘钥,拒绝访问');
  12. const errorList = [
  13. { key: 'jwt expired', word: '秘钥已过期,请重新登陆' },
  14. { key: 'invalid signature', word: '秘钥错误,请检查秘钥' },
  15. { key: 'JSON at position', word: '秘钥错误,请检查秘钥' },
  16. { key: 'invalid token', word: '秘钥错误,请检查秘钥' },
  17. ];
  18. try {
  19. const r = jwt.verify(token, secret);
  20. if (r) return r; // 如果过期将返回false
  21. return false;
  22. } catch (e) {
  23. const { message } = e;
  24. const r = errorList.find(f => message.includes(f.key));
  25. if (r) throw new BusinessError(ErrorCode.ACCESS_DENIED, r.word);
  26. else throw new BusinessError(ErrorCode.ACCESS_DENIED, '秘钥产生位置错误,检测失败');
  27. }
  28. };
  29. module.exports = ({ enable = false }) => {
  30. return async function checkToken(ctx, next) {
  31. if (enable) {
  32. // token处理
  33. const token = _.get(ctx.request, 'header.authorization');
  34. if (token) {
  35. const r = checkJwt(token, ctx.app.config.jwt.secret);
  36. ctx.user = r;
  37. }
  38. await next();
  39. } else await next();
  40. };
  41. };