-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.service.ts
77 lines (63 loc) · 2.56 KB
/
crypto.service.ts
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
import { ForbiddenException, Injectable, InternalServerErrorException, NotAcceptableException, UnauthorizedException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { JwtService } from '@nestjs/jwt'
import { JsonWebTokenError, TokenExpiredError } from 'jsonwebtoken'
import { Users, UserStatus } from '../entity'
import shajs from 'sha.js'
@Injectable()
export class CryptoService {
private readonly jwtService: JwtService
private readonly SERVER_TOKEN: string
constructor (jwtService: JwtService, configService: ConfigService) {
this.jwtService = jwtService
this.SERVER_TOKEN = configService.get<string>('SERVER_TOKEN', 'youshallnotpass')
}
/** generate client token with provided user entity */
public generateClientToken (user: Users): string {
if ([UserStatus.BLOCKED, UserStatus.DELETED].includes(user.status)) {
throw new ForbiddenException('USER_STATUS_NOT_ALLOWED_TO_GENERATE_CLIENT_TOKEN')
}
return this.jwtService.sign({ sub: user.id })
}
/** verify client token and returns client user id (if malformed, throw an error) */
public verifyClientToken (token: string): number {
try {
const payload = this.jwtService.verify(token) as { sub?: unknown }
if (typeof payload?.sub !== 'number') {
throw new NotAcceptableException('TOKEN_MALFORMED')
}
return payload.sub
} catch (e) {
if (e instanceof JsonWebTokenError) {
throw new NotAcceptableException('TOKEN_MALFORMED')
}
if (e instanceof TokenExpiredError) {
throw new UnauthorizedException('TOKEN_EXPIRED')
}
throw new InternalServerErrorException('JWT_SERVICE_ERROR')
}
}
/** verify server token and returns result (true: acceptable / false: unauthorized) */
public verifyServerToken (token: string): boolean {
return token === this.SERVER_TOKEN
}
/** verify user password and returns result (true: valied password, false: invalied password) */
public verifyUserPassword (password: string, user: Users): boolean {
const hashedPassword =
shajs('sha512')
.update(user.salt + password)
.digest('hex')
return hashedPassword === user.password
}
/** generate new salt string */
public generateSalt (): string {
return new Array(4)
.fill(1)
.map(() => String.fromCharCode(Math.floor(Math.random() * 11139) + 44032))
.join('')
}
/** sha512 hash with provided password & salt */
public hashUserPassword (password: string, salt: string): string {
return shajs('sha512').update(salt + password).digest('hex')
}
}