habitica/test/api/unit/middlewares/auth.test.js

80 lines
2.4 KiB
JavaScript
Raw Normal View History

import {
generateRes,
generateReq,
2018-06-18 12:40:25 +00:00
} from '../../../helpers/api-unit.helper';
import { authWithHeaders as authWithHeadersFactory } from '../../../../website/server/middlewares/auth';
describe('auth middleware', () => {
2019-10-08 18:45:38 +00:00
let res; let req; let
user;
beforeEach(async () => {
res = generateRes();
req = generateReq();
user = await res.locals.user.save();
});
describe('auth with headers', () => {
2019-10-08 18:45:38 +00:00
it('allows to specify a list of user field that we do not want to load', done => {
const authWithHeaders = authWithHeadersFactory({
userFieldsToExclude: ['items'],
});
req.headers['x-api-user'] = user._id;
req.headers['x-api-key'] = user.apiToken;
2019-10-08 18:45:38 +00:00
authWithHeaders(req, res, err => {
if (err) return done(err);
const userToJSON = res.locals.user.toJSON();
expect(userToJSON.items).to.not.exist;
expect(userToJSON.auth).to.exist;
2019-10-08 18:45:38 +00:00
return done();
});
});
2019-10-08 18:45:38 +00:00
it('makes sure some fields are always included', done => {
const authWithHeaders = authWithHeadersFactory({
userFieldsToExclude: [
'items', 'auth.timestamps',
'preferences', 'notifications', '_id', 'flags', 'auth', // these are always loaded
],
});
req.headers['x-api-user'] = user._id;
req.headers['x-api-key'] = user.apiToken;
2019-10-08 18:45:38 +00:00
authWithHeaders(req, res, err => {
if (err) return done(err);
const userToJSON = res.locals.user.toJSON();
expect(userToJSON.items).to.not.exist;
expect(userToJSON.auth.timestamps).to.exist;
expect(userToJSON.auth).to.exist;
expect(userToJSON.notifications).to.exist;
expect(userToJSON.preferences).to.exist;
expect(userToJSON._id).to.exist;
expect(userToJSON.flags).to.exist;
2019-10-08 18:45:38 +00:00
return done();
});
});
it('errors with InvalidCredentialsError and code when token is wrong', done => {
const authWithHeaders = authWithHeadersFactory({ userFieldsToExclude: [] });
req.headers['x-api-user'] = user._id;
req.headers['x-api-key'] = 'totally-wrong-token';
authWithHeaders(req, res, err => {
expect(err).to.exist;
expect(err.name).to.equal('InvalidCredentialsError');
expect(err.code).to.equal('invalid_credentials');
expect(err.message).to.equal(res.t('invalidCredentials'));
return done();
});
});
});
});