-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth.service.ts
More file actions
260 lines (206 loc) · 7.28 KB
/
auth.service.ts
File metadata and controls
260 lines (206 loc) · 7.28 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import { Inject, Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { CreateUser } from '@shared/validation/user/dto/CreateUser.dto';
import axios from 'axios';
import type { Request, Response } from 'express';
import type { UserDocument } from '@server/user/entity/user.entity';
import { UserService } from '@server/user/user.service';
import { DiscordUser } from './types/discordProfile';
import { GithubAccessToken, GithubEmailList } from './types/githubProfile';
import { GoogleProfile } from './types/googleProfile';
import { Profile } from './types/profile';
import { TokenPayload, Tokens } from './types/token';
@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);
constructor(
@Inject(UserService)
private readonly userService: UserService,
@Inject(JwtService)
private readonly jwtService: JwtService,
@Inject('COOKIE_EXPIRES_IN')
private readonly COOKIE_EXPIRES_IN: string,
@Inject('FRONTEND_URL')
private readonly FRONTEND_URL: string,
@Inject('JWT_SECRET')
private readonly JWT_SECRET: string,
@Inject('JWT_EXPIRES_IN')
private readonly JWT_EXPIRES_IN: string,
@Inject('JWT_REFRESH_SECRET')
private readonly JWT_REFRESH_SECRET: string,
@Inject('JWT_REFRESH_EXPIRES_IN')
private readonly JWT_REFRESH_EXPIRES_IN: string,
@Inject('WHITELISTED_USERS')
private readonly WHITELISTED_USERS: string,
@Inject('APP_DOMAIN')
private readonly APP_DOMAIN?: string,
) {}
public async verifyToken(req: Request, res: Response) {
const headers = req.headers;
const authorizationHeader = headers.authorization;
if (!authorizationHeader) {
return res.status(401).json({ message: 'No authorization header' });
}
const token = authorizationHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'No token provided' });
}
try {
const decoded = this.jwtService.verify(token, {
secret: this.JWT_SECRET,
});
// verify if user exists
const user_registered = await this.userService.findByID(decoded.id);
if (!user_registered) {
return res.status(401).json({ message: 'Unauthorized' });
} else {
return decoded;
}
} catch (error) {
return res.status(401).json({ message: 'Unauthorized' });
}
}
public async googleLogin(req: Request, res: Response) {
const user = req.user as GoogleProfile;
const email = user.emails[0].value;
const profile = {
// Generate username from display name
username: email.split('@')[0],
email: email,
profileImage: user.photos[0].value,
};
if (!(await this.verifyWhitelist(profile.username))) {
return res.redirect(this.FRONTEND_URL + '/login');
}
// verify if user exists
const user_registered = await this.verifyAndGetUser(profile);
return this.GenTokenRedirect(user_registered, res);
}
private async createNewUser(user: Profile) {
const { username, email, profileImage } = user;
const baseUsername = username;
const newUsername = await this.userService.generateUsername(baseUsername);
const newUser = new CreateUser({
username: newUsername,
email: email,
profileImage: profileImage,
});
return await this.userService.create(newUser);
}
private async verifyAndGetUser(user: Profile) {
const user_registered = await this.userService.findByEmail(user.email);
if (!user_registered) {
return await this.createNewUser(user);
}
// Update profile picture if it has changed
if (user_registered.profileImage !== user.profileImage) {
user_registered.profileImage = user.profileImage;
await user_registered.save();
}
return user_registered;
}
private async verifyWhitelist(username: string) {
const whitelist = this.WHITELISTED_USERS;
if (whitelist.length === 0) {
return true;
}
if (whitelist.includes(username.toLowerCase())) {
this.logger.log(`User ${username} is whitelisted; approving login`);
return true;
}
this.logger.log(`User ${username} is not whitelisted; rejecting login`);
return false;
}
public async githubLogin(req: Request, res: Response) {
const user = req.user as GithubAccessToken;
const { profile } = user;
// verify if user exists
const response = await axios.get<GithubEmailList>(
'https://api.github.com/user/emails',
{
headers: {
Authorization: `token ${user.accessToken}`,
},
},
);
const email = response.data.filter((email) => email.primary)[0].email;
if (!(await this.verifyWhitelist(profile.username))) {
return res.redirect(this.FRONTEND_URL + '/login');
}
const user_registered = await this.verifyAndGetUser({
username: profile.username,
email: email,
profileImage: profile.photos[0].value,
});
return this.GenTokenRedirect(user_registered, res);
}
public async discordLogin(req: Request, res: Response) {
const user = (req.user as DiscordUser).profile;
const profilePictureUrl = `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png`;
const profile = {
// Generate username from display name
username: user.username,
email: user.email,
profileImage: profilePictureUrl,
};
if (!(await this.verifyWhitelist(profile.username))) {
return res.redirect(this.FRONTEND_URL + '/login');
}
// verify if user exists
const user_registered = await this.verifyAndGetUser(profile);
return this.GenTokenRedirect(user_registered, res);
}
public async loginWithEmail(req: Request, res: Response) {
const user = req.user as UserDocument;
if (!user) {
return res.redirect(this.FRONTEND_URL + '/login');
}
return this.GenTokenRedirect(user, res);
}
public async createJwtPayload(payload: TokenPayload): Promise<Tokens> {
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(payload, {
secret: this.JWT_SECRET,
expiresIn: this.JWT_EXPIRES_IN,
}),
this.jwtService.signAsync(payload, {
secret: this.JWT_REFRESH_SECRET,
expiresIn: this.JWT_REFRESH_EXPIRES_IN,
}),
]);
return {
access_token: accessToken,
refresh_token: refreshToken,
};
}
private async GenTokenRedirect(
user_registered: UserDocument,
res: Response<any, Record<string, any>>,
): Promise<void> {
const token = await this.createJwtPayload({
id: user_registered._id.toString(),
email: user_registered.email,
username: user_registered.username,
});
const frontEndURL = this.FRONTEND_URL;
const domain = this.APP_DOMAIN;
const maxAge = parseInt(this.COOKIE_EXPIRES_IN) * 1000;
res.cookie('token', token.access_token, {
domain: domain,
maxAge: maxAge,
});
res.cookie('refresh_token', token.refresh_token, {
domain: domain,
maxAge: maxAge,
});
res.redirect(frontEndURL + '/');
}
public async getUserFromToken(token: string): Promise<UserDocument | null> {
const decoded = this.jwtService.decode(token) as TokenPayload;
if (!decoded) {
return null;
}
const user = await this.userService.findByID(decoded.id);
return user;
}
}