Merge pull request #602 from outline/authorization-improves
Authorization Improvements
This commit is contained in:
commit
fb19075d0e
@ -87,6 +87,7 @@
|
||||
"boundless-popover": "^1.0.4",
|
||||
"bugsnag": "^1.7.0",
|
||||
"bull": "^3.3.7",
|
||||
"cancan": "3.1.0",
|
||||
"copy-to-clipboard": "^3.0.6",
|
||||
"css-loader": "^0.28.7",
|
||||
"debug": "2.2.0",
|
||||
|
@ -63,6 +63,15 @@ Object {
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#documents.update should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
"message": "Authentication required",
|
||||
"ok": false,
|
||||
"status": 401,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#documents.viewed should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
|
@ -2,21 +2,23 @@
|
||||
|
||||
exports[`#team.addAdmin should promote a new admin 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": true,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"username": "user1",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.addAdmin should require admin 1`] = `
|
||||
Object {
|
||||
"error": "only_available_for_admins",
|
||||
"message": "Only available for admins",
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
@ -24,7 +26,14 @@ Object {
|
||||
|
||||
exports[`#team.removeAdmin should demote an admin 1`] = `
|
||||
Object {
|
||||
"avatarUrl": null,
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
@ -32,8 +41,8 @@ Object {
|
||||
|
||||
exports[`#team.removeAdmin should require admin 1`] = `
|
||||
Object {
|
||||
"error": "only_available_for_admins",
|
||||
"message": "Only available for admins",
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
@ -41,7 +50,7 @@ Object {
|
||||
|
||||
exports[`#team.removeAdmin shouldn't demote admins if only one available 1`] = `
|
||||
Object {
|
||||
"error": "at_least_one_admin_is_required",
|
||||
"error": "validation_error",
|
||||
"message": "At least one admin is required",
|
||||
"ok": false,
|
||||
"status": 400,
|
||||
|
19
server/api/__snapshots__/views.test.js.snap
Normal file
19
server/api/__snapshots__/views.test.js.snap
Normal file
@ -0,0 +1,19 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`#views.create should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
"message": "Authentication required",
|
||||
"ok": false,
|
||||
"status": 401,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#views.list should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
"message": "Authentication required",
|
||||
"ok": false,
|
||||
"status": 401,
|
||||
}
|
||||
`;
|
@ -1,12 +1,13 @@
|
||||
// @flow
|
||||
import Router from 'koa-router';
|
||||
import httpErrors from 'http-errors';
|
||||
|
||||
import auth from './middlewares/authentication';
|
||||
import pagination from './middlewares/pagination';
|
||||
import { presentApiKey } from '../presenters';
|
||||
import { ApiKey } from '../models';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('apiKeys.create', auth(), async ctx => {
|
||||
@ -14,6 +15,7 @@ router.post('apiKeys.create', auth(), async ctx => {
|
||||
ctx.assertPresent(name, 'name is required');
|
||||
|
||||
const user = ctx.state.user;
|
||||
authorize(user, 'create', ApiKey);
|
||||
|
||||
const key = await ApiKey.create({
|
||||
name,
|
||||
@ -36,9 +38,7 @@ router.post('apiKeys.list', auth(), pagination(), async ctx => {
|
||||
limit: ctx.state.pagination.limit,
|
||||
});
|
||||
|
||||
const data = keys.map(key => {
|
||||
return presentApiKey(ctx, key);
|
||||
});
|
||||
const data = keys.map(key => presentApiKey(ctx, key));
|
||||
|
||||
ctx.body = {
|
||||
pagination: ctx.state.pagination,
|
||||
@ -52,15 +52,9 @@ router.post('apiKeys.delete', auth(), async ctx => {
|
||||
|
||||
const user = ctx.state.user;
|
||||
const key = await ApiKey.findById(id);
|
||||
authorize(user, 'delete', key);
|
||||
|
||||
if (!key || key.userId !== user.id) throw httpErrors.BadRequest();
|
||||
|
||||
// Delete the actual document
|
||||
try {
|
||||
await key.destroy();
|
||||
} catch (e) {
|
||||
throw httpErrors.BadRequest('Error while deleting key');
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
|
@ -9,7 +9,7 @@ const router = new Router();
|
||||
|
||||
router.post('auth.info', auth(), async ctx => {
|
||||
const user = ctx.state.user;
|
||||
const team = await Team.findOne({ where: { id: user.teamId } });
|
||||
const team = await Team.findById(user.teamId);
|
||||
|
||||
ctx.body = {
|
||||
data: {
|
||||
|
@ -1,13 +1,14 @@
|
||||
// @flow
|
||||
import Router from 'koa-router';
|
||||
import httpErrors from 'http-errors';
|
||||
import _ from 'lodash';
|
||||
|
||||
import auth from './middlewares/authentication';
|
||||
import pagination from './middlewares/pagination';
|
||||
import { presentCollection } from '../presenters';
|
||||
import { Collection } from '../models';
|
||||
import { ValidationError } from '../errors';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('collections.create', auth(), async ctx => {
|
||||
@ -17,6 +18,7 @@ router.post('collections.create', auth(), async ctx => {
|
||||
ctx.assertHexColor(color, 'Invalid hex value (please use format #FFFFFF)');
|
||||
|
||||
const user = ctx.state.user;
|
||||
authorize(user, 'create', Collection);
|
||||
|
||||
const collection = await Collection.create({
|
||||
name,
|
||||
@ -32,6 +34,18 @@ router.post('collections.create', auth(), async ctx => {
|
||||
};
|
||||
});
|
||||
|
||||
router.post('collections.info', auth(), async ctx => {
|
||||
const { id } = ctx.body;
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
|
||||
const collection = await Collection.scope('withRecentDocuments').findById(id);
|
||||
authorize(ctx.state.user, 'read', collection);
|
||||
|
||||
ctx.body = {
|
||||
data: await presentCollection(ctx, collection),
|
||||
};
|
||||
});
|
||||
|
||||
router.post('collections.update', auth(), async ctx => {
|
||||
const { id, name, color } = ctx.body;
|
||||
ctx.assertPresent(name, 'name is required');
|
||||
@ -39,6 +53,8 @@ router.post('collections.update', auth(), async ctx => {
|
||||
ctx.assertHexColor(color, 'Invalid hex value (please use format #FFFFFF)');
|
||||
|
||||
const collection = await Collection.findById(id);
|
||||
authorize(ctx.state.user, 'update', collection);
|
||||
|
||||
collection.name = name;
|
||||
collection.color = color;
|
||||
await collection.save();
|
||||
@ -48,25 +64,6 @@ router.post('collections.update', auth(), async ctx => {
|
||||
};
|
||||
});
|
||||
|
||||
router.post('collections.info', auth(), async ctx => {
|
||||
const { id } = ctx.body;
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
|
||||
const user = ctx.state.user;
|
||||
const collection = await Collection.scope('withRecentDocuments').findOne({
|
||||
where: {
|
||||
id,
|
||||
teamId: user.teamId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!collection) throw httpErrors.NotFound();
|
||||
|
||||
ctx.body = {
|
||||
data: await presentCollection(ctx, collection),
|
||||
};
|
||||
});
|
||||
|
||||
router.post('collections.list', auth(), pagination(), async ctx => {
|
||||
const user = ctx.state.user;
|
||||
const collections = await Collection.findAll({
|
||||
@ -94,20 +91,13 @@ router.post('collections.delete', auth(), async ctx => {
|
||||
const { id } = ctx.body;
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
|
||||
const user = ctx.state.user;
|
||||
const collection = await Collection.findById(id);
|
||||
authorize(ctx.state.user, 'delete', collection);
|
||||
|
||||
const total = await Collection.count();
|
||||
if (total === 1) throw new ValidationError('Cannot delete last collection');
|
||||
|
||||
if (total === 1) throw httpErrors.BadRequest('Cannot delete last collection');
|
||||
|
||||
if (!collection || collection.teamId !== user.teamId)
|
||||
throw httpErrors.BadRequest();
|
||||
|
||||
try {
|
||||
await collection.destroy();
|
||||
} catch (e) {
|
||||
throw httpErrors.BadRequest('Error while deleting collection');
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
|
@ -2,7 +2,8 @@
|
||||
import TestServer from 'fetch-test-server';
|
||||
import app from '..';
|
||||
import { flushdb, seed } from '../test/support';
|
||||
import Collection from '../models/Collection';
|
||||
import { buildUser } from '../test/factories';
|
||||
import { Collection } from '../models';
|
||||
const server = new TestServer(app.callback());
|
||||
|
||||
beforeEach(flushdb);
|
||||
@ -31,14 +32,6 @@ describe('#collections.list', async () => {
|
||||
});
|
||||
|
||||
describe('#collections.info', async () => {
|
||||
it('should require authentication', async () => {
|
||||
const res = await server.post('/api/collections.info');
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return collection', async () => {
|
||||
const { user, collection } = await seed();
|
||||
const res = await server.post('/api/collections.info', {
|
||||
@ -49,6 +42,23 @@ describe('#collections.info', async () => {
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.id).toEqual(collection.id);
|
||||
});
|
||||
|
||||
it('should require authentication', async () => {
|
||||
const res = await server.post('/api/collections.info');
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { collection } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/collections.info', {
|
||||
body: { token: user.getJwtToken(), id: collection.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#collections.create', async () => {
|
||||
@ -82,6 +92,15 @@ describe('#collections.delete', async () => {
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { collection } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/collections.delete', {
|
||||
body: { token: user.getJwtToken(), id: collection.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it('should not delete last collection', async () => {
|
||||
const { user, collection } = await seed();
|
||||
const res = await server.post('/api/collections.delete', {
|
||||
|
@ -6,12 +6,9 @@ import auth from './middlewares/authentication';
|
||||
import pagination from './middlewares/pagination';
|
||||
import { presentDocument, presentRevision } from '../presenters';
|
||||
import { Document, Collection, Star, View, Revision } from '../models';
|
||||
import policy from '../policies';
|
||||
|
||||
const authDocumentForUser = (ctx, document) => {
|
||||
const user = ctx.state.user;
|
||||
if (!document || document.teamId !== user.teamId) throw httpErrors.NotFound();
|
||||
};
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('documents.list', auth(), pagination(), async ctx => {
|
||||
@ -110,7 +107,7 @@ router.post('documents.info', auth(), async ctx => {
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
const document = await Document.findById(id);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'read', document);
|
||||
|
||||
ctx.body = {
|
||||
data: await presentDocument(ctx, document),
|
||||
@ -123,7 +120,7 @@ router.post('documents.revisions', auth(), pagination(), async ctx => {
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
const document = await Document.findById(id);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'read', document);
|
||||
|
||||
const revisions = await Revision.findAll({
|
||||
where: { documentId: id },
|
||||
@ -170,7 +167,7 @@ router.post('documents.star', auth(), async ctx => {
|
||||
const user = await ctx.state.user;
|
||||
const document = await Document.findById(id);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'read', document);
|
||||
|
||||
await Star.findOrCreate({
|
||||
where: { documentId: document.id, userId: user.id },
|
||||
@ -183,7 +180,7 @@ router.post('documents.unstar', auth(), async ctx => {
|
||||
const user = await ctx.state.user;
|
||||
const document = await Document.findById(id);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'read', document);
|
||||
|
||||
await Star.destroy({
|
||||
where: { documentId: document.id, userId: user.id },
|
||||
@ -201,12 +198,15 @@ router.post('documents.create', auth(), async ctx => {
|
||||
if (index) ctx.assertPositiveInteger(index, 'index must be an integer (>=0)');
|
||||
|
||||
const user = ctx.state.user;
|
||||
authorize(user, 'create', Document);
|
||||
|
||||
const ownerCollection = await Collection.findOne({
|
||||
where: {
|
||||
id: collection,
|
||||
teamId: user.teamId,
|
||||
},
|
||||
});
|
||||
authorize(user, 'publish', ownerCollection);
|
||||
|
||||
if (!ownerCollection) throw httpErrors.BadRequest();
|
||||
|
||||
@ -254,20 +254,20 @@ router.post('documents.update', auth(), async ctx => {
|
||||
|
||||
const user = ctx.state.user;
|
||||
const document = await Document.findById(id);
|
||||
const collection = document.collection;
|
||||
|
||||
authorize(ctx.state.user, 'update', document);
|
||||
|
||||
if (lastRevision && lastRevision !== document.revisionCount) {
|
||||
throw httpErrors.BadRequest('Document has changed since last revision');
|
||||
}
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
|
||||
// Update document
|
||||
if (title) document.title = title;
|
||||
if (text) document.text = text;
|
||||
document.lastModifiedById = user.id;
|
||||
|
||||
await document.save();
|
||||
const collection = document.collection;
|
||||
if (collection.type === 'atlas') {
|
||||
await collection.updateDocument(document);
|
||||
}
|
||||
@ -287,10 +287,9 @@ router.post('documents.move', auth(), async ctx => {
|
||||
if (index) ctx.assertPositiveInteger(index, 'index must be an integer (>=0)');
|
||||
|
||||
const document = await Document.findById(id);
|
||||
const collection = await Collection.findById(document.atlasId);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'update', document);
|
||||
|
||||
const collection = document.collection;
|
||||
if (collection.type !== 'atlas')
|
||||
throw httpErrors.BadRequest("This document can't be moved");
|
||||
|
||||
@ -324,10 +323,9 @@ router.post('documents.delete', auth(), async ctx => {
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
|
||||
const document = await Document.findById(id);
|
||||
const collection = await Collection.findById(document.atlasId);
|
||||
|
||||
authDocumentForUser(ctx, document);
|
||||
authorize(ctx.state.user, 'delete', document);
|
||||
|
||||
const collection = document.collection;
|
||||
if (collection.type === 'atlas') {
|
||||
// Don't allow deletion of root docs
|
||||
if (collection.documentStructure.length === 1) {
|
||||
|
@ -1,9 +1,9 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import TestServer from 'fetch-test-server';
|
||||
import app from '..';
|
||||
import { View, Star } from '../models';
|
||||
import { Document, View, Star } from '../models';
|
||||
import { flushdb, seed } from '../test/support';
|
||||
import Document from '../models/Document';
|
||||
import { buildUser } from '../test/factories';
|
||||
|
||||
const server = new TestServer(app.callback());
|
||||
|
||||
@ -55,7 +55,7 @@ describe('#documents.list', async () => {
|
||||
});
|
||||
|
||||
describe('#documents.revision', async () => {
|
||||
it("should return document's revisions", async () => {
|
||||
it("should return a document's revisions", async () => {
|
||||
const { user, document } = await seed();
|
||||
const res = await server.post('/api/documents.revisions', {
|
||||
body: {
|
||||
@ -70,6 +70,18 @@ describe('#documents.revision', async () => {
|
||||
expect(body.data[0].id).not.toEqual(document.id);
|
||||
expect(body.data[0].title).toEqual(document.title);
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/documents.revisions', {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: document.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#documents.search', async () => {
|
||||
@ -199,6 +211,15 @@ describe('#documents.star', async () => {
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/documents.star', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#documents.unstar', async () => {
|
||||
@ -222,6 +243,15 @@ describe('#documents.unstar', async () => {
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/documents.unstar', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#documents.create', async () => {
|
||||
@ -393,4 +423,24 @@ describe('#documents.update', async () => {
|
||||
'Updated title'
|
||||
);
|
||||
});
|
||||
|
||||
it('should require authentication', async () => {
|
||||
const { document } = await seed();
|
||||
const res = await server.post('/api/documents.update', {
|
||||
body: { id: document.id, text: 'Updated' },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/documents.update', {
|
||||
body: { token: user.getJwtToken(), id: document.id, text: 'Updated' },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
@ -1,7 +1,7 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import TestServer from 'fetch-test-server';
|
||||
import app from '..';
|
||||
import Authentication from '../models/Authentication';
|
||||
import { Authentication } from '../models';
|
||||
import { flushdb, seed } from '../test/support';
|
||||
import * as Slack from '../slack';
|
||||
|
||||
|
@ -38,6 +38,10 @@ api.use(async (ctx, next) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (message.match('Authorization error')) {
|
||||
ctx.status = 403;
|
||||
}
|
||||
|
||||
if (ctx.status === 500) {
|
||||
message = 'Internal Server Error';
|
||||
ctx.app.emit('error', err, ctx);
|
||||
|
@ -7,7 +7,6 @@ import { User, ApiKey } from '../../models';
|
||||
|
||||
type AuthOptions = {
|
||||
require?: boolean,
|
||||
adminOnly?: boolean,
|
||||
};
|
||||
|
||||
export default function auth(options: AuthOptions = {}) {
|
||||
@ -96,10 +95,6 @@ export default function auth(options: AuthOptions = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (options.adminOnly && !user.isAdmin) {
|
||||
throw httpErrors.Forbidden('Only available for admins');
|
||||
}
|
||||
|
||||
ctx.state.token = token;
|
||||
ctx.state.user = user;
|
||||
// $FlowFixMe
|
||||
|
@ -1,6 +1,6 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import { flushdb, seed } from '../../test/support';
|
||||
import ApiKey from '../../models/ApiKey';
|
||||
import { ApiKey } from '../../models';
|
||||
import randomstring from 'randomstring';
|
||||
import auth from './authentication';
|
||||
|
||||
@ -91,45 +91,6 @@ describe('Authentication middleware', async () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('adminOnly', () => {
|
||||
it('should work if user is an admin', async () => {
|
||||
const state = {};
|
||||
const { user } = await seed();
|
||||
const authMiddleware = auth({ adminOnly: true });
|
||||
user.isAdmin = true;
|
||||
await user.save();
|
||||
|
||||
await authMiddleware(
|
||||
{
|
||||
request: {
|
||||
get: jest.fn(() => `Bearer ${user.getJwtToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
},
|
||||
jest.fn()
|
||||
);
|
||||
expect(state.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it('should raise 403 if user is not an admin', async () => {
|
||||
const { user } = await seed();
|
||||
const authMiddleware = auth({ adminOnly: true });
|
||||
user.idAdmin = true;
|
||||
await user.save();
|
||||
|
||||
try {
|
||||
await authMiddleware({
|
||||
request: {
|
||||
get: jest.fn(() => `Bearer ${user.getJwtToken()}`),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
expect(e.message).toBe('Only available for admins');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should return error message if no auth token is available', async () => {
|
||||
const state = {};
|
||||
const authMiddleware = auth();
|
||||
|
@ -1,43 +1,43 @@
|
||||
// @flow
|
||||
import apiError from '../../errors';
|
||||
import validator from 'validator';
|
||||
import { ParamRequiredError, ValidationError } from '../../errors';
|
||||
import { validateColorHex } from '../../../shared/utils/color';
|
||||
|
||||
export default function validation() {
|
||||
return function validationMiddleware(ctx: Object, next: Function) {
|
||||
ctx.assertPresent = function assertPresent(value, message) {
|
||||
ctx.assertPresent = (value, message) => {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ParamRequiredError(message);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.assertNotEmpty = function assertNotEmpty(value, message) {
|
||||
ctx.assertNotEmpty = (value, message) => {
|
||||
if (value === '') {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ValidationError(message);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.assertEmail = (value, message) => {
|
||||
if (!validator.isEmail(value)) {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ValidationError(message);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.assertUuid = (value, message) => {
|
||||
if (!validator.isUUID(value)) {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ValidationError(message);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.assertPositiveInteger = (value, message) => {
|
||||
if (!validator.isInt(value, { min: 0 })) {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ValidationError(message);
|
||||
}
|
||||
};
|
||||
|
||||
ctx.assertHexColor = (value, message) => {
|
||||
if (!validateColorHex(value)) {
|
||||
throw apiError(400, 'validation_error', message);
|
||||
throw new ValidationError(message);
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -1,14 +1,14 @@
|
||||
// @flow
|
||||
import Router from 'koa-router';
|
||||
import httpErrors from 'http-errors';
|
||||
|
||||
import User from '../models/User';
|
||||
import Team from '../models/Team';
|
||||
import { ValidationError } from '../errors';
|
||||
import { Team, User } from '../models';
|
||||
|
||||
import auth from './middlewares/authentication';
|
||||
import pagination from './middlewares/pagination';
|
||||
import { presentUser } from '../presenters';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('team.users', auth(), pagination(), async ctx => {
|
||||
@ -31,41 +31,41 @@ router.post('team.users', auth(), pagination(), async ctx => {
|
||||
};
|
||||
});
|
||||
|
||||
router.post('team.addAdmin', auth({ adminOnly: true }), async ctx => {
|
||||
const { user } = ctx.body;
|
||||
const admin = ctx.state.user;
|
||||
ctx.assertPresent(user, 'id is required');
|
||||
router.post('team.addAdmin', auth(), async ctx => {
|
||||
const userId = ctx.body.user;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const team = await Team.findById(admin.teamId);
|
||||
const promotedUser = await User.findOne({
|
||||
where: { id: user, teamId: admin.teamId },
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'promote', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
await team.addAdmin(user);
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
if (!promotedUser) throw httpErrors.NotFound();
|
||||
router.post('team.removeAdmin', auth(), async ctx => {
|
||||
const userId = ctx.body.user;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
await team.addAdmin(promotedUser);
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'demote', user);
|
||||
|
||||
ctx.body = presentUser(ctx, promotedUser, { includeDetails: true });
|
||||
});
|
||||
|
||||
router.post('team.removeAdmin', auth({ adminOnly: true }), async ctx => {
|
||||
const { user } = ctx.body;
|
||||
const admin = ctx.state.user;
|
||||
ctx.assertPresent(user, 'id is required');
|
||||
|
||||
const team = await Team.findById(admin.teamId);
|
||||
const demotedUser = await User.findOne({
|
||||
where: { id: user, teamId: admin.teamId },
|
||||
});
|
||||
|
||||
if (!demotedUser) throw httpErrors.NotFound();
|
||||
const team = await Team.findById(teamId);
|
||||
|
||||
try {
|
||||
await team.removeAdmin(demotedUser);
|
||||
ctx.body = presentUser(ctx, user, { includeDetails: true });
|
||||
} catch (e) {
|
||||
throw httpErrors.BadRequest(e.message);
|
||||
await team.removeAdmin(user);
|
||||
} catch (err) {
|
||||
throw new ValidationError(err.message);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
@ -40,10 +40,7 @@ describe('#team.addAdmin', async () => {
|
||||
const { admin, user } = await seed();
|
||||
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
user: user.id,
|
||||
},
|
||||
body: { token: admin.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
@ -54,7 +51,7 @@ describe('#team.addAdmin', async () => {
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: { token: user.getJwtToken() },
|
||||
body: { token: user.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
@ -98,7 +95,7 @@ describe('#team.removeAdmin', async () => {
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: { token: user.getJwtToken() },
|
||||
body: { token: user.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
|
@ -2,7 +2,7 @@
|
||||
import uuid from 'uuid';
|
||||
import Router from 'koa-router';
|
||||
import { makePolicy, signPolicy, publicS3Endpoint } from '../utils/s3';
|
||||
import Event from '../models/Event';
|
||||
import { Event } from '../models';
|
||||
import auth from './middlewares/authentication';
|
||||
import { presentUser } from '../presenters';
|
||||
|
||||
|
@ -1,24 +1,26 @@
|
||||
// @flow
|
||||
import Router from 'koa-router';
|
||||
import httpErrors from 'http-errors';
|
||||
import auth from './middlewares/authentication';
|
||||
import { presentView } from '../presenters';
|
||||
import { View, Document } from '../models';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('views.list', auth(), async ctx => {
|
||||
const { id } = ctx.body;
|
||||
ctx.assertPresent(id, 'id is required');
|
||||
|
||||
const user = ctx.state.user;
|
||||
const document = await Document.findById(id);
|
||||
authorize(user, 'read', document);
|
||||
|
||||
const views = await View.findAll({
|
||||
where: {
|
||||
documentId: id,
|
||||
},
|
||||
where: { documentId: id },
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
|
||||
// Collectiones
|
||||
let users = [];
|
||||
let count = 0;
|
||||
await Promise.all(
|
||||
@ -42,11 +44,13 @@ router.post('views.create', auth(), async ctx => {
|
||||
|
||||
const user = ctx.state.user;
|
||||
const document = await Document.findById(id);
|
||||
|
||||
if (!document || document.teamId !== user.teamId)
|
||||
throw httpErrors.BadRequest();
|
||||
authorize(user, 'read', document);
|
||||
|
||||
await View.increment({ documentId: document.id, userId: user.id });
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
};
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
73
server/api/views.test.js
Normal file
73
server/api/views.test.js
Normal file
@ -0,0 +1,73 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import TestServer from 'fetch-test-server';
|
||||
import app from '..';
|
||||
import { flushdb, seed } from '../test/support';
|
||||
import { buildUser } from '../test/factories';
|
||||
|
||||
const server = new TestServer(app.callback());
|
||||
|
||||
beforeEach(flushdb);
|
||||
afterAll(server.close);
|
||||
|
||||
describe('#views.list', async () => {
|
||||
it('should return views for a document', async () => {
|
||||
const { user, document } = await seed();
|
||||
const res = await server.post('/api/views.list', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
it('should require authentication', async () => {
|
||||
const { document } = await seed();
|
||||
const res = await server.post('/api/views.list', {
|
||||
body: { id: document.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/views.list', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#views.create', async () => {
|
||||
it('should allow creating a view record for document', async () => {
|
||||
const { user, document } = await seed();
|
||||
const res = await server.post('/api/views.create', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should require authentication', async () => {
|
||||
const { document } = await seed();
|
||||
const res = await server.post('/api/views.create', {
|
||||
body: { id: document.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(401);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require authorization', async () => {
|
||||
const { document } = await seed();
|
||||
const user = await buildUser();
|
||||
const res = await server.post('/api/views.create', {
|
||||
body: { token: user.getJwtToken(), id: document.id },
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
@ -1,9 +1,28 @@
|
||||
// @flow
|
||||
import httpErrors from 'http-errors';
|
||||
|
||||
const apiError = (code: number, id: string, message: string) => {
|
||||
return httpErrors(code, message, { id });
|
||||
};
|
||||
export function ValidationError(message: string = 'Validation failed') {
|
||||
return httpErrors(400, message, { id: 'validation_error' });
|
||||
}
|
||||
|
||||
export default apiError;
|
||||
export { httpErrors };
|
||||
export function ParamRequiredError(
|
||||
message: string = 'Required parameter missing'
|
||||
) {
|
||||
return httpErrors(400, message, { id: 'param_required' });
|
||||
}
|
||||
|
||||
export function AuthorizationError(
|
||||
message: string = 'You do not have permission to access this resource'
|
||||
) {
|
||||
return httpErrors(403, message, { id: 'permission_required' });
|
||||
}
|
||||
|
||||
export function AdminRequiredError(
|
||||
message: string = 'An admin role is required to access this resource'
|
||||
) {
|
||||
return httpErrors(403, message, { id: 'admin_required' });
|
||||
}
|
||||
|
||||
export function NotFoundError(message: string = 'Resource not found') {
|
||||
return httpErrors(404, message, { id: 'not_found' });
|
||||
}
|
||||
|
@ -2,8 +2,7 @@
|
||||
import Queue from 'bull';
|
||||
import debug from 'debug';
|
||||
import services from '../services';
|
||||
import Document from './models/Document';
|
||||
import Collection from './models/Collection';
|
||||
import { Collection, Document } from './models';
|
||||
|
||||
type DocumentEvent = {
|
||||
name: 'documents.create',
|
||||
|
@ -1,7 +1,6 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import { flushdb, seed } from '../test/support';
|
||||
import Collection from '../models/Collection';
|
||||
import Document from '../models/Document';
|
||||
import { Collection, Document } from '../models';
|
||||
|
||||
beforeEach(flushdb);
|
||||
beforeEach(jest.resetAllMocks);
|
||||
|
@ -42,13 +42,13 @@ Team.prototype.createFirstCollection = async function(userId) {
|
||||
};
|
||||
|
||||
Team.prototype.addAdmin = async function(user: User) {
|
||||
return await user.update({ isAdmin: true });
|
||||
return user.update({ isAdmin: true });
|
||||
};
|
||||
|
||||
Team.prototype.removeAdmin = async function(user: User) {
|
||||
const res = await User.findAndCountAll({
|
||||
where: {
|
||||
teamId: user.teamId,
|
||||
teamId: this.id,
|
||||
isAdmin: true,
|
||||
id: {
|
||||
[Op.ne]: user.id,
|
||||
@ -57,7 +57,7 @@ Team.prototype.removeAdmin = async function(user: User) {
|
||||
limit: 1,
|
||||
});
|
||||
if (res.count >= 1) {
|
||||
return await user.update({ isAdmin: false });
|
||||
return user.update({ isAdmin: false });
|
||||
} else {
|
||||
throw new Error('At least one admin is required');
|
||||
}
|
||||
|
14
server/policies/apiKey.js
Normal file
14
server/policies/apiKey.js
Normal file
@ -0,0 +1,14 @@
|
||||
// @flow
|
||||
import policy from './policy';
|
||||
import { ApiKey, User } from '../models';
|
||||
|
||||
const { allow } = policy;
|
||||
|
||||
allow(User, 'create', ApiKey);
|
||||
|
||||
allow(
|
||||
User,
|
||||
['read', 'update', 'delete'],
|
||||
ApiKey,
|
||||
(user, apiKey) => user && user.id === apiKey.userId
|
||||
);
|
21
server/policies/collection.js
Normal file
21
server/policies/collection.js
Normal file
@ -0,0 +1,21 @@
|
||||
// @flow
|
||||
import policy from './policy';
|
||||
import { Collection, User } from '../models';
|
||||
import { AdminRequiredError } from '../errors';
|
||||
|
||||
const { allow } = policy;
|
||||
|
||||
allow(User, 'create', Collection);
|
||||
|
||||
allow(
|
||||
User,
|
||||
['read', 'publish', 'update'],
|
||||
Collection,
|
||||
(user, collection) => collection && user.teamId === collection.teamId
|
||||
);
|
||||
|
||||
allow(User, 'delete', Collection, (user, collection) => {
|
||||
if (!collection || user.teamId !== collection.teamId) return false;
|
||||
if (user.id === collection.creatorId) return true;
|
||||
if (!user.isAdmin) throw new AdminRequiredError();
|
||||
});
|
14
server/policies/document.js
Normal file
14
server/policies/document.js
Normal file
@ -0,0 +1,14 @@
|
||||
// @flow
|
||||
import policy from './policy';
|
||||
import { Document, User } from '../models';
|
||||
|
||||
const { allow } = policy;
|
||||
|
||||
allow(User, 'create', Document);
|
||||
|
||||
allow(
|
||||
User,
|
||||
['read', 'update', 'delete'],
|
||||
Document,
|
||||
(user, document) => user.teamId === document.teamId
|
||||
);
|
8
server/policies/index.js
Normal file
8
server/policies/index.js
Normal file
@ -0,0 +1,8 @@
|
||||
// @flow
|
||||
import policy from './policy';
|
||||
import './apiKey';
|
||||
import './collection';
|
||||
import './document';
|
||||
import './user';
|
||||
|
||||
export default policy;
|
3
server/policies/policy.js
Normal file
3
server/policies/policy.js
Normal file
@ -0,0 +1,3 @@
|
||||
// @flow
|
||||
import CanCan from 'cancan';
|
||||
export default new CanCan();
|
26
server/policies/user.js
Normal file
26
server/policies/user.js
Normal file
@ -0,0 +1,26 @@
|
||||
// @flow
|
||||
import policy from './policy';
|
||||
import { User } from '../models';
|
||||
import { AdminRequiredError } from '../errors';
|
||||
|
||||
const { allow } = policy;
|
||||
|
||||
allow(
|
||||
User,
|
||||
'read',
|
||||
User,
|
||||
(actor, user) => user && user.teamId === actor.teamId
|
||||
);
|
||||
|
||||
allow(User, ['update', 'delete'], User, (actor, user) => {
|
||||
if (!user || user.teamId !== actor.teamId) return false;
|
||||
if (user.id === actor.id) return true;
|
||||
if (actor.isAdmin) return true;
|
||||
throw new AdminRequiredError();
|
||||
});
|
||||
|
||||
allow(User, ['promote', 'demote'], User, (actor, user) => {
|
||||
if (!user || user.teamId !== actor.teamId) return false;
|
||||
if (actor.isAdmin) return true;
|
||||
throw new AdminRequiredError();
|
||||
});
|
@ -1,5 +1,5 @@
|
||||
// @flow
|
||||
import User from '../models/User';
|
||||
import { User } from '../models';
|
||||
|
||||
type Options = {
|
||||
includeDetails?: boolean,
|
||||
|
@ -1,7 +1,7 @@
|
||||
// @flow
|
||||
import fetch from 'isomorphic-fetch';
|
||||
import querystring from 'querystring';
|
||||
import { httpErrors } from './errors';
|
||||
import httpErrors from 'http-errors';
|
||||
|
||||
const SLACK_API_URL = 'https://slack.com/api';
|
||||
|
||||
|
33
server/test/factories.js
Normal file
33
server/test/factories.js
Normal file
@ -0,0 +1,33 @@
|
||||
// @flow
|
||||
import { Team, User } from '../models';
|
||||
import uuid from 'uuid';
|
||||
|
||||
let count = 0;
|
||||
|
||||
export function buildTeam(overrides: Object = {}) {
|
||||
count++;
|
||||
|
||||
return Team.create({
|
||||
name: `Team ${count}`,
|
||||
slackId: uuid.v4(),
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function buildUser(overrides: Object = {}) {
|
||||
count++;
|
||||
|
||||
if (!overrides.teamId) {
|
||||
const team = await buildTeam();
|
||||
overrides.teamId = team.id;
|
||||
}
|
||||
|
||||
return User.create({
|
||||
email: `user${count}@example.com`,
|
||||
username: `user${count}`,
|
||||
name: `User ${count}`,
|
||||
password: 'test123!',
|
||||
slackId: uuid.v4(),
|
||||
...overrides,
|
||||
});
|
||||
}
|
@ -3,7 +3,7 @@ import type { Event } from '../../server/events';
|
||||
|
||||
const Slack = {
|
||||
on: (event: Event) => {
|
||||
console.log(`Slack service received ${event.name}, id: ${event.model.id}`);
|
||||
// console.log(`Slack service received ${event.name}, id: ${event.model.id}`);
|
||||
},
|
||||
};
|
||||
|
||||
|
12
yarn.lock
12
yarn.lock
@ -423,6 +423,10 @@ attr-accept@^1.0.3:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/attr-accept/-/attr-accept-1.1.0.tgz#b5cd35227f163935a8f1de10ed3eba16941f6be6"
|
||||
|
||||
auto-bind@^1.1.0:
|
||||
version "1.2.0"
|
||||
resolved "https://registry.yarnpkg.com/auto-bind/-/auto-bind-1.2.0.tgz#8b7e318aad53d43ba8a8ecaf0066d85d5f798cd6"
|
||||
|
||||
autoprefixer@^6.3.1:
|
||||
version "6.7.7"
|
||||
resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-6.7.7.tgz#1dbd1c835658e35ce3f9984099db00585c782014"
|
||||
@ -1531,6 +1535,14 @@ camelize@1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/camelize/-/camelize-1.0.0.tgz#164a5483e630fa4321e5af07020e531831b2609b"
|
||||
|
||||
cancan@3.1.0:
|
||||
version "3.1.0"
|
||||
resolved "https://registry.yarnpkg.com/cancan/-/cancan-3.1.0.tgz#4d148e73795324f689a9b1002e61839c17ea821e"
|
||||
dependencies:
|
||||
arrify "^1.0.1"
|
||||
auto-bind "^1.1.0"
|
||||
is-plain-obj "^1.1.0"
|
||||
|
||||
caniuse-api@^1.5.2:
|
||||
version "1.6.1"
|
||||
resolved "https://registry.yarnpkg.com/caniuse-api/-/caniuse-api-1.6.1.tgz#b534e7c734c4f81ec5fbe8aca2ad24354b962c6c"
|
||||
|
Reference in New Issue
Block a user