123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- 'use strict';
- const _ = require('lodash');
- const jwt = require('jsonwebtoken');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- /**
- * 验证token
- * @param {Object} token token字符串
- * @param {String} secret jwt密码
- */
- const checkJwt = (token, secret) => {
- if (!token) throw new BusinessError(ErrorCode.ACCESS_DENIED, '缺少秘钥,拒绝访问');
- const errorList = [
- { key: 'jwt expired', word: '秘钥已过期,请重新登陆' },
- { key: 'invalid signature', word: '秘钥错误,请检查秘钥' },
- { key: 'JSON at position', word: '秘钥错误,请检查秘钥' },
- { key: 'invalid token', word: '秘钥错误,请检查秘钥' },
- ];
- try {
- const r = jwt.verify(token, secret);
- if (r) return r; // 如果过期将返回false
- return false;
- } catch (e) {
- const { message } = e;
- const r = errorList.find(f => message.includes(f.key));
- if (r) throw new BusinessError(ErrorCode.ACCESS_DENIED, r.word);
- else throw new BusinessError(ErrorCode.ACCESS_DENIED, '秘钥产生位置错误,检测失败');
- }
- };
- module.exports = ({ enable = false }) => {
- return async function checkToken(ctx, next) {
- if (enable) {
- // token处理
- const token = _.get(ctx.request, 'header.authorization');
- if (token) {
- const r = checkJwt(token, ctx.app.config.jwt.secret);
- ctx.user = r;
- }
- await next();
- } else await next();
- };
- };
|