-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.service.ts
More file actions
159 lines (134 loc) · 5.16 KB
/
auth.service.ts
File metadata and controls
159 lines (134 loc) · 5.16 KB
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
import { UserNotFound, isError } from '@lib/core';
import { RepositoryService } from '@lib/repository';
import { UserEntity } from '@lib/repository/entities/user.entity';
import { Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { SHA256 } from 'crypto-js';
import { v4 } from 'uuid';
import { EnvConfig } from '../../config/config.model';
import { UserService } from '../user/user.service';
import { SignInBody, SignUpBody } from './common/auth.dto';
import {
CannotFindEmailConfirm,
EmailAlreadyConfirmed,
EmailNotConfirmed,
EmailOrPasswordIncorrect,
} from './common/auth.errors';
import { GetTokenResult } from './common/auth.model';
@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);
constructor(
private readonly jwt: JwtService,
private readonly rep: RepositoryService,
private readonly config: EnvConfig,
private readonly user: UserService,
) {}
async signUp(body: SignUpBody) {
const user = await this.user.createUser(body.email, body.password);
if (isError(user)) {
return user;
}
const sendEmailResult = await this.sendConfirmEmail(user);
if (isError(sendEmailResult)) {
return sendEmailResult;
}
}
async signIn(body: SignInBody): Promise<GetTokenResult | EmailOrPasswordIncorrect | EmailNotConfirmed> {
const hash = SHA256(body.password).toString();
const user = await this.rep.user.findOne({ where: { email: body.email, hash } });
if (!user) {
return new EmailOrPasswordIncorrect(body.email);
}
if (!user.emailConfirmed) {
return new EmailNotConfirmed(body.email);
}
const { accessToken, refreshToken, refreshTokenHash } = this.generateToken(user.id);
await this.rep.user.save({ id: user.id, refreshTokenHash });
return {
token: accessToken,
refreshCookie:
`Refresh=${refreshToken}; HttpOnly; ` + `Path=/; Max-Age=${this.config.JWT_REFRESH_EXPIRES_IN}`,
};
}
async signOut(id: number) {
const user = await this.rep.user.findOne({ where: { id } });
if (user) {
user.refreshTokenHash = null;
await this.rep.user.save(user);
}
}
async refresh(id: number): Promise<GetTokenResult | UserNotFound> {
const user = await this.rep.user.findOne({ where: { id } });
if (!user) {
return new UserNotFound({ userId: id });
}
const { accessToken, refreshToken, refreshTokenHash } = this.generateToken(id);
user.refreshTokenHash = refreshTokenHash;
await this.rep.user.save(user);
return {
token: accessToken,
refreshCookie:
`Refresh=${refreshToken}; HttpOnly; ` + `Path=/; Max-Age=${this.config.JWT_REFRESH_EXPIRES_IN}`,
};
}
async confirmEmail(token: string) {
const user = await this.rep.user.findOne({ where: { emailConfirmed: false, emailConfirmToken: token } });
if (user === null) {
return new CannotFindEmailConfirm();
}
user.emailConfirmed = true;
const { accessToken, refreshToken, refreshTokenHash } = this.generateToken(user.id);
user.refreshTokenHash = refreshTokenHash;
await this.rep.user.save(user);
this.logger.log({
message: 'Confirm email',
payload: { email: user.email, user: user.id, token },
});
return {
token: accessToken,
refreshCookie:
`Refresh=${refreshToken}; HttpOnly; ` + `Path=/; Max-Age=${this.config.JWT_REFRESH_EXPIRES_IN}`,
};
}
async sendConfirmEmail(user: UserEntity) {
if (user.emailConfirmed) {
return new EmailAlreadyConfirmed(user.id);
}
const token = v4();
user.emailConfirmToken = token;
await this.rep.user.save(user);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const link = `${this.config.DOMAIN}/auth/confirm-email?token=${token}`;
// await this.mailService.sendEmail(
// 'Please confirm email',
// `<a href="${link}">${link}</a>`,
// userResult.email,
// ); FIXME: Need mail service implementation
this.logger.log({
message: 'Send confirm email',
payload: { email: user.email, token, user: user.id },
});
}
private generateToken(id: number) {
const refreshToken = this.jwt.sign(
{ id, date: Date.now() },
{
secret: this.config.JWT_REFRESH_SECRET,
expiresIn: this.config.JWT_REFRESH_EXPIRES_IN,
},
);
const refreshTokenHash = SHA256(refreshToken).toString();
return {
refreshToken,
refreshTokenHash,
accessToken: this.jwt.sign(
{ id, date: Date.now() },
{
secret: this.config.JWT_SECRET,
expiresIn: this.config.JWT_EXPIRES_IN,
},
),
};
}
}