test(middleware-jwt): integration tests
ADD
packages/middleware-jwt/test/api.integration.spec.ts
+import * as request from 'supertest';
+import { verifyToken } from '../src';
+import { app, SECRET_KEY } from './api.integration';
+
+const LOGIN_CREDENTIALS = { email: 'admin@admin.com', password: 'admin' };
+
+describe('API integration', () => {
+ test('POST /api/login returns token and verifies its correctness', async () =>
+ request(app)
+ .post('/api/login')
+ .send(LOGIN_CREDENTIALS)
+ .expect(200)
+ .then(req => {
+ const { token } = req.body;
+ expect(token).toBeDefined();
+ expect(typeof token).toBe('string');
+
+ const payload = verifyToken<any>({ secret: SECRET_KEY })(token);
+ expect(payload.id).toEqual('test_id');
+ expect(payload.email).toEqual('admin@admin.com');
+ }));
+
+ test('GET /api/secured authorizes request and checks the `req.user` object', async () => {
+ const token = await request(app)
+ .post('/api/login')
+ .send(LOGIN_CREDENTIALS)
+ .expect(200)
+ .then(req => req.body.token as string);
+
+ return request(app)
+ .get('/api/secured')
+ .set('Authorization', `Bearer ${token}`)
+ .expect(200)
+ .then(req => {
+ const user = req.body;
+ expect(user.id).toEqual('test_id');
+ expect(user.email).toEqual(LOGIN_CREDENTIALS.email);
+ expect(user.password).toBeUndefined();
+ });
+ });
+
+ test('GET /api/secured authorizes request and checks the `req.user` object', async () =>
+ request(app)
+ .get('/api/secured')
+ .set('Authorization', `Bearer WRONG_TOKEN`)
+ .expect(401, { error: { status: 401, message: 'Unauthorized' }}));
+});

ADD
packages/middleware-jwt/test/api.integration.ts
+import { authorize$, generateToken } from '../src';
+import { httpListener, EffectFactory, combineRoutes } from '@marblejs/core';
+import { bodyParser$ } from '@marblejs/middleware-body';
+import { map, mapTo } from 'rxjs/operators';
+
+type LoginCredentials = { email: string, password: string };
+
+export const SECRET_KEY = 'SOME_SSH_KEY';
+
+const generateFakeJWTPayload = ({ email }: LoginCredentials) => ({ id: 'test_id', email });
+
+const login$ = EffectFactory
+ .matchPath('/login')
+ .matchType('POST')
+ .use(req$ => req$.pipe(
+ map(req => req.body as LoginCredentials),
+ map(generateFakeJWTPayload),
+ map(generateToken({ secret: SECRET_KEY })),
+ map(token => ({ body: { token } })),
+ ));
+
+const securedRoot$ = EffectFactory
+ .matchPath('/')
+ .matchType('GET')
+ .use(req$ => req$.pipe(
+ map(req => ({ body: req.user })),
+ ));
+
+const secured$ = combineRoutes('/secured', {
+ effects: [securedRoot$],
+ middlewares: [authorize$({ secret: SECRET_KEY })],
+});
+
+const api$ = combineRoutes('/api', [login$, secured$]);
+
+// bootstraping
+const middlewares = [bodyParser$];
+const effects = [api$];
+
+export const app = httpListener({ middlewares, effects });

test(middleware-jwt): integration tests