|
|
@@ -132,4 +132,60 @@ describe('access-token-parser middleware', () => {
|
|
|
expect(nextMock).toHaveBeenCalled();
|
|
|
});
|
|
|
|
|
|
+ it('should set req.user with a valid Bearer token in Authorization header', async() => {
|
|
|
+ // arrange
|
|
|
+ const reqMock = mock<AccessTokenParserReq>({
|
|
|
+ user: undefined,
|
|
|
+ headers: {
|
|
|
+ authorization: undefined,
|
|
|
+ },
|
|
|
+ });
|
|
|
+ const resMock = mock<Response>();
|
|
|
+ const nextMock = vi.fn();
|
|
|
+
|
|
|
+ expect(reqMock.user).toBeUndefined();
|
|
|
+
|
|
|
+ // prepare a user with an access token
|
|
|
+ const targetUser = await User.create({
|
|
|
+ name: faker.person.fullName(),
|
|
|
+ username: faker.string.uuid(),
|
|
|
+ password: faker.internet.password(),
|
|
|
+ lang: 'en_US',
|
|
|
+ apiToken: faker.internet.password(),
|
|
|
+ });
|
|
|
+
|
|
|
+ // act
|
|
|
+ reqMock.headers.authorization = `Bearer ${targetUser.apiToken}`;
|
|
|
+ await accessTokenParser(reqMock, resMock, nextMock);
|
|
|
+
|
|
|
+ // assert
|
|
|
+ expect(reqMock.user).toBeDefined();
|
|
|
+ expect(reqMock.user?._id).toStrictEqual(targetUser._id);
|
|
|
+ expect(serializeUserSecurely).toHaveBeenCalledOnce();
|
|
|
+ expect(nextMock).toHaveBeenCalled();
|
|
|
+ });
|
|
|
+
|
|
|
+ it('should ignore non-Bearer Authorization header', async() => {
|
|
|
+ // arrange
|
|
|
+ const reqMock = mock<AccessTokenParserReq>({
|
|
|
+ user: undefined,
|
|
|
+ headers: {
|
|
|
+ authorization: undefined,
|
|
|
+ },
|
|
|
+ });
|
|
|
+ const resMock = mock<Response>();
|
|
|
+ const nextMock = vi.fn();
|
|
|
+
|
|
|
+ expect(reqMock.user).toBeUndefined();
|
|
|
+
|
|
|
+ // act
|
|
|
+ reqMock.headers.authorization = 'Basic dXNlcjpwYXNz'; // Basic auth header
|
|
|
+ await accessTokenParser(reqMock, resMock, nextMock);
|
|
|
+
|
|
|
+ // assert
|
|
|
+ expect(reqMock.user).toBeUndefined();
|
|
|
+ expect(serializeUserSecurely).not.toHaveBeenCalled();
|
|
|
+ expect(nextMock).toHaveBeenCalled();
|
|
|
+ });
|
|
|
+
|
|
|
});
|