|
@@ -8,7 +8,12 @@ const assert = require('assert');
|
|
|
class UserService extends CrudService {
|
|
|
constructor(ctx) {
|
|
|
super(ctx, 'user');
|
|
|
+ this.redis = this.app.redis;
|
|
|
this.model = this.ctx.model.User.User;
|
|
|
+ this.emailKey = 'bindEmail:';
|
|
|
+ this.httpUtil = this.ctx.service.util.httpUtil;
|
|
|
+ this.emailServiceUrl = _.get(this.app, 'config.httpPrefix.email');
|
|
|
+ this.conenctCode = '&&';
|
|
|
}
|
|
|
async beforeCreate(data) {
|
|
|
const openid = _.get(data, 'openid');
|
|
@@ -69,6 +74,34 @@ class UserService extends CrudService {
|
|
|
const token = this.ctx.service.util.jwt.encrypt(user);
|
|
|
return token;
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 绑定邮箱验证码
|
|
|
+ * @param {Object} body 请求体
|
|
|
+ * @param body.id 用户id
|
|
|
+ * @param body.email 用户要绑定的邮箱
|
|
|
+ */
|
|
|
+ async toBindEmail({ id, email }) {
|
|
|
+ const code = _.random(100000, 999999);
|
|
|
+ const value = `${email}${this.conenctCode}${code}`;
|
|
|
+ await this.redis.set(`${this.emailKey}${id}`, value, 'EX', 300);
|
|
|
+ // 发邮件
|
|
|
+ const data = { template: 'bindEmail', receiver: email, params: { code } };
|
|
|
+ const url = `${this.emailServiceUrl}/sendEmail`;
|
|
|
+ const res = await this.httpUtil.cpost(url, data);
|
|
|
+ console.log(res);
|
|
|
+ return res;
|
|
|
+ }
|
|
|
+ async checkBindEmail({ code, id, email }) {
|
|
|
+ const redisData = await this.redis.get(`${this.emailKey}${id}`);
|
|
|
+ if (!redisData) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '验证码已超时');
|
|
|
+ const arr = redisData.split(this.conenctCode);
|
|
|
+ const rEmail = _.head(arr);
|
|
|
+ const rCode = _.last(arr);
|
|
|
+ if (code !== rCode) throw new BusinessError(ErrorCode.DATA_INVALID, '验证码错误');
|
|
|
+ if (email !== rEmail) throw new BusinessError(ErrorCode.DATA_INVALID, '要绑定的邮箱与接收验证码的邮箱不是同一个邮箱');
|
|
|
+ await this.model.updateOne({ _id: id }, { email });
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
module.exports = UserService;
|