File size: 7,058 Bytes
db242f8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
import { compare, hashSync } from 'bcrypt';
import { Redis } from 'ioredis';
import * as Joi from 'joi';
import { CustomPrismaService } from 'nestjs-prisma';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { Inject, Injectable } from '@nestjs/common';
import { Role } from '@prisma/client';
import { BizException } from '@/common/exceptions/biz.exception';
import { EmailService } from '@/libs/email/email.service';
import { JwtService } from '@/libs/jwt/jwt.service';
import { SmsService } from '@/libs/sms/sms.service';
import { ExtendedPrismaClient } from '@/processors/database/prisma.extension';
import { IAccountStatus } from 'shared';
import { ErrorCodeEnum } from 'shared/dist/error-code';
type ByPassword = {
identity: string;
password: string;
};
const SALT_ROUNDS = 10;
const emailSchema = Joi.string().email().required();
const phoneSchema = Joi.string()
.pattern(/^[0-9]{11}$/)
.required();
const getPhoneOrEmail = (identity: string) => {
const emailValidation = emailSchema.validate(identity);
const phoneValidation = phoneSchema.validate(identity);
if (!emailValidation.error) {
return { email: identity.trim().toLowerCase(), phone: undefined };
} else if (!phoneValidation.error) {
return { email: undefined, phone: identity.trim() };
} else {
throw Error('Invalid identity');
}
};
function generateRandomSixDigitNumber() {
const min = 100000;
const max = 999999;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
@Injectable()
export class AuthService {
constructor(
@InjectRedis() private readonly redis: Redis,
@Inject('PrismaService')
private prisma: CustomPrismaService<ExtendedPrismaClient>,
private jwt: JwtService,
private emailService: EmailService,
private smsService: SmsService,
) {}
/* 通常来说是最后一步:
* 1. 检查是否绑定账户
* 2. 检查是否设置密码
*/
async #signWithCheck(user: any): Promise<{
token: string;
status: IAccountStatus;
}> {
let status: IAccountStatus = 'ok';
if (!user.email && !user.phone) {
status = 'bind';
} else if (!user.password) {
status = 'password';
}
return {
token: await this.jwt.sign({ id: user.id, role: user.role }),
status,
};
}
async #verifyCode(identity: string, code: string) {
const isValid = (await this.redis.get(identity)) === code;
if (!isValid) {
throw new BizException(ErrorCodeEnum.CodeValidationError);
} else {
await this.redis.del(identity);
}
}
/* 添加验证码 */
async newValidateCode(identity: string) {
const { email, phone } = getPhoneOrEmail(identity);
if (!email && !phone) {
return {
success: false,
};
}
const ttl = await this.redis.ttl(identity);
/* if key not exist, ttl will be -2 */
if (600 - ttl < 60) {
return {
success: false,
ttl,
};
} else {
const newTtl = 10 * 60;
const code = generateRandomSixDigitNumber();
await this.redis.setex(identity, newTtl, code);
if (email) {
await this.emailService.sendCode(identity, code);
} else if (phone) {
await this.smsService.sendCode(identity, code);
}
return {
success: true,
ttl: newTtl,
};
}
}
/* 通过验证码登录/注册 */
async WithValidateCode(identity: string, code: string) {
const { email, phone } = getPhoneOrEmail(identity);
await this.#verifyCode(identity, code);
const existUser = await this.prisma.client.user.findMany({
where: {
OR: [{ email }, { phone }],
},
});
let user;
if (existUser.length != 1) {
// 注册用户
user = await this.prisma.client.user.create({
data: {
email: email,
phone: phone,
role: Role.User,
},
});
} else {
user = existUser[0];
}
return this.#signWithCheck(user);
}
/* 通过密码登录 */
async loginPassword({ identity, password }: ByPassword) {
const { email, phone } = getPhoneOrEmail(identity);
const user = await this.prisma.client.user.findMany({
where: {
OR: [{ email }, { phone }],
},
});
if (user.length != 1) {
throw Error('User does not exist');
}
const isPasswordCorrect = await compare(password, user[0].password);
if (!isPasswordCorrect) {
throw Error('Password is incorrect');
}
return this.#signWithCheck(user[0]);
}
/* 添加密码 */
async bindPassword(userId: number, password: string) {
const user = await this.prisma.client.user.findUniqueOrThrow({
where: {
id: userId,
},
});
if (user.password) {
throw Error('Password already exists');
}
return await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
password: hashSync(password, SALT_ROUNDS),
},
});
}
async updateName(userId: number, name: string) {
await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
name: name,
},
});
}
/* 修改密码 */
async changePassword(userId: number, password: string) {
await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
password: hashSync(password, SALT_ROUNDS),
},
});
}
/* 找回密码 */
async forgetPassword(identity: string, code: string, password: string) {
const { email, phone } = getPhoneOrEmail(identity);
await this.#verifyCode(identity, code);
const existUser = await this.prisma.client.user.findMany({
where: {
OR: [{ email }, { phone }],
},
});
let user;
if (existUser.length != 1) {
throw new BizException(ErrorCodeEnum.UserNotExist);
} else {
user = existUser[0];
}
await this.changePassword(user.id, password);
return this.#signWithCheck(user);
}
/* 绑定用户身份 */
async bindIdentity(userId: number, identity: string, password?: string) {
const { email, phone } = getPhoneOrEmail(identity);
const user = await this.prisma.client.user.findUniqueOrThrow({
where: {
id: userId,
},
});
if (email) {
if (user.email) {
throw new BizException(ErrorCodeEnum.BindEmailExist);
}
await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
email: email,
},
});
}
if (phone) {
if (user.phone) {
throw new BizException(ErrorCodeEnum.BindPhoneExist);
}
await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
phone: phone,
},
});
}
if (password) {
await this.prisma.client.user.update({
where: {
id: userId,
},
data: {
password: hashSync(password, SALT_ROUNDS),
},
});
}
}
}
|