Passing test suite

This commit is contained in:
Tom Moor committed 2019-09-05 23:30:06 -07:00
1 parent 1baf27c6e7
commit 980bc7e426
17 files changed
+442 -138

No files matched your search

+1
View File
@@ -91,6 +91,7 @@ class Editor extends React.Component<Props> {
onShowToast={this.onShowToast}
getLinkComponent={this.getLinkComponent}
tooltip={EditorTooltip}
headingsOffset={1}
{...this.props}
/>
</React.Fragment>
+72
View File
@@ -0,0 +1,72 @@
// @flow
import * as React from 'react';
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import styled from 'styled-components';
import VisuallyHidden from 'components/VisuallyHidden';
import { Outline, LabelText } from './Input';
const Select = styled.select`
border: 0;
flex: 1;
padding: 8px 12px;
outline: none;
background: none;
color: ${props => props.theme.text};
&:disabled,
&::placeholder {
color: ${props => props.theme.placeholder};
}
`;
type Option = { label: string, value: string };
export type Props = {
value?: string,
label?: string,
className?: string,
labelHidden?: boolean,
options: Option[],
};
@observer
class InputSelect extends React.Component<Props> {
@observable focused: boolean = false;
handleBlur = () => {
this.focused = false;
};
handleFocus = () => {
this.focused = true;
};
render() {
const { label, className, labelHidden, options, ...rest } = this.props;
const wrappedLabel = <LabelText>{label}</LabelText>;
return (
<label>
{label &&
(labelHidden ? (
<VisuallyHidden>{wrappedLabel}</VisuallyHidden>
) : (
wrappedLabel
))}
<Outline focused={this.focused} className={className}>
<Select onBlur={this.handleBlur} onFocus={this.handleFocus} {...rest}>
{options.map(option => (
<option value={option.value} key={option.value}>
{option.label}
</option>
))}
</Select>
</Outline>
</label>
);
}
}
export default InputSelect;
@@ -50,6 +50,19 @@ class CollectionMembers extends React.Component<Props> {
}
};
handleUpdateUser = (user, permission) => {
try {
this.props.memberships.create({
collectionId: this.props.collection.id,
userId: user.id,
permission,
});
this.props.ui.showToast(`${user.name} permissions were updated`);
} catch (err) {
this.props.ui.showToast('Could not update user');
}
};
render() {
const { collection, users, memberships, auth } = this.props;
const { user } = auth;
@@ -103,8 +116,10 @@ class CollectionMembers extends React.Component<Props> {
<MemberListItem
key={item.id}
user={item}
membership={memberships.get(`${item.id}-${collection.id}`)}
canEdit={collection.private && item.id !== user.id}
onRemove={() => this.handleRemoveUser(item)}
onUpdate={permission => this.handleUpdateUser(item, permission)}
/>
)}
/>
@@ -1,22 +1,38 @@
// @flow
import * as React from 'react';
import styled from 'styled-components';
import Avatar from 'components/Avatar';
import Flex from 'shared/components/Flex';
import Time from 'shared/components/Time';
import Badge from 'components/Badge';
import Button from 'components/Button';
import InputSelect from 'components/InputSelect';
import ListItem from 'components/List/Item';
import User from 'models/User';
import Membership from 'models/Membership';
import { DropdownMenu, DropdownMenuItem } from 'components/DropdownMenu';
const PERMISSIONS = [
{ label: 'Read only', value: 'read' },
{ label: 'Read & Edit', value: 'read_write' },
];
type Props = {
user: User,
membership: Membership,
canEdit: boolean,
onAdd?: () => void,
onRemove?: () => void,
onUpdate?: (permission: string) => void,
};
const MemberListItem = ({ user, onRemove, onAdd, canEdit }: Props) => {
const MemberListItem = ({
user,
membership,
onRemove,
onUpdate,
onAdd,
canEdit,
}: Props) => {
return (
<ListItem
title={user.name}
@@ -29,6 +45,17 @@ const MemberListItem = ({ user, onRemove, onAdd, canEdit }: Props) => {
image={<Avatar src={user.avatarUrl} size={32} />}
actions={
<Flex align="center">
{canEdit &&
onUpdate && (
<Select
label="Permissions"
options={PERMISSIONS}
value={membership.permission}
onChange={ev => onUpdate(ev.target.value)}
labelHidden
/>
)}
&nbsp;&nbsp;
{canEdit &&
onRemove && (
<DropdownMenu>
@@ -47,4 +74,9 @@ const MemberListItem = ({ user, onRemove, onAdd, canEdit }: Props) => {
);
};
const Select = styled(InputSelect)`
margin: 0;
font-size: 14px;
`;
export default MemberListItem;
+3
View File
@@ -38,13 +38,16 @@ export default class MembershipsStore extends BaseStore<Membership> {
async create({
collectionId,
userId,
permission,
}: {
collectionId: string,
userId: string,
permission: string,
}) {
const res = await client.post('/collections.add_user', {
id: collectionId,
userId,
permission,
});
invariant(res && res.data, 'Membership data should be available');
+25 -7
View File
@@ -60,7 +60,9 @@ router.post('collections.info', auth(), async ctx => {
ctx.assertUuid(id, 'id is required');
const user = ctx.state.user;
const collection = await Collection.findByPk(id);
const collection = await Collection.scope({
method: ['withMembership', user.id],
}).findByPk(id);
authorize(user, 'read', collection);
ctx.body = {
@@ -74,7 +76,9 @@ router.post('collections.add_user', auth(), async ctx => {
ctx.assertUuid(id, 'id is required');
ctx.assertUuid(userId, 'userId is required');
const collection = await Collection.findByPk(id);
const collection = await Collection.scope({
method: ['withMembership', ctx.state.user.id],
}).findByPk(id);
authorize(ctx.state.user, 'update', collection);
const user = await User.findByPk(userId);
@@ -94,6 +98,9 @@ router.post('collections.add_user', auth(), async ctx => {
permission,
createdById: ctx.state.user.id,
});
} else if (permission) {
membership.permission = permission;
await membership.save();
}
await Event.create({
@@ -114,14 +121,14 @@ router.post('collections.add_user', auth(), async ctx => {
};
});
// TODO: update_user
router.post('collections.remove_user', auth(), async ctx => {
const { id, userId } = ctx.body;
ctx.assertUuid(id, 'id is required');
ctx.assertUuid(userId, 'userId is required');
const collection = await Collection.findByPk(id);
const collection = await Collection.scope({
method: ['withMembership', ctx.state.user.id],
}).findByPk(id);
authorize(ctx.state.user, 'update', collection);
const user = await User.findByPk(userId);
@@ -309,8 +316,19 @@ router.post('collections.update', auth(), async ctx => {
ip: ctx.request.ip,
});
// must reload to update collection.users
await collection.reload();
// must reload to update collection membership for correct policy calculation
await collection.reload({
include: [
{
model: 'collection_user',
as: 'membership',
where: {
userId: user.id,
},
required: false,
},
],
});
ctx.body = {
data: presentCollection(collection),
+56 -34
View File
@@ -29,6 +29,22 @@ const Op = Sequelize.Op;
const { authorize, cannot } = policy;
const router = new Router();
const findDocumentAndCollection = async (documentId, userId) => {
const document = await Document.findByPk(documentId);
const collection = await Collection.scope(
userId
? {
method: ['withMembership', userId],
}
: 'defaultScope'
).findByPk(document.collectionId);
return {
document,
collection,
};
};
router.post('documents.list', auth(), pagination(), async ctx => {
const { sort = 'updatedAt' } = ctx.body;
const collectionId = ctx.body.collection;
@@ -324,8 +340,12 @@ router.post('documents.info', auth({ required: false }), async ctx => {
}
document = share.document;
} else {
document = await Document.findByPk(id);
authorize(user, 'read', document);
const response = await findDocumentAndCollection(
id,
user ? user.id : undefined
);
document = response.document;
authorize(user, 'read', document, { collection: response.collection });
}
const isPublic = cannot(user, 'read', document);
@@ -341,8 +361,9 @@ router.post('documents.revision', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
ctx.assertPresent(revisionId, 'revisionId is required');
const document = await Document.findByPk(id);
authorize(ctx.state.user, 'read', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'read', document, { collection });
const revision = await Revision.findOne({
where: {
@@ -361,9 +382,10 @@ router.post('documents.revisions', auth(), pagination(), async ctx => {
let { id, sort = 'updatedAt', direction } = ctx.body;
if (direction !== 'ASC') direction = 'DESC';
ctx.assertPresent(id, 'id is required');
const document = await Document.findByPk(id);
authorize(ctx.state.user, 'read', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'read', document, { collection });
const revisions = await Revision.findAll({
where: { documentId: id },
@@ -383,10 +405,10 @@ router.post('documents.restore', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
const { document, collection } = await findDocumentAndCollection(id, user.id);
if (document.archivedAt) {
authorize(user, 'unarchive', document);
authorize(user, 'unarchive', document, { collection });
// restore a previously archived document
await document.unarchive(user.id);
@@ -402,7 +424,7 @@ router.post('documents.restore', auth(), async ctx => {
});
} else if (revisionId) {
// restore a document to a specific revision
authorize(user, 'update', document);
authorize(user, 'update', document, { collection });
const revision = await Revision.findByPk(revisionId);
authorize(document, 'restore', revision);
@@ -486,10 +508,10 @@ router.post('documents.search', auth(), pagination(), async ctx => {
router.post('documents.pin', auth(), async ctx => {
const { id } = ctx.body;
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'update', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'update', document, { collection });
document.pinnedById = user.id;
await document.save();
@@ -513,10 +535,10 @@ router.post('documents.pin', auth(), async ctx => {
router.post('documents.unpin', auth(), async ctx => {
const { id } = ctx.body;
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'update', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'update', document, { collection });
document.pinnedById = null;
await document.save();
@@ -540,10 +562,10 @@ router.post('documents.unpin', auth(), async ctx => {
router.post('documents.star', auth(), async ctx => {
const { id } = ctx.body;
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'read', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'read', document, { collection });
await Star.findOrCreate({
where: { documentId: document.id, userId: user.id },
@@ -563,10 +585,10 @@ router.post('documents.star', auth(), async ctx => {
router.post('documents.unstar', auth(), async ctx => {
const { id } = ctx.body;
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'read', document);
const user = ctx.state.user;
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'read', document, { collection });
await Star.destroy({
where: { documentId: document.id, userId: user.id },
@@ -603,7 +625,9 @@ router.post('documents.create', auth(), async ctx => {
const user = ctx.state.user;
authorize(user, 'create', Document);
const collection = await Collection.findOne({
const collection = await Collection.scope({
method: ['withMembership', user.id],
}).findOne({
where: {
id: collectionId,
teamId: user.teamId,
@@ -619,7 +643,7 @@ router.post('documents.create', auth(), async ctx => {
collectionId: collection.id,
},
});
authorize(user, 'read', parentDocument);
authorize(user, 'read', parentDocument, { collection });
}
let document = await Document.create({
@@ -686,9 +710,8 @@ router.post('documents.update', auth(), async ctx => {
if (append) ctx.assertPresent(text, 'Text is required while appending');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(ctx.state.user, 'update', document);
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'update', document, { collection });
if (lastRevision && lastRevision !== document.revisionCount) {
throw new InvalidRequestError('Document has changed since last revision');
@@ -771,11 +794,10 @@ router.post('documents.move', auth(), async ctx => {
}
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'move', document);
const { document, collection } = await findDocumentAndCollection(id, user.id);
const collection = await Collection.findByPk(collectionId);
authorize(user, 'update', collection);
authorize(user, 'move', document, { collection });
if (collection.type !== 'atlas' && parentDocumentId) {
throw new InvalidRequestError(
@@ -785,7 +807,7 @@ router.post('documents.move', auth(), async ctx => {
if (parentDocumentId) {
const parent = await Document.findByPk(parentDocumentId);
authorize(user, 'update', parent);
authorize(user, 'update', parent, { collection });
}
const { documents, collections } = await documentMover({
@@ -815,8 +837,8 @@ router.post('documents.archive', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'archive', document);
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'archive', document, { collection });
await document.archive(user.id);
@@ -841,8 +863,8 @@ router.post('documents.delete', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
authorize(user, 'delete', document);
const { document, collection } = await findDocumentAndCollection(id, user.id);
authorize(user, 'delete', document, { collection });
await document.delete();
+73 -13
View File
@@ -1,7 +1,14 @@
/* eslint-disable flowtype/require-valid-file-annotation */
import TestServer from 'fetch-test-server';
import app from '../app';
import { Document, View, Star, Revision, Backlink } from '../models';
import {
Document,
View,
Star,
Revision,
Backlink,
CollectionUser,
} from '../models';
import { flushdb, seed } from '../test/support';
import {
buildShare,
@@ -817,6 +824,7 @@ describe('#documents.pin', async () => {
body: { token: user.getJwtToken(), id: document.id },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.pinned).toEqual(true);
});
@@ -935,6 +943,7 @@ describe('#documents.unpin', async () => {
body: { token: user.getJwtToken(), id: document.id },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.pinned).toEqual(false);
});
@@ -1036,7 +1045,7 @@ describe('#documents.create', async () => {
const newDocument = await Document.findByPk(body.data.id);
expect(res.status).toEqual(200);
expect(newDocument.parentDocumentId).toBe(null);
expect(newDocument.collection.id).toBe(collection.id);
expect(newDocument.collectionId).toBe(collection.id);
});
it('should fallback to a default title', async () => {
@@ -1252,23 +1261,54 @@ describe('#documents.update', async () => {
expect(body.data.title).toBe('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' },
it('allows editing by read-write collection user', async () => {
const { user, document, collection } = await seed();
collection.private = true;
await collection.save();
await CollectionUser.create({
collectionId: collection.id,
userId: user.id,
createdById: user.id,
permission: 'read_write',
});
const res = await server.post('/api/documents.update', {
body: {
token: user.getJwtToken(),
id: document.id,
text: 'Changed text',
lastRevision: document.revision,
},
});
const body = await res.json();
expect(res.status).toEqual(401);
expect(body).toMatchSnapshot();
expect(res.status).toEqual(200);
expect(body.data.text).toBe('Changed text');
});
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' },
it('does not allow editing by read-only collection user', async () => {
const { user, document, collection } = await seed();
collection.private = true;
await collection.save();
await CollectionUser.create({
collectionId: collection.id,
userId: user.id,
createdById: user.id,
permission: 'read',
});
const res = await server.post('/api/documents.update', {
body: {
token: user.getJwtToken(),
id: document.id,
text: 'Changed text',
lastRevision: document.revision,
},
});
expect(res.status).toEqual(403);
});
@@ -1307,6 +1347,26 @@ describe('#documents.update', async () => {
expect(res.status).toEqual(400);
expect(body).toMatchSnapshot();
});
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);
});
});
describe('#documents.archive', async () => {
+4 -2
View File
@@ -2,7 +2,7 @@
import Router from 'koa-router';
import { escapeRegExp } from 'lodash';
import { AuthenticationError, InvalidRequestError } from '../errors';
import { Authentication, Document, User, Team } from '../models';
import { Authentication, Document, User, Team, Collection } from '../models';
import { presentSlackAttachment } from '../presenters';
import * as Slack from '../slack';
const router = new Router();
@@ -80,13 +80,14 @@ router.post('hooks.interactive', async ctx => {
if (!document) throw new InvalidRequestError('Invalid document');
const team = await Team.findByPk(user.teamId);
const collection = await Collection.findByPk(document.collectionId);
// respond with a public message that will be posted in the original channel
ctx.body = {
response_type: 'in_channel',
replace_original: false,
attachments: [
presentSlackAttachment(document, team, document.getSummary()),
presentSlackAttachment(document, collection, team, document.getSummary()),
],
};
});
@@ -145,6 +146,7 @@ router.post('hooks.slack', async ctx => {
attachments.push(
presentSlackAttachment(
result.document,
result.document.collection,
team,
queryIsInTitle ? undefined : result.context,
process.env.SLACK_MESSAGE_ACTIONS
@@ -1,10 +1,25 @@
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn('collections', 'maintainerApprovalRequired', {
type: Sequelize.BOOLEAN,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn('collections', 'maintainerApprovalRequired');
},
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn('collections', 'maintainerApprovalRequired', {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false,
});
await queryInterface.changeColumn('collection_users', 'permission', {
type: Sequelize.STRING,
allowNull: false,
defaultValue: 'read_write',
});
await queryInterface.addIndex('collection_users', ['permission']);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn('collections', 'maintainerApprovalRequired');
await queryInterface.changeColumn('collection_users', 'permission', {
type: Sequelize.STRING,
allowNull: false,
defaultValue: null,
});
await queryInterface.removeIndex('collection_users', ['permission']);
},
};
+15 -14
View File
@@ -54,6 +54,11 @@ Collection.associate = models => {
foreignKey: 'collectionId',
onDelete: 'cascade',
});
Collection.hasMany(models.CollectionUser, {
as: 'memberships',
foreignKey: 'collectionId',
onDelete: 'cascade',
});
Collection.belongsToMany(models.User, {
as: 'users',
through: models.CollectionUser,
@@ -66,20 +71,16 @@ Collection.associate = models => {
Collection.belongsTo(models.Team, {
as: 'team',
});
Collection.addScope(
'defaultScope',
{
include: [
{
model: models.User,
as: 'users',
through: 'collection_users',
paranoid: false,
},
],
},
{ override: true }
);
Collection.addScope('withMembership', userId => ({
include: [
{
model: models.CollectionUser,
as: 'memberships',
where: { userId },
required: false,
},
],
}));
};
Collection.addHook('afterDestroy', async (model: Collection) => {
+1
View File
@@ -6,6 +6,7 @@ const CollectionUser = sequelize.define(
{
permission: {
type: DataTypes.STRING,
defaultValue: 'read_write',
validate: {
isIn: [['read', 'read_write', 'maintainer']],
},
+14 -17
View File
@@ -155,25 +155,22 @@ Document.associate = models => {
Document.hasMany(models.View, {
as: 'views',
});
Document.addScope(
'defaultScope',
{
include: [
{ model: models.Collection, as: 'collection' },
{ model: models.User, as: 'createdBy', paranoid: false },
{ model: models.User, as: 'updatedBy', paranoid: false },
],
where: {
publishedAt: {
[Op.ne]: null,
},
Document.addScope('defaultScope', {
include: [
{ model: models.User, as: 'createdBy', paranoid: false },
{ model: models.User, as: 'updatedBy', paranoid: false },
],
where: {
publishedAt: {
[Op.ne]: null,
},
},
{ override: true }
);
});
Document.addScope('withCollection', {
include: [{ model: models.Collection, as: 'collection' }],
});
Document.addScope('withUnpublished', {
include: [
{ model: models.Collection, as: 'collection' },
{ model: models.User, as: 'createdBy', paranoid: false },
{ model: models.User, as: 'updatedBy', paranoid: false },
],
@@ -190,8 +187,8 @@ Document.associate = models => {
}));
};
Document.findByPk = async (id, options) => {
const scope = Document.scope('withUnpublished');
Document.findByPk = async function(id, options) {
const scope = this.scope('withUnpublished', 'withCollection');
if (isUUID(id)) {
return scope.findOne({
+19 -3
View File
@@ -3,7 +3,7 @@ import crypto from 'crypto';
import uuid from 'uuid';
import JWT from 'jsonwebtoken';
import subMinutes from 'date-fns/sub_minutes';
import { DataTypes, sequelize, encryptedFields } from '../sequelize';
import { Op, DataTypes, sequelize, encryptedFields } from '../sequelize';
import { publicS3Endpoint, uploadToS3FromUrl } from '../utils/s3';
import { sendEmail } from '../mailer';
import { Star, Team, Collection, NotificationSetting, ApiKey } from '.';
@@ -51,17 +51,33 @@ User.associate = models => {
});
User.hasMany(models.Document, { as: 'documents' });
User.hasMany(models.View, { as: 'views' });
User.belongsToMany(models.User, {
as: 'users',
through: 'collection_users',
onDelete: 'cascade',
});
};
// Instance methods
User.prototype.collectionIds = async function(paranoid: boolean = true) {
User.prototype.collectionIds = async function(
paranoid: boolean = true,
writeAccess = true
) {
let models = await Collection.findAll({
attributes: ['id', 'private'],
where: { teamId: this.teamId },
include: [
{
model: User,
through: 'collection_users',
through: {
where: writeAccess
? {
permission: {
[Op.in]: ['read_write', 'maintainer'],
},
}
: undefined,
},
as: 'users',
where: { id: this.id },
required: false,
+47 -21
View File
@@ -1,6 +1,6 @@
// @flow
import invariant from 'invariant';
import policy from './policy';
import { map } from 'lodash';
import { Collection, User } from '../models';
import { AdminRequiredError } from '../errors';
@@ -8,34 +8,60 @@ const { allow } = policy;
allow(User, 'create', Collection);
allow(
User,
['read', 'publish', 'update', 'export'],
Collection,
(user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
if (
collection.private &&
!map(collection.users, u => u.id).includes(user.id)
) {
return false;
}
return true;
}
);
allow(User, 'delete', Collection, (user, collection) => {
allow(User, ['read', 'export'], Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
if (
collection.private &&
!map(collection.users, u => u.id).includes(user.id)
(!collection.memberships || !collection.memberships.length)
) {
return false;
}
return true;
});
allow(User, ['publish', 'update'], Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
if (collection.private) {
invariant(
collection.memberships,
'membership should be preloaded, did you forget withMembership scope?'
);
if (!collection.memberships.length) return false;
if (
!['read_write', 'maintainer'].includes(
collection.memberships[0].permission
)
) {
return false;
}
}
return true;
});
allow(User, 'delete', Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
if (collection.private) {
invariant(
collection.memberships,
'membership should be preloaded, did you forget withMembership scope?'
);
if (!collection.memberships.length) return false;
if (
!['read_write', 'maintainer'].includes(
collection.memberships[0].permission
)
) {
return false;
}
}
if (user.isAdmin) return true;
if (user.id === collection.creatorId) return true;
+37 -15
View File
@@ -1,4 +1,5 @@
// @flow
import invariant from 'invariant';
import policy from './policy';
import { Document, Revision, User } from '../models';
@@ -6,37 +7,58 @@ const { allow, cannot } = policy;
allow(User, 'create', Document);
allow(User, ['read', 'delete'], Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
allow(User, ['read', 'share'], Document, (user, document, { collection }) => {
// existance of collection option is not required here to account for share tokens
if (collection && cannot(user, 'read', collection)) {
return false;
}
return user.teamId === document.teamId;
});
allow(User, ['update', 'move', 'share'], Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
}
// the collection associated with the document must be passed in options, it must
// be queried withMembership scope to include the models needed to authorize
allow(User, ['update', 'move'], Document, (user, document, { collection }) => {
invariant(
collection,
'collection is missing, did you forget to include in the query scope?'
);
if (cannot(user, 'update', collection)) return false;
if (document.archivedAt) return false;
return user.teamId === document.teamId;
});
allow(User, 'archive', Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
}
// the collection associated with the document must be passed in options, it must
// be queried withMembership scope to include the models needed to authorize
allow(User, ['delete'], Document, (user, document, { collection }) => {
// allow deleting document without a collection
if (collection && cannot(user, 'update', collection)) return false;
if (document.archivedAt) return false;
return user.teamId === document.teamId;
});
allow(User, 'archive', Document, (user, document, { collection }) => {
invariant(
collection,
'collection is missing, did you forget to include in the query scope?'
);
if (cannot(user, 'update', collection)) return false;
if (!document.publishedAt) return false;
if (document.archivedAt) return false;
return user.teamId === document.teamId;
});
allow(User, 'unarchive', Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
}
allow(User, 'unarchive', Document, (user, document, { collection }) => {
invariant(
collection,
'collection is missing, did you forget to include in the query scope?'
);
if (cannot(user, 'update', collection)) return false;
if (!document.archivedAt) return false;
return user.teamId === document.teamId;
+4 -3
View File
@@ -1,5 +1,5 @@
// @flow
import { Document, Team } from '../models';
import { Document, Collection, Team } from '../models';
type Action = {
type: string,
@@ -10,6 +10,7 @@ type Action = {
export default function present(
document: Document,
collection: Collection,
team: Team,
context?: string,
actions?: Action[]
@@ -21,10 +22,10 @@ export default function present(
: document.getSummary();
return {
color: document.collection.color,
color: collection.color,
title: document.title,
title_link: `${team.url}${document.url}`,
footer: document.collection.name,
footer: collection.name,
callback_id: document.id,
text,
ts: document.getTimestamp(),