lrf402788946 3 سال پیش
والد
کامیت
39715be6bc
1فایلهای تغییر یافته به همراه219 افزوده شده و 215 حذف شده
  1. 219 215
      app/controller/weixin.js

+ 219 - 215
app/controller/weixin.js

@@ -1,215 +1,219 @@
-'use strict';
-
-const assert = require('assert');
-const _ = require('lodash');
-const uuid = require('uuid');
-const urljoin = require('url-join');
-const stringRandom = require('string-random');
-const Controller = require('egg').Controller;
-const { BusinessError, ErrorCode } = require('naf-core').Error;
-
-/**
- * 微信认证,获得openid和用户信息,生成微信Jwt
- */
-class WeixinController extends Controller {
-  /**
-   * 认证流程
-   * 1. 缓存原始请求地址,生成state和认证回调地址
-   * 2. 通过wxapi认证,获得认证code
-   * 3. 通过code获得openid,通过openid,查询绑定用户,创建jwt
-   * 4. jwt写入redis,返回认证code
-   * 5. 通过code获取jwt
-   */
-  // GET 请求认证
-  // response_type:
-  //       code - url带上code参数重定向到原始地址
-  //       store - 默认,认证结果写入sessionStore,然后重定向回请求页面(要求请求页面和认证服务在同一域名下)
-  //       token - url带上token参数重定向到原始地址
-  async auth() {
-    const { redirect_uri, code, test, type, response_type = 'store', uid, qrcode, msgid, objid } = this.ctx.query;
-    if (test) {
-      return await this.authTest();
-    }
-    if (code) {
-      return await this.authBack(this.ctx.query);
-    }
-
-    this.ctx.logger.debug(`[auth] reditect_uri - ${redirect_uri}`);
-    // assert(redirect_uri, '回调地址不能为空');
-
-    // TODO: 保存原始请求地址
-    // const { config } = this.app;
-    // console.log('ctx.host: ', this.ctx.host);
-    // console.log('config.hostHeaders: ', config.hostHeaders);
-    // TODO: 保存原始请求地址
-    const state = uuid();
-    const key = `visit:auth:state:${state}`;
-    const val = JSON.stringify({ redirect_uri, type, uid, qrcode, msgid, objid });
-    await this.app.redis.set(key, val, 'EX', 600);
-
-    // TODO: 生成回调地址
-    const { wxapi, authUrl = this.ctx.path } = this.app.config;
-    const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}?state=${state}`);
-    const to_uri = encodeURI(`${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`);
-    // const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}/`);
-    // const to_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxapi.appid}&response_type=code&scope=snsapi_base&redirect_uri=${backUrl}&state=${state}&connect_redirect=1#wechat_redirect`;
-    this.ctx.redirect(to_uri);
-  }
-
-  // GET 认证回调
-  async authBack({ code, state }) {
-    // const { code, state, type, redirecturi } = this.ctx.query;
-    this.ctx.logger.debug(`[auth-back] code - ${code}, state - ${state}`);
-    assert(code, 'code不能为空');
-    assert(state, 'state不能为空');
-    const { weixin } = this.ctx.service;
-    const key = `visit:auth:state:${state}`;
-    const val = await this.app.redis.get(key);
-    let openid;
-    try {
-      ({ openid } = await weixin.fetch(code));
-    } catch (err) {
-      await this.ctx.render('error.njk', { title: err.message, message: err.details });
-      return;
-    }
-    if (openid) {
-
-      const { redirect_uri, type, uid, qrcode, msgid, objid } = JSON.parse(val);
-      const user = await this.ctx.service.user.findByOpenid(openid);
-      if (type === '0') {
-        // 通过openid取得用户信息
-        if (user) {
-          const token = await this.ctx.service.login.createJwt(user);
-          if (user.type === '4') {
-            // 学生
-            // 检查学生是否已退出,学生表的isComming是不是2,如果是2 就跳到别的地方提示您已退出
-            const stu = await this.ctx.service.student.fetch({ id: user.uid });
-            if (stu) {
-              const { isComming } = stu;
-              if (isComming && isComming === '2') {
-                const refuse = `${this.app.config.baseUrl}/msgconfirm/isleave`;
-                this.ctx.redirect(refuse);
-              } else {
-                const to_uri = urljoin(redirect_uri, `?token=${token}`);
-                // TODO: 重定性页面
-                this.ctx.redirect(to_uri);
-              }
-            }
-
-
-          } else if (user.type === '1') {
-            // 班主任
-            const touri = `${this.app.config.baseUrl}/mobiledirtea`;
-            const to_uri = urljoin(touri, `?token=${token}`);
-            // TODO: 重定性页面
-            this.ctx.redirect(to_uri);
-          } else if (user.type === '3') {
-            // 教师
-            const touri = `${this.app.config.baseUrl}/mobiledirtea`;
-            const to_uri = urljoin(touri, `?token=${token}`);
-            // TODO: 重定性页面
-            this.ctx.redirect(to_uri);
-          }
-
-        } else {
-          // const resunionid = await weixin.fetchUnionID(openid);
-          const touri = `${this.app.config.baseUrl}/student/bind`;
-          const to_uri = urljoin(touri, `?openid=${openid}`); // &unionid=${resunionid.unionid}
-          // TODO: 重定性页面
-          this.ctx.redirect(to_uri);
-        }
-      } else if (type === '1') {
-        const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
-        // TODO: 重定性页面
-        this.ctx.redirect(to_uri);
-      } else if (type === '2') {
-        const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
-        // TODO: 重定性页面
-        this.ctx.redirect(to_uri);
-      } else if (type === '9') {
-        // const token = await this.ctx.service.login.createJwt(user);
-        const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
-        // TODO: 重定性页面
-        this.ctx.redirect(to_uri);
-      }
-    }
-
-  }
-
-  // GET 用户授权内部测试接口
-  async authTest() {
-    const { redirect_uri, type, uid, qrcode, openid, msgid, objid } = this.ctx.query;
-    // const openid = stringRandom();
-    this.ctx.logger.debug(`[auth-test] reditect_uri - ${redirect_uri}, openid - ${openid}`);
-    assert(redirect_uri, '回调地址不能为空');
-    assert(openid, 'openid不能为空');
-    const user = await this.ctx.service.user.findByOpenid(openid);
-    if (type === '0') {
-      // 通过openid取得用户信息
-      if (user) {
-        const token = await this.ctx.service.login.createJwt(user);
-        if (user.type === '4') {
-          const to_uri = urljoin(redirect_uri, `?token=${token}`);
-          // TODO: 重定性页面
-          this.ctx.redirect(to_uri);
-        } else if (user.type === '1') {
-          const touri = `${this.app.config.baseUrl}/mobiledirtea`;
-          const to_uri = urljoin(touri, `?token=${token}`);
-          // TODO: 重定性页面
-          this.ctx.redirect(to_uri);
-        } else if (user.type === '3') {
-          const touri = `${this.app.config.baseUrl}/mobiledirtea`;
-          const to_uri = urljoin(touri, `?token=${token}`);
-          // TODO: 重定性页面
-          this.ctx.redirect(to_uri);
-        }
-
-      } else {
-        console.log('rrr0000--->' + redirect_uri);
-        const resunionid = await weixin.fetchUnionID(openid);
-        const touri = `${this.app.config.baseUrl}/student/bind`;
-        const to_uri = urljoin(touri, `?openid=${openid}&unionid=${resunionid.unionid}`);
-        // TODO: 重定性页面
-        this.ctx.redirect(to_uri);
-      }
-    } else if (type === '1') {
-      const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
-      // TODO: 重定性页面
-      console.log('1111---?' + to_uri);
-      this.ctx.redirect(to_uri);
-    } else if (type === '2') {
-      const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
-      // TODO: 重定性页面
-      console.log('22222---?' + to_uri);
-      this.ctx.redirect(to_uri);
-    } else if (type === '9') {
-      // const token = await this.ctx.service.login.createJwt(user);
-      const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
-      // TODO: 重定性页面
-      console.log('99999---?' + to_uri);
-      this.ctx.redirect(to_uri);
-    }
-  }
-
-  // GET 签到小程序请求用户
-  async appAuth() {
-    try {
-      const { js_code, login = true } = this.ctx.query;
-      console.log(js_code);
-      const appopenid = await this.ctx.service.weixin.appAuth(js_code);
-      if (!login) this.ctx.ok(appopenid);
-      console.warn(`openid=>${appopenid}`);
-      // const state = uuid();
-      // const key = `appinfo:${state}`;
-      // await this.app.redis.set(key, appopenid, 'EX', 600);
-      const res = await this.ctx.service.user.findByAppOpenid(appopenid);
-      const obj = { user: res, openid: appopenid };
-      this.ctx.ok(obj);
-    } catch (error) {
-      throw new BusinessError(ErrorCode.NETWORK, '获取小程序信息失败,请尝试重新进入');
-    }
-
-  }
-}
-
-module.exports = WeixinController;
+'use strict';
+
+const assert = require('assert');
+const _ = require('lodash');
+const uuid = require('uuid');
+const urljoin = require('url-join');
+const stringRandom = require('string-random');
+const Controller = require('egg').Controller;
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+
+/**
+ * 微信认证,获得openid和用户信息,生成微信Jwt
+ */
+class WeixinController extends Controller {
+  /**
+   * 认证流程
+   * 1. 缓存原始请求地址,生成state和认证回调地址
+   * 2. 通过wxapi认证,获得认证code
+   * 3. 通过code获得openid,通过openid,查询绑定用户,创建jwt
+   * 4. jwt写入redis,返回认证code
+   * 5. 通过code获取jwt
+   */
+  // GET 请求认证
+  // response_type:
+  //       code - url带上code参数重定向到原始地址
+  //       store - 默认,认证结果写入sessionStore,然后重定向回请求页面(要求请求页面和认证服务在同一域名下)
+  //       token - url带上token参数重定向到原始地址
+  async auth() {
+    const { redirect_uri, code, test, type, response_type = 'store', uid, qrcode, msgid, objid } = this.ctx.query;
+    if (test) {
+      return await this.authTest();
+    }
+    if (code) {
+      return await this.authBack(this.ctx.query);
+    }
+
+    this.ctx.logger.debug(`[auth] reditect_uri - ${redirect_uri}`);
+    // assert(redirect_uri, '回调地址不能为空');
+
+    // TODO: 保存原始请求地址
+    // const { config } = this.app;
+    // console.log('ctx.host: ', this.ctx.host);
+    // console.log('config.hostHeaders: ', config.hostHeaders);
+    // TODO: 保存原始请求地址
+    const state = uuid();
+    const key = `visit:auth:state:${state}`;
+    const val = JSON.stringify({ redirect_uri, type, uid, qrcode, msgid, objid });
+    await this.app.redis.set(key, val, 'EX', 600);
+
+    // TODO: 生成回调地址
+    const { wxapi, authUrl = this.ctx.path } = this.app.config;
+    const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}?state=${state}`);
+    const to_uri = encodeURI(`${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`);
+    // const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}/`);
+    // const to_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxapi.appid}&response_type=code&scope=snsapi_base&redirect_uri=${backUrl}&state=${state}&connect_redirect=1#wechat_redirect`;
+    this.ctx.redirect(to_uri);
+  }
+
+  // GET 认证回调
+  async authBack({ code, state }) {
+    // const { code, state, type, redirecturi } = this.ctx.query;
+    this.ctx.logger.debug(`[auth-back] code - ${code}, state - ${state}`);
+    assert(code, 'code不能为空');
+    assert(state, 'state不能为空');
+    const { weixin } = this.ctx.service;
+    const key = `visit:auth:state:${state}`;
+    const val = await this.app.redis.get(key);
+    let openid;
+    try {
+      ({ openid } = await weixin.fetch(code));
+    } catch (err) {
+      await this.ctx.render('error.njk', { title: err.message, message: err.details });
+      return;
+    }
+    if (openid) {
+
+      const { redirect_uri, type, uid, qrcode, msgid, objid } = JSON.parse(val);
+      const user = await this.ctx.service.user.findByOpenid(openid);
+      if (type === '0') {
+        // 通过openid取得用户信息
+        if (user) {
+          const token = await this.ctx.service.login.createJwt(user);
+          if (user.type === '4') {
+            // 学生
+            // 检查学生是否已退出,学生表的isComming是不是2,如果是2 就跳到别的地方提示您已退出
+            const stu = await this.ctx.service.student.fetch({ id: user.uid });
+            if (stu) {
+              const { isComming } = stu;
+              if (isComming && isComming === '2') {
+                const refuse = `${this.app.config.baseUrl}/msgconfirm/isleave`;
+                this.ctx.redirect(refuse);
+              } else {
+                const to_uri = urljoin(redirect_uri, `?token=${token}`);
+                // TODO: 重定性页面
+                this.ctx.redirect(to_uri);
+              }
+            } else {
+              const touri = `${this.app.config.baseUrl}/student/bind`;
+              const to_uri = urljoin(touri, `?openid=${openid}`);
+              this.ctx.redirect(to_uri);
+            }
+
+
+          } else if (user.type === '1') {
+            // 班主任
+            const touri = `${this.app.config.baseUrl}/mobiledirtea`;
+            const to_uri = urljoin(touri, `?token=${token}`);
+            // TODO: 重定性页面
+            this.ctx.redirect(to_uri);
+          } else if (user.type === '3') {
+            // 教师
+            const touri = `${this.app.config.baseUrl}/mobiledirtea`;
+            const to_uri = urljoin(touri, `?token=${token}`);
+            // TODO: 重定性页面
+            this.ctx.redirect(to_uri);
+          }
+
+        } else {
+          // const resunionid = await weixin.fetchUnionID(openid);
+          const touri = `${this.app.config.baseUrl}/student/bind`;
+          const to_uri = urljoin(touri, `?openid=${openid}`); // &unionid=${resunionid.unionid}
+          // TODO: 重定性页面
+          this.ctx.redirect(to_uri);
+        }
+      } else if (type === '1') {
+        const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
+        // TODO: 重定性页面
+        this.ctx.redirect(to_uri);
+      } else if (type === '2') {
+        const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
+        // TODO: 重定性页面
+        this.ctx.redirect(to_uri);
+      } else if (type === '9') {
+        // const token = await this.ctx.service.login.createJwt(user);
+        const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
+        // TODO: 重定性页面
+        this.ctx.redirect(to_uri);
+      }
+    }
+
+  }
+
+  // GET 用户授权内部测试接口
+  async authTest() {
+    const { redirect_uri, type, uid, qrcode, openid, msgid, objid } = this.ctx.query;
+    // const openid = stringRandom();
+    this.ctx.logger.debug(`[auth-test] reditect_uri - ${redirect_uri}, openid - ${openid}`);
+    assert(redirect_uri, '回调地址不能为空');
+    assert(openid, 'openid不能为空');
+    const user = await this.ctx.service.user.findByOpenid(openid);
+    if (type === '0') {
+      // 通过openid取得用户信息
+      if (user) {
+        const token = await this.ctx.service.login.createJwt(user);
+        if (user.type === '4') {
+          const to_uri = urljoin(redirect_uri, `?token=${token}`);
+          // TODO: 重定性页面
+          this.ctx.redirect(to_uri);
+        } else if (user.type === '1') {
+          const touri = `${this.app.config.baseUrl}/mobiledirtea`;
+          const to_uri = urljoin(touri, `?token=${token}`);
+          // TODO: 重定性页面
+          this.ctx.redirect(to_uri);
+        } else if (user.type === '3') {
+          const touri = `${this.app.config.baseUrl}/mobiledirtea`;
+          const to_uri = urljoin(touri, `?token=${token}`);
+          // TODO: 重定性页面
+          this.ctx.redirect(to_uri);
+        }
+
+      } else {
+        console.log('rrr0000--->' + redirect_uri);
+        const resunionid = await weixin.fetchUnionID(openid);
+        const touri = `${this.app.config.baseUrl}/student/bind`;
+        const to_uri = urljoin(touri, `?openid=${openid}&unionid=${resunionid.unionid}`);
+        // TODO: 重定性页面
+        this.ctx.redirect(to_uri);
+      }
+    } else if (type === '1') {
+      const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
+      // TODO: 重定性页面
+      console.log('1111---?' + to_uri);
+      this.ctx.redirect(to_uri);
+    } else if (type === '2') {
+      const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
+      // TODO: 重定性页面
+      console.log('22222---?' + to_uri);
+      this.ctx.redirect(to_uri);
+    } else if (type === '9') {
+      // const token = await this.ctx.service.login.createJwt(user);
+      const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
+      // TODO: 重定性页面
+      console.log('99999---?' + to_uri);
+      this.ctx.redirect(to_uri);
+    }
+  }
+
+  // GET 签到小程序请求用户
+  async appAuth() {
+    try {
+      const { js_code, login = true } = this.ctx.query;
+      console.log(js_code);
+      const appopenid = await this.ctx.service.weixin.appAuth(js_code);
+      if (!login) this.ctx.ok(appopenid);
+      console.warn(`openid=>${appopenid}`);
+      // const state = uuid();
+      // const key = `appinfo:${state}`;
+      // await this.app.redis.set(key, appopenid, 'EX', 600);
+      const res = await this.ctx.service.user.findByAppOpenid(appopenid);
+      const obj = { user: res, openid: appopenid };
+      this.ctx.ok(obj);
+    } catch (error) {
+      throw new BusinessError(ErrorCode.NETWORK, '获取小程序信息失败,请尝试重新进入');
+    }
+
+  }
+}
+
+module.exports = WeixinController;