-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth-api.test.ts
291 lines (236 loc) · 8.02 KB
/
auth-api.test.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
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
import supertest from 'supertest';
import jwt, { JwtPayload } from 'jsonwebtoken';
import app from '../src/app';
import testHelpers from './helpers/test-helpers';
import { testMongodb } from '../src/mongo';
import { User } from '../src/types';
import config from '../src/utils/config';
const api = supertest(app);
const LOGIN_URL = '/api/auth/login';
const REFRESH_URL = '/api/auth/refresh';
const { JWT_SECRET } = config;
beforeAll(async () => { await testMongodb.connect(); });
beforeEach(async () => { await testMongodb.clear(); });
afterAll(async () => { await testMongodb.close(); });
let testUser: User;
describe('successful login', () => {
beforeEach(async () => {
testUser = await testHelpers.createTestUser({
username: 'admin',
fullName: 'Bobby Bo',
email: 'bobby@email.com',
password: 'secret',
});
});
test('responds with 200 code and returns JSON', async () => {
await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' })
.expect(200)
.expect('Content-Type', /application\/json/);
});
test('responds with the access token', async () => {
const response = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' });
expect(response.body.accessToken).toBeDefined();
});
test('decoded access token contains username and id', async () => {
const response = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' });
const decodedToken = jwt.verify(
response.body.accessToken,
JWT_SECRET || '',
) as JwtPayload;
expect(decodedToken).toBeDefined();
expect(decodedToken.id).toBe(testUser.id);
expect(decodedToken.username).toBe(testUser.username);
});
test('sets a cookie with the refresh token', async () => {
const response = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' });
const refreshTokenCookie = response.header['set-cookie'][0];
expect(refreshTokenCookie).toBeDefined();
expect(refreshTokenCookie).toMatch(/refreshToken=/);
const refreshToken = refreshTokenCookie.split(';')[0].split('=')[1];
const decodedToken = jwt.verify(
refreshToken,
JWT_SECRET || '',
) as JwtPayload;
expect(decodedToken).toBeDefined();
expect(decodedToken.id).toBe(testUser.id);
expect(decodedToken.username).toBe(testUser.username);
});
});
describe('unsuccessful login', () => {
test('login with non-existing username fails with 401 error code', async () => {
const nonExistingUser = {
username: 'i dont exist',
password: 'i also dont exist',
};
const response = await api
.post(LOGIN_URL)
.send(nonExistingUser)
.expect(401)
.expect('Content-Type', /application\/json/);
expect(response.body.error).toMatch(/invalid username or password/i);
});
test('login with wrong password responds with 401 error code', async () => {
const user = await testHelpers.createTestUser({
username: 'admin',
fullName: 'Bobby Bo',
email: 'bobby@email.com',
password: 'secret',
});
const invalidLoginInfo = {
username: user.username,
password: 'wrong password',
};
const response = await api
.post(LOGIN_URL)
.send(invalidLoginInfo)
.expect(401)
.expect('Content-Type', /application\/json/);
expect(response.body.error).toMatch(/invalid username or password/i);
});
test('does not set a cookie with the refresh token', async () => {
const user = await testHelpers.createTestUser({
username: 'admin',
fullName: 'Bobby Bo',
email: 'bobby@email.com',
password: 'secret',
});
const invalidLoginInfo = {
username: user.username,
password: 'wrong password',
};
const response = await api
.post(LOGIN_URL)
.send(invalidLoginInfo)
.expect(401)
.expect('Content-Type', /application\/json/);
expect(response.headers['set-cookie']).toBeUndefined();
});
});
describe('successful token refresh', () => {
let refreshTokenCookie: string;
beforeEach(async () => {
testUser = await testHelpers.createTestUser({
username: 'admin',
fullName: 'Bobby Bo',
email: 'bobby@email.com',
password: 'secret',
});
const response = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' })
.expect(200);
[refreshTokenCookie] = response.header['set-cookie'];
});
test('responds with 200 code and returns JSON', async () => {
await api
.post('/api/auth/refresh')
.expect(200)
.set('Cookie', refreshTokenCookie)
.expect('Content-Type', /application\/json/);
});
test('responds with a new access token and username', async () => {
const response = await api
.post('/api/auth/refresh')
.set('Cookie', refreshTokenCookie);
expect(response.body.accessToken).toBeDefined();
expect(response.body.username).toBeDefined();
expect(response.body.username).toBe(testUser.username);
});
test('decoded access token contains username and id', async () => {
const response = await api
.post('/api/auth/refresh')
.set('Cookie', refreshTokenCookie);
const decodedToken = jwt.verify(
response.body.accessToken,
JWT_SECRET || '',
) as JwtPayload;
expect(decodedToken).toBeDefined();
expect(decodedToken.id).toBe(testUser.id);
expect(decodedToken.username).toBe(testUser.username);
});
test('when user updates their username and refreshes token, the new username is returned', async () => {
const updatedUserFields = { username: 'newusername' };
// logging in to get access token
const loginResponse = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' });
const { accessToken } = loginResponse.body;
await api
.put(`/api/users/${testUser.id}`)
.send(updatedUserFields)
.set('authorization', `bearer ${accessToken}`)
.expect(200);
const refreshResponse = await api
.post('/api/auth/refresh')
.set('Cookie', refreshTokenCookie);
expect(refreshResponse.body.username).toBe(updatedUserFields.username);
});
});
describe('unsuccessful token refresh', () => {
test('responds with 401 code if no refresh token is sent', async () => {
await api
.post(REFRESH_URL)
.expect(401);
});
test('returns no access token', async () => {
const response = await api
.post(REFRESH_URL)
.expect(401);
expect(response.body.accessToken).toBeUndefined();
});
test('responds with 401 code if invalid refresh token is sent', async () => {
await api
.post(REFRESH_URL)
.set('Cookie', 'refreshToken=invalidtoken')
.expect(401);
});
test('responds with 401 code if expired refresh token is sent', async () => {
const expiredToken = jwt.sign(
{ id: '123', username: 'test' },
JWT_SECRET || '',
{ expiresIn: -1 },
);
await api
.post(REFRESH_URL)
.set('Cookie', `refreshToken=${expiredToken}`)
.expect(401);
});
});
describe('logout', () => {
let refreshTokenCookie: string;
beforeEach(async () => {
testUser = await testHelpers.createTestUser({
username: 'admin',
fullName: 'Bobby Bo',
email: 'bobby@email.com',
password: 'secret',
});
const response = await api
.post(LOGIN_URL)
.send({ username: testUser.username, password: 'secret' })
.expect(200);
[refreshTokenCookie] = response.header['set-cookie'];
});
test('responds with 204 code', async () => {
await api
.post('/api/auth/logout')
.set('Cookie', refreshTokenCookie)
.expect(204);
});
test('clears the refresh token cookie', async () => {
const response = await api
.post('/api/auth/logout')
.set('Cookie', refreshTokenCookie);
const setCookieHeader = response.headers['set-cookie'];
expect(setCookieHeader).toBeDefined();
expect(setCookieHeader[0]).toMatch(/refreshToken=;/);
});
});