-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth.service.spec.ts
More file actions
348 lines (281 loc) · 9.79 KB
/
auth.service.spec.ts
File metadata and controls
348 lines (281 loc) · 9.79 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import type { UserDocument } from '@nbw/database';
import { JwtService } from '@nestjs/jwt';
import { Test, TestingModule } from '@nestjs/testing';
import { beforeEach, describe, expect, it, jest, mock, spyOn } from 'bun:test';
import type { Request, Response } from 'express';
import { UserService } from '@server/user/user.service';
import { AuthService } from './auth.service';
import { Profile } from './types/profile';
const mockAxios = {
get: jest.fn(),
post: jest.fn(),
put: jest.fn(),
delete: jest.fn(),
create: jest.fn(),
};
mock.module('axios', () => mockAxios);
const mockUserService = {
generateUsername: jest.fn(),
findByEmail: jest.fn(),
findByID: jest.fn(),
create: jest.fn(),
};
const mockJwtService = {
decode: jest.fn(),
signAsync: jest.fn(),
verify: jest.fn(),
};
describe('AuthService', () => {
let authService: AuthService;
let userService: UserService;
let jwtService: JwtService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthService,
{
provide: UserService,
useValue: mockUserService,
},
{
provide: JwtService,
useValue: mockJwtService,
},
{
provide: 'COOKIE_EXPIRES_IN',
useValue: '3600',
},
{
provide: 'FRONTEND_URL',
useValue: 'http://frontend.test.com',
},
{
provide: 'COOKIE_EXPIRES_IN',
useValue: '3600',
},
{
provide: 'JWT_SECRET',
useValue: 'test-jwt-secret',
},
{
provide: 'JWT_EXPIRES_IN',
useValue: '1d',
},
{
provide: 'JWT_REFRESH_SECRET',
useValue: 'test-jwt-refresh-secret',
},
{
provide: 'JWT_REFRESH_EXPIRES_IN',
useValue: '7d',
},
{
provide: 'WHITELISTED_USERS',
useValue: 'tomast1337,bentroen,testuser',
},
{
provide: 'APP_DOMAIN',
useValue: '.test.com',
},
],
}).compile();
authService = module.get<AuthService>(AuthService);
userService = module.get<UserService>(UserService);
jwtService = module.get<JwtService>(JwtService);
});
it('should be defined', () => {
expect(authService).toBeDefined();
});
describe('verifyToken', () => {
it('should throw an error if no authorization header is provided', async () => {
const req = { headers: {} } as Request;
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as any;
await authService.verifyToken(req, res);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({
message: 'No authorization header',
});
});
it('should throw an error if no token is provided', async () => {
const req = { headers: { authorization: 'Bearer ' } } as Request;
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as any;
await authService.verifyToken(req, res);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ message: 'No token provided' });
});
it('should throw an error if user is not found', async () => {
const req = {
headers: { authorization: 'Bearer test-token' },
} as Request;
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as any;
mockJwtService.verify.mockReturnValueOnce({ id: 'test-id' });
mockUserService.findByID.mockResolvedValueOnce(null);
await authService.verifyToken(req, res);
expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ message: 'Unauthorized' });
});
it('should return decoded token if user is found', async () => {
const req = {
headers: { authorization: 'Bearer test-token' },
} as Request;
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as any;
const decodedToken = { id: 'test-id' };
mockJwtService.verify.mockReturnValueOnce(decodedToken);
mockUserService.findByID.mockResolvedValueOnce({ id: 'test-id' });
const result = await authService.verifyToken(req, res);
expect(result).toEqual(decodedToken);
});
});
describe('getUserFromToken', () => {
it('should return null if token is invalid', async () => {
mockJwtService.decode.mockReturnValueOnce(null);
const result = await authService.getUserFromToken('invalid-token');
expect(result).toBeNull();
});
it('should return user if token is valid', async () => {
const decodedToken = { id: 'test-id' };
mockJwtService.decode.mockReturnValueOnce(decodedToken);
mockUserService.findByID.mockResolvedValueOnce({ id: 'test-id' });
const result = await authService.getUserFromToken('valid-token');
expect(result).toEqual({ id: 'test-id' } as UserDocument);
});
});
describe('createJwtPayload', () => {
it('should create access and refresh tokens', async () => {
const payload = { id: 'user-id', username: 'testuser' };
const accessToken = 'access-token';
const refreshToken = 'refresh-token';
spyOn(jwtService, 'signAsync').mockImplementation(
(payload: any, options: any) => {
if (options.secret === 'test-jwt-secret') {
return Promise.resolve(accessToken);
} else if (options.secret === 'test-jwt-refresh-secret') {
return Promise.resolve(refreshToken);
}
return Promise.reject(new Error('Invalid secret'));
},
);
const tokens = await (authService as any).createJwtPayload(payload);
expect(tokens).toEqual({
access_token: accessToken,
refresh_token: refreshToken,
});
expect(jwtService.signAsync).toHaveBeenCalledWith(payload, {
secret: 'test-jwt-secret',
expiresIn: '1d',
});
expect(jwtService.signAsync).toHaveBeenCalledWith(payload, {
secret: 'test-jwt-refresh-secret',
expiresIn: '7d',
});
});
});
describe('GenTokenRedirect', () => {
it('should set cookies and redirect to the frontend URL', async () => {
const user_registered = {
_id: 'user-id',
email: '[email protected]',
username: 'testuser',
} as unknown as UserDocument;
const res = {
cookie: jest.fn(),
redirect: jest.fn(),
} as unknown as Response;
const tokens = {
access_token: 'access-token',
refresh_token: 'refresh-token',
};
spyOn(authService as any, 'createJwtPayload').mockResolvedValue(tokens);
await (authService as any).GenTokenRedirect(user_registered, res);
expect((authService as any).createJwtPayload).toHaveBeenCalledWith({
id: 'user-id',
email: '[email protected]',
username: 'testuser',
});
expect(res.cookie).toHaveBeenCalledWith('token', 'access-token', {
domain: '.test.com',
maxAge: 3600000,
path: '/',
});
expect(res.cookie).toHaveBeenCalledWith(
'refresh_token',
'refresh-token',
{
domain: '.test.com',
maxAge: 3600000,
path: '/',
},
);
expect(res.redirect).toHaveBeenCalledWith('http://frontend.test.com/');
});
});
describe('verifyAndGetUser', () => {
it('should create a new user if the user is not registered', async () => {
const user: Profile = {
username: 'testuser',
email: '[email protected]',
profileImage: 'http://example.com/photo.jpg',
};
mockUserService.generateUsername.mockResolvedValue('testuser');
mockUserService.findByEmail.mockResolvedValue(null);
mockUserService.create.mockResolvedValue({ id: 'new-user-id' });
const result = await (authService as any).verifyAndGetUser(user);
expect(userService.findByEmail).toHaveBeenCalledWith('[email protected]');
expect(userService.create).toHaveBeenCalledWith(
expect.objectContaining({
email: '[email protected]',
profileImage: 'http://example.com/photo.jpg',
}),
);
expect(result).toEqual({ id: 'new-user-id' });
});
it('should return the registered user if the user is already registered', async () => {
const user: Profile = {
username: 'testuser',
email: '[email protected]',
profileImage: 'http://example.com/photo.jpg',
};
const registeredUser = {
id: 'registered-user-id',
profileImage: 'http://example.com/photo.jpg',
};
mockUserService.findByEmail.mockResolvedValue(registeredUser);
const result = await (authService as any).verifyAndGetUser(user);
expect(userService.findByEmail).toHaveBeenCalledWith('[email protected]');
expect(result).toEqual(registeredUser);
});
it('should update the profile image if it has changed', async () => {
const user: Profile = {
username: 'testuser',
email: '[email protected]',
profileImage: 'http://example.com/new-photo.jpg',
};
const registeredUser = {
id: 'registered-user-id',
profileImage: 'http://example.com/old-photo.jpg',
save: jest.fn(),
};
mockUserService.findByEmail.mockResolvedValue(registeredUser);
const result = await (authService as any).verifyAndGetUser(user);
expect(userService.findByEmail).toHaveBeenCalledWith('[email protected]');
expect(registeredUser.profileImage).toEqual(
'http://example.com/new-photo.jpg',
);
expect(registeredUser.save).toHaveBeenCalled();
expect(result).toEqual(registeredUser);
});
});
describe('createNewUser', () => undefined);
});