|
@@ -1,28 +1,25 @@
|
|
import { RedisService } from '@/redis/redis.service'
|
|
import { RedisService } from '@/redis/redis.service'
|
|
import { Injectable } from '@nestjs/common'
|
|
import { Injectable } from '@nestjs/common'
|
|
-
|
|
|
|
|
|
+import { ConfigService } from '@nestjs/config'
|
|
|
|
+import { createCipheriv, createDecipheriv } from 'crypto'
|
|
@Injectable()
|
|
@Injectable()
|
|
export class CodService {
|
|
export class CodService {
|
|
- constructor(private readonly redisservice: RedisService) {}
|
|
|
|
- async getcod(ip: string) {
|
|
|
|
|
|
+ constructor(private readonly redisservice: RedisService, private configservice: ConfigService) {}
|
|
|
|
+ async getCod(ip: string) {
|
|
const cod = this.randomString(6)
|
|
const cod = this.randomString(6)
|
|
- await this.redisservice.set(`cod${ip}`, cod, 'EX', 60)
|
|
|
|
|
|
+ await this.redisservice.set(`cod:${ip}`, this.encrypt(cod), 'EX', 60)
|
|
return { status: true, msg: '验证码已发送', cod }
|
|
return { status: true, msg: '验证码已发送', cod }
|
|
}
|
|
}
|
|
- async verifycod(ip: string, cod: string) {
|
|
|
|
- //是否存在
|
|
|
|
- const cod1 = await this.redisservice.get(`cod${ip}`)
|
|
|
|
- if (!cod1) {
|
|
|
|
|
|
+ async verifyCod(ip: string, cod: string) {
|
|
|
|
+ const Rcod = await this.redisservice.get(`cod:${ip}`)
|
|
|
|
+ if (!Rcod) {
|
|
return { status: false, msg: '验证码不存在' }
|
|
return { status: false, msg: '验证码不存在' }
|
|
}
|
|
}
|
|
- //是否正确
|
|
|
|
- if (cod1 !== cod) {
|
|
|
|
- await this.redisservice.del(`cod${ip}`)
|
|
|
|
|
|
+ if (Rcod === this.decrypt(cod)) {
|
|
|
|
+ await this.redisservice.del(`cod:${ip}`)
|
|
return { status: false, msg: '验证码错误' }
|
|
return { status: false, msg: '验证码错误' }
|
|
}
|
|
}
|
|
- //是否过期
|
|
|
|
- const ttl = await this.redisservice.ttl(`cod${ip}`)
|
|
|
|
- if (ttl < 0) {
|
|
|
|
|
|
+ if ((await this.redisservice.ttl(`cod:${ip}`)) < 0) {
|
|
return { status: false, msg: '验证码已过期' }
|
|
return { status: false, msg: '验证码已过期' }
|
|
}
|
|
}
|
|
return { status: true, msg: '验证码正确' }
|
|
return { status: true, msg: '验证码正确' }
|
|
@@ -37,4 +34,22 @@ export class CodService {
|
|
}
|
|
}
|
|
return pwd
|
|
return pwd
|
|
}
|
|
}
|
|
|
|
+ private encrypt(
|
|
|
|
+ data: string,
|
|
|
|
+ key: string = this.configservice.get('CODE_KEY'),
|
|
|
|
+ iv: string = this.configservice.get('CODE_IV'),
|
|
|
|
+ ) {
|
|
|
|
+ const cipher = createCipheriv('aes192', Buffer.from(key, 'utf-8'), iv)
|
|
|
|
+ cipher.update(data, 'utf-8', 'hex')
|
|
|
|
+ return cipher.final('hex')
|
|
|
|
+ }
|
|
|
|
+ private decrypt(
|
|
|
|
+ encrypted: string,
|
|
|
|
+ key: string = this.configservice.get('CODE_KEY'),
|
|
|
|
+ iv: string = this.configservice.get('CODE_IV'),
|
|
|
|
+ ) {
|
|
|
|
+ const decipher = createDecipheriv('aes192', Buffer.from(key, 'utf-8'), iv)
|
|
|
|
+ decipher.update(encrypted, 'hex', 'utf8')
|
|
|
|
+ return decipher.final('utf8')
|
|
|
|
+ }
|
|
}
|
|
}
|