/
auth.service.ts
154 lines (132 loc) · 4.06 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
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
import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { User, IdentityProvider } from '@altairgraphql/db';
import { PrismaService } from 'nestjs-prisma';
import { SecurityConfig } from 'src/common/config';
import { ChangePasswordInput } from './models/change-password.input';
import { PasswordService } from './password/password.service';
import { Token } from '@altairgraphql/api-utils';
import { Request } from 'express';
@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly prisma: PrismaService,
private readonly passwordService: PasswordService,
private readonly configService: ConfigService
) {}
async passwordLogin(email: string, password: string) {
const user = await this.prisma.user.findUnique({ where: { email } });
if (!user) {
throw new NotFoundException(`No user found for email: ${email}`);
}
const passwordValid = await this.passwordService.validatePassword(
password,
user.password
);
if (!passwordValid) {
throw new BadRequestException('Invalid password');
}
return this.getLoginResponse(user);
}
googleLogin(req: Request) {
if (!req.user) {
throw new BadRequestException('No user from google');
}
return this.getLoginResponse(req.user);
}
getUserCredential(providerUserId: string, provider: IdentityProvider) {
return this.prisma.userCredential.findFirst({
where: {
providerUserId,
provider,
},
});
}
validateUser(userId: string): Promise<User> {
return this.prisma.user.findUnique({ where: { id: userId } });
}
getUserFromToken(token: string): Promise<User> {
const id = this.jwtService.decode(token)['userId'];
return this.prisma.user.findUnique({ where: { id } });
}
async changePassword(
userId: string,
userPassword: string,
changePassword: ChangePasswordInput
) {
const passwordValid = await this.passwordService.validatePassword(
changePassword.oldPassword,
userPassword
);
if (!passwordValid) {
throw new BadRequestException('Invalid password');
}
const hashedPassword = await this.passwordService.hashPassword(
changePassword.newPassword
);
return this.prisma.user.update({
data: {
password: hashedPassword,
},
where: { id: userId },
});
}
getLoginResponse(user: User) {
return {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
picture: user.picture,
tokens: this.generateTokens({ userId: user.id }),
};
}
generateTokens(payload: { userId: string }): Token {
return {
accessToken: this.generateAccessToken(payload),
refreshToken: this.generateRefreshToken(payload),
};
}
/**
* Generates a short-lived events token for the purpose of event connection
*/
getShortLivedEventsToken(userId: string): string {
const securityConfig = this.configService.get<SecurityConfig>('security');
return this.jwtService.sign(
{ userId },
{
secret: this.configService.get<string>('EVENTS_JWT_ACCESS_SECRET'),
expiresIn: securityConfig.shortExpiresIn,
}
);
}
private generateAccessToken(payload: { userId: string }): string {
return this.jwtService.sign(payload);
}
private generateRefreshToken(payload: { userId: string }): string {
const securityConfig = this.configService.get<SecurityConfig>('security');
return this.jwtService.sign(payload, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
expiresIn: securityConfig.refreshIn,
});
}
refreshToken(token: string) {
try {
const { userId } = this.jwtService.verify(token, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
});
return this.generateTokens({
userId,
});
} catch (e) {
throw new UnauthorizedException();
}
}
}