/* * @author gs * @date 2020/07/21 13:23 */ import { Inject, Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { v1 as uuidV1 } from 'uuid'; import { User } from '../model/user'; import { BaseService } from '../../../base/base.service'; import { MongoDBCollection } from '../../../constant'; import { AuthService, TokenModel } from '../../auth'; import { SMSService } from '../../smscode/service/sms.service'; import { SMSCode } from '../../smscode/model/sms'; import { ServerError } from '../../../common/error/server.error'; @Injectable() export class UserService extends BaseService { constructor( @InjectModel(MongoDBCollection.User) protected readonly model: Model, @Inject('AuthService') private readonly authService: AuthService, @Inject('SMSService') private readonly smsService: SMSService ) { super(model); } async refreshToken(userId: string): Promise { let tokenModel = await this.authService.findOne({ userId }); const expirationDate = new Date(); expirationDate.setDate(new Date().getDate() + 30); if (tokenModel) { tokenModel.expiration = expirationDate; tokenModel.value = uuidV1(); tokenModel = await tokenModel.save(); } else { tokenModel = await this.authService.create({ userId, expiration: expirationDate, value: uuidV1() }); } return tokenModel; } async findUserByPhone(phone: string): Promise { return this.findOne({ phone }); } async findUserByEmail(email: string): Promise { return this.findOne({ email }); } async getSMSCodeValidationResult( phone: string, smsCode: string ): Promise<{ status: boolean; model: SMSCode }> { const smsModel = await this.smsService.findOne({ phone }); if (!smsModel) { throw ServerError.code.SMSCodeNotMatch; } if ( (smsModel.invalidAt && new Date().getTime() > smsModel.invalidAt.getTime()) || !smsModel.status ) { throw ServerError.code.SMSCodeExpired; } return { status: smsModel.code === smsCode, model: smsModel }; } }