-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.service.ts
75 lines (65 loc) · 2.25 KB
/
auth.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
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { RegisterDto } from './dto/register.dto';
import { RegisterResponseDto } from './dto/register-response.dto';
import { saltRounds } from './constants';
import { SignInResponseDto } from './dto/sign-in-response.dto';
import { MailerService } from 'src/mailer/mailer.service';
import { appConfig } from 'src/config';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private mailer: MailerService,
) { }
async login(email: string, password: string): Promise<SignInResponseDto> {
const user = await this.usersService.findOneByEmail(email);
if (!user) {
throw new UnauthorizedException('User not found');
}
const match = await bcrypt.compare(password, user?.hashedPassword);
if (!match) {
throw new UnauthorizedException();
}
if (appConfig.enableMail) {
await this.mailer.sendTemplateMail({
templateType: 'login',
recipients: [email],
subject: 'Flux@Codegasms New Login Detected',
username: user.fullName,
});
} else {
console.log(`Simulating sending login mail to ${email}!`)
}
return {
access_token: await this.generateJwtToken(email),
};
}
async register(registerDto: RegisterDto): Promise<RegisterResponseDto> {
const hashedPassword = await bcrypt.hash(registerDto.password, saltRounds);
const user = await this.usersService.create({
email: registerDto.email,
fullName: registerDto.fullName,
hashedPassword: hashedPassword,
});
if (appConfig.enableMail) {
await this.mailer.sendTemplateMail({
templateType: 'register',
recipients: [user.email],
subject: 'Welcome to Flux@Codegasms',
username: user.fullName,
});
} else {
console.log(`Simulating sending registration mail to ${user.email}!`)
}
return {
access_token: await this.generateJwtToken(user.email),
};
}
async generateJwtToken(email: string) {
return await this.jwtService.signAsync({ sub: email });
}
}