1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- //
- class UserService extends CrudService {
- constructor(ctx) {
- super(ctx, 'user');
- this.model = this.ctx.model.User.User;
- }
- async beforeCreate(data) {
- const openid = _.get(data, 'openid');
- const phone = _.get(data, 'phone');
- if (!openid && phone) {
- const num = await this.model.count({ phone });
- if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号已注册');
- } else if (openid) {
- const num = await this.model.count({ openid });
- if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该微信号已注册');
- }
- return data;
- }
- async resetPwd({ id }, { password }) {
- const data = await this.model.findById(id);
- if (!data) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
- data.password = { secret: password };
- await data.save();
- }
- /**
- * 登陆
- * @param {Object} body 登陆参数
- * @param body.phone 账户
- * @param body.password 密码
- */
- async login({ phone, password }) {
- const { populate } = this.getRefMods();
- let user = await this.model.findOne({ phone }, '+password').populate(populate);
- if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
- const { password: upwd, status } = user;
- if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
- if (password !== upwd.secret) throw new BusinessError(ErrorCode.BAD_PASSWORD);
- // // 使用redis存储,后续的任何操作进行token的校验
- // await this.setUserInRedis(user);
- user = JSON.parse(JSON.stringify(user));
- delete user.password;
- delete user.meta;
- delete user.__v;
- const token = this.ctx.service.util.jwt.encrypt(user);
- return token;
- }
- /**
- * 微信登录
- * @param {Object} body 登陆参数
- * @param body.openid 微信小程序的openid
- */
- async wxLogin({ openid }) {
- const { populate } = this.getRefMods();
- const user = await this.model.findOne({ openid }).populate(populate);
- if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
- const { status } = user;
- if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
- delete user.meta;
- delete user.__v;
- const token = this.ctx.service.util.jwt.encrypt(user);
- return token;
- }
- }
- module.exports = UserService;
|