weapp_auth.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const weappConfig = require('../const/weapp');
  3. const jwt = require('jsonwebtoken');
  4. module.exports = (options, app) => {
  5. return async function wechatAuth(ctx, next) {
  6. const token = ctx.headers.authorization && ctx.headers.authorization.replace('Bearer ', '');
  7. console.log('1111');
  8. const code = ctx.headers['platform-code'];
  9. if (!token || !code) return ctx.fail(401, '请登录');
  10. try {
  11. const decoded = jwt.verify(token, weappConfig.jwtSecret);
  12. const projectData = await ctx.service.project.getProjectByCode(
  13. code.trim()
  14. );
  15. if (projectData === null) {
  16. throw '不存在项目数据';
  17. }
  18. const projectAccount = await ctx.service.projectAccount.getDataByCondition({
  19. wx_openid: decoded.openid,
  20. project_id: projectData.id,
  21. enable: 1,
  22. });
  23. if (!projectAccount) {
  24. throw '账号不存在或未启用';
  25. }
  26. ctx.projectAccount = projectAccount;
  27. ctx.project = projectData;
  28. } catch (error) {
  29. if (error.name === 'TokenExpiredError') {
  30. ctx.body = { code: 2, msg: '', data: null };
  31. return;
  32. }
  33. ctx.body = { code: -1, msg: error.toString() || '请登录', data: null };
  34. return;
  35. }
  36. await next();
  37. };
  38. };