From 980bc7e42657c7a3936c7d9f85961f5409b53f0f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 5 Sep 2019 23:30:06 -0700 Subject: [PATCH 01/23] Passing test suite --- app/components/Editor/Editor.js | 1 + app/components/InputSelect.js | 72 +++++++++++++++ .../CollectionMembers/CollectionMembers.js | 15 ++++ .../components/MemberListItem.js | 34 ++++++- app/stores/MembershipsStore.js | 3 + server/api/collections.js | 32 +++++-- server/api/documents.js | 90 ++++++++++++------- server/api/documents.test.js | 86 +++++++++++++++--- server/api/hooks.js | 6 +- .../migrations/20190811231511-maintainers.js | 31 +++++-- server/models/Collection.js | 29 +++--- server/models/CollectionUser.js | 1 + server/models/Document.js | 31 +++---- server/models/User.js | 22 ++++- server/policies/collection.js | 68 +++++++++----- server/policies/document.js | 52 +++++++---- server/presenters/slackAttachment.js | 7 +- 17 files changed, 442 insertions(+), 138 deletions(-) create mode 100644 app/components/InputSelect.js diff --git a/app/components/Editor/Editor.js b/app/components/Editor/Editor.js index 4fa087693c..517a3073c2 100644 --- a/app/components/Editor/Editor.js +++ b/app/components/Editor/Editor.js @@ -91,6 +91,7 @@ class Editor extends React.Component { onShowToast={this.onShowToast} getLinkComponent={this.getLinkComponent} tooltip={EditorTooltip} + headingsOffset={1} {...this.props} /> diff --git a/app/components/InputSelect.js b/app/components/InputSelect.js new file mode 100644 index 0000000000..d60689b7b2 --- /dev/null +++ b/app/components/InputSelect.js @@ -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 { + @observable focused: boolean = false; + + handleBlur = () => { + this.focused = false; + }; + + handleFocus = () => { + this.focused = true; + }; + + render() { + const { label, className, labelHidden, options, ...rest } = this.props; + + const wrappedLabel = {label}; + + return ( + + ); + } +} + +export default InputSelect; diff --git a/app/scenes/CollectionMembers/CollectionMembers.js b/app/scenes/CollectionMembers/CollectionMembers.js index a9d4c62308..768a8255c0 100644 --- a/app/scenes/CollectionMembers/CollectionMembers.js +++ b/app/scenes/CollectionMembers/CollectionMembers.js @@ -50,6 +50,19 @@ class CollectionMembers extends React.Component { } }; + 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 { this.handleRemoveUser(item)} + onUpdate={permission => this.handleUpdateUser(item, permission)} /> )} /> diff --git a/app/scenes/CollectionMembers/components/MemberListItem.js b/app/scenes/CollectionMembers/components/MemberListItem.js index dc5249de6e..c11fe6ffda 100644 --- a/app/scenes/CollectionMembers/components/MemberListItem.js +++ b/app/scenes/CollectionMembers/components/MemberListItem.js @@ -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 ( { image={} actions={ + {canEdit && + onUpdate && ( + onUpdate(ev.target.value)} labelHidden /> From 3f6b8beab991b1654fd736565d694c2d03b29b06 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Sep 2019 14:19:36 -0700 Subject: [PATCH 04/23] test: Add collections.update tests --- .../__snapshots__/collections.test.js.snap | 9 ++ server/api/collections.js | 42 ++++------ server/api/collections.test.js | 83 +++++++++++++++++++ server/models/User.js | 14 +--- server/policies/collection.js | 10 +-- 5 files changed, 114 insertions(+), 44 deletions(-) diff --git a/server/api/__snapshots__/collections.test.js.snap b/server/api/__snapshots__/collections.test.js.snap index c3ddf53d1b..f5f5bb344f 100644 --- a/server/api/__snapshots__/collections.test.js.snap +++ b/server/api/__snapshots__/collections.test.js.snap @@ -79,6 +79,15 @@ Object { } `; +exports[`#collections.update should require authentication 1`] = ` +Object { + "error": "authentication_required", + "message": "Authentication required", + "ok": false, + "status": 401, +} +`; + exports[`#collections.users should require authentication 1`] = ` Object { "error": "authentication_required", diff --git a/server/api/collections.js b/server/api/collections.js index ab5da7f5f6..9000eab588 100644 --- a/server/api/collections.js +++ b/server/api/collections.js @@ -50,7 +50,7 @@ router.post('collections.create', auth(), async ctx => { }); ctx.body = { - data: await presentCollection(collection), + data: presentCollection(collection), policies: presentPolicies(user, [collection]), }; }); @@ -66,7 +66,7 @@ router.post('collections.info', auth(), async ctx => { authorize(user, 'read', collection); ctx.body = { - data: await presentCollection(collection), + data: presentCollection(collection), policies: presentPolicies(user, [collection]), }; }); @@ -279,15 +279,20 @@ router.post('collections.exportAll', auth(), async ctx => { router.post('collections.update', auth(), async ctx => { const { id, name, description, color } = ctx.body; const isPrivate = ctx.body.private; - ctx.assertPresent(name, 'name is required'); - if (color) + + if (color) { ctx.assertHexColor(color, 'Invalid hex value (please use format #FFFFFF)'); + } const user = ctx.state.user; - const collection = await Collection.findByPk(id); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(id); authorize(user, 'update', collection); + // we're making this collection private right now, ensure that the current + // user has a read-write membership so that at least they can edit it if (isPrivate && !collection.private) { await CollectionUser.findOrCreate({ where: { @@ -318,16 +323,9 @@ router.post('collections.update', auth(), async ctx => { // 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, - }, - ], + scope: { + method: ['withMembership', user.id], + }, }); ctx.body = { @@ -338,7 +336,6 @@ router.post('collections.update', auth(), async ctx => { router.post('collections.list', auth(), pagination(), async ctx => { const user = ctx.state.user; - const collectionIds = await user.collectionIds(); let collections = await Collection.findAll({ where: { @@ -350,15 +347,10 @@ router.post('collections.list', auth(), pagination(), async ctx => { limit: ctx.state.pagination.limit, }); - const data = await Promise.all( - collections.map(async collection => await presentCollection(collection)) - ); - const policies = presentPolicies(user, collections); - ctx.body = { pagination: ctx.state.pagination, - data, - policies, + data: collections.map(presentCollection), + policies: presentPolicies(user, collections), }; }); @@ -367,7 +359,9 @@ router.post('collections.delete', auth(), async ctx => { const user = ctx.state.user; ctx.assertUuid(id, 'id is required'); - const collection = await Collection.findByPk(id); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(id); authorize(user, 'delete', collection); const total = await Collection.count(); diff --git a/server/api/collections.test.js b/server/api/collections.test.js index 72e7e5c2ee..685e6c539e 100644 --- a/server/api/collections.test.js +++ b/server/api/collections.test.js @@ -472,6 +472,89 @@ describe('#collections.create', async () => { }); }); +describe('#collections.update', async () => { + it('should require authentication', async () => { + const collection = await buildCollection(); + const res = await server.post('/api/collections.update', { + body: { id: collection.id, name: 'Test' }, + }); + const body = await res.json(); + + expect(res.status).toEqual(401); + expect(body).toMatchSnapshot(); + }); + + it('allows editing non-private collection', async () => { + const { user, collection } = await seed(); + const res = await server.post('/api/collections.update', { + body: { token: user.getJwtToken(), id: collection.id, name: 'Test' }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.name).toBe('Test'); + expect(body.policies.length).toBe(1); + }); + + it('allows editing from non-private to private collection', async () => { + const { user, collection } = await seed(); + const res = await server.post('/api/collections.update', { + body: { + token: user.getJwtToken(), + id: collection.id, + private: true, + name: 'Test', + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.name).toBe('Test'); + expect(body.data.private).toBe(true); + + // ensure we return with a write level policy + expect(body.policies.length).toBe(1); + expect(body.policies[0].abilities.update).toBe(true); + }); + + it('allows editing by read-write collection user', async () => { + const { user, 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/collections.update', { + body: { token: user.getJwtToken(), id: collection.id, name: 'Test' }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.name).toBe('Test'); + expect(body.policies.length).toBe(1); + }); + + it('does not allow editing by read-only collection user', async () => { + const { user, 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/collections.update', { + body: { token: user.getJwtToken(), id: collection.id, name: 'Test' }, + }); + expect(res.status).toEqual(403); + }); +}); + describe('#collections.delete', async () => { it('should require authentication', async () => { const res = await server.post('/api/collections.delete'); diff --git a/server/models/User.js b/server/models/User.js index 806c82622f..ef35f02732 100644 --- a/server/models/User.js +++ b/server/models/User.js @@ -59,25 +59,13 @@ User.associate = models => { }; // Instance methods -User.prototype.collectionIds = async function( - paranoid: boolean = true, - writeAccess = true -) { +User.prototype.collectionIds = async function(paranoid: boolean = true) { let models = await Collection.findAll({ attributes: ['id', 'private'], where: { teamId: this.teamId }, include: [ { model: User, - through: { - where: writeAccess - ? { - permission: { - [Op.in]: ['read_write', 'maintainer'], - }, - } - : undefined, - }, as: 'users', where: { id: this.id }, required: false, diff --git a/server/policies/collection.js b/server/policies/collection.js index 2d7a35e20d..9a1d1765e4 100644 --- a/server/policies/collection.js +++ b/server/policies/collection.js @@ -31,13 +31,9 @@ allow(User, ['publish', 'update'], Collection, (user, collection) => { ); if (!collection.memberships.length) return false; - if ( - !['read_write', 'maintainer'].includes( - collection.memberships[0].permission - ) - ) { - return false; - } + return ['read_write', 'maintainer'].includes( + collection.memberships[0].permission + ); } return true; From d74e051d00591ed4316f36a175076032292a1b97 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Sep 2019 14:26:45 -0700 Subject: [PATCH 05/23] lint --- server/models/User.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/models/User.js b/server/models/User.js index ef35f02732..8d241dad1e 100644 --- a/server/models/User.js +++ b/server/models/User.js @@ -3,7 +3,7 @@ import crypto from 'crypto'; import uuid from 'uuid'; import JWT from 'jsonwebtoken'; import subMinutes from 'date-fns/sub_minutes'; -import { Op, DataTypes, sequelize, encryptedFields } from '../sequelize'; +import { DataTypes, sequelize, encryptedFields } from '../sequelize'; import { publicS3Endpoint, uploadToS3FromUrl } from '../utils/s3'; import { sendEmail } from '../mailer'; import { Star, Team, Collection, NotificationSetting, ApiKey } from '.'; From 55391c74d0040354717e930eb34dee0816892d70 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 6 Sep 2019 14:26:50 -0700 Subject: [PATCH 06/23] test: moar tests --- server/api/collections.js | 15 +++++--- server/api/collections.test.js | 64 ++++++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/server/api/collections.js b/server/api/collections.js index 9000eab588..e8e367d676 100644 --- a/server/api/collections.js +++ b/server/api/collections.js @@ -306,6 +306,8 @@ router.post('collections.update', auth(), async ctx => { }); } + const isPrivacyChanged = isPrivate !== collection.private; + collection.name = name; collection.description = description; collection.color = color; @@ -322,11 +324,14 @@ router.post('collections.update', auth(), async ctx => { }); // must reload to update collection membership for correct policy calculation - await collection.reload({ - scope: { - method: ['withMembership', user.id], - }, - }); + // if the privacy level has changed. Otherwise skip this query for speed. + if (isPrivacyChanged) { + await collection.reload({ + scope: { + method: ['withMembership', user.id], + }, + }); + } ctx.body = { data: presentCollection(collection), diff --git a/server/api/collections.test.js b/server/api/collections.test.js index 685e6c539e..d34b54882e 100644 --- a/server/api/collections.test.js +++ b/server/api/collections.test.js @@ -278,7 +278,7 @@ describe('#collections.users', async () => { createdById: user.id, collectionId: collection.id, userId: user.id, - permission: 'read_write', + permission: 'read', }); const res = await server.post('/api/collections.users', { @@ -431,6 +431,27 @@ describe('#collections.info', async () => { expect(res.status).toEqual(403); }); + it('should allow user member of collection', async () => { + const { user, 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/collections.info', { + body: { token: user.getJwtToken(), id: collection.id }, + }); + const body = await res.json(); + + 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(); @@ -484,6 +505,15 @@ describe('#collections.update', async () => { expect(body).toMatchSnapshot(); }); + it('should require authorization', async () => { + const { collection } = await seed(); + const user = await buildUser(); + const res = await server.post('/api/collections.update', { + body: { token: user.getJwtToken(), id: collection.id, name: 'Test' }, + }); + expect(res.status).toEqual(403); + }); + it('allows editing non-private collection', async () => { const { user, collection } = await seed(); const res = await server.post('/api/collections.update', { @@ -515,6 +545,36 @@ describe('#collections.update', async () => { expect(body.policies[0].abilities.update).toBe(true); }); + it('allows editing from private to non-private collection', async () => { + const { user, 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/collections.update', { + body: { + token: user.getJwtToken(), + id: collection.id, + private: false, + name: 'Test', + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.name).toBe('Test'); + expect(body.data.private).toBe(false); + + // ensure we return with a write level policy + expect(body.policies.length).toBe(1); + expect(body.policies[0].abilities.update).toBe(true); + }); + it('allows editing by read-write collection user', async () => { const { user, collection } = await seed(); collection.private = true; @@ -573,7 +633,7 @@ describe('#collections.delete', async () => { expect(res.status).toEqual(403); }); - it('should not delete last collection', async () => { + it('should not allow deleting last collection', async () => { const { user, collection } = await seed(); const res = await server.post('/api/collections.delete', { body: { token: user.getJwtToken(), id: collection.id }, From 0326937e95ccd0503a2747d15135feab7c1c070c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Sep 2019 11:52:35 -0700 Subject: [PATCH 07/23] fix: Missing scopes, more missing tests --- server/api/collections.js | 18 ++++-- server/api/collections.test.js | 10 +++ server/api/documents.js | 27 ++++++-- server/api/documents.test.js | 113 +++++++++++++++++++++++++++++++++ server/pages/developers/Api.js | 8 ++- 5 files changed, 163 insertions(+), 13 deletions(-) diff --git a/server/api/collections.js b/server/api/collections.js index e8e367d676..799ccdcf67 100644 --- a/server/api/collections.js +++ b/server/api/collections.js @@ -156,8 +156,11 @@ router.post('collections.users', auth(), async ctx => { const { id } = ctx.body; ctx.assertUuid(id, 'id is required'); - const collection = await Collection.findByPk(id); - authorize(ctx.state.user, 'read', collection); + const user = ctx.state.user; + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(id); + authorize(user, 'read', collection); const users = await collection.getUsers(); @@ -170,8 +173,11 @@ router.post('collections.memberships', auth(), pagination(), async ctx => { const { id, query, permission } = ctx.body; ctx.assertUuid(id, 'id is required'); - const collection = await Collection.findByPk(id); - authorize(ctx.state.user, 'read', collection); + const user = ctx.state.user; + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(id); + authorize(user, 'read', collection); let where = { collectionId: id, @@ -342,7 +348,9 @@ router.post('collections.update', auth(), async ctx => { router.post('collections.list', auth(), pagination(), async ctx => { const user = ctx.state.user; const collectionIds = await user.collectionIds(); - let collections = await Collection.findAll({ + let collections = await Collection.scope({ + method: ['withMembership', user.id], + }).findAll({ where: { teamId: user.teamId, id: collectionIds, diff --git a/server/api/collections.test.js b/server/api/collections.test.js index d34b54882e..ddf2af75cc 100644 --- a/server/api/collections.test.js +++ b/server/api/collections.test.js @@ -28,6 +28,8 @@ describe('#collections.list', async () => { expect(res.status).toEqual(200); expect(body.data.length).toEqual(1); expect(body.data[0].id).toEqual(collection.id); + expect(body.policies.length).toEqual(1); + expect(body.policies[0].abilities.read).toEqual(true); }); it('should not return private collections not a member of', async () => { @@ -60,6 +62,8 @@ describe('#collections.list', async () => { expect(res.status).toEqual(200); expect(body.data.length).toEqual(2); + expect(body.policies.length).toEqual(2); + expect(body.policies[0].abilities.read).toEqual(true); }); }); @@ -274,6 +278,9 @@ describe('#collections.remove_user', async () => { describe('#collections.users', async () => { it('should return users in private collection', async () => { const { collection, user } = await seed(); + collection.private = true; + await collection.save(); + await CollectionUser.create({ createdById: user.id, collectionId: collection.id, @@ -311,6 +318,9 @@ describe('#collections.users', async () => { describe('#collections.memberships', async () => { it('should return members in private collection', async () => { const { collection, user } = await seed(); + collection.private = true; + await collection.save(); + await CollectionUser.create({ createdById: user.id, collectionId: collection.id, diff --git a/server/api/documents.js b/server/api/documents.js index 2e6d4d34c6..9f14880b01 100644 --- a/server/api/documents.js +++ b/server/api/documents.js @@ -53,7 +53,9 @@ router.post('documents.list', auth(), pagination(), async ctx => { ctx.assertUuid(collectionId, 'collection must be a UUID'); where = { ...where, collectionId }; - const collection = await Collection.findByPk(collectionId); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(collectionId); authorize(user, 'read', collection); // otherwise, filter by all collections the user has access to @@ -78,7 +80,12 @@ router.post('documents.list', auth(), pagination(), async ctx => { // add the users starred state to the response by default const starredScope = { method: ['withStarred', user.id] }; - const documents = await Document.scope('defaultScope', starredScope).findAll({ + const collectionScope = { method: ['withCollection', user.id] }; + const documents = await Document.scope( + 'defaultScope', + starredScope, + collectionScope + ).findAll({ where, order: [[sort, direction]], offset: ctx.state.pagination.offset, @@ -99,18 +106,24 @@ router.post('documents.list', auth(), pagination(), async ctx => { }); router.post('documents.pinned', auth(), pagination(), async ctx => { - const { sort = 'updatedAt' } = ctx.body; - const collectionId = ctx.body.collection; + const { collectionId, sort = 'updatedAt' } = ctx.body; let direction = ctx.body.direction; if (direction !== 'ASC') direction = 'DESC'; - ctx.assertUuid(collectionId, 'collection is required'); + ctx.assertUuid(collectionId, 'collectionId is required'); const user = ctx.state.user; - const collection = await Collection.findByPk(collectionId); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(collectionId); authorize(user, 'read', collection); const starredScope = { method: ['withStarred', user.id] }; - const documents = await Document.scope('defaultScope', starredScope).findAll({ + const collectionScope = { method: ['withCollection', user.id] }; + const documents = await Document.scope( + 'defaultScope', + starredScope, + collectionScope + ).findAll({ where: { teamId: user.teamId, collectionId, diff --git a/server/api/documents.test.js b/server/api/documents.test.js index 4d25b0bf97..81fd820576 100644 --- a/server/api/documents.test.js +++ b/server/api/documents.test.js @@ -281,6 +281,30 @@ describe('#documents.list', async () => { expect(body.data.length).toEqual(1); }); + it('should allow filtering to private collection', async () => { + const { user, collection } = await seed(); + collection.private = true; + await collection.save(); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + const res = await server.post('/api/documents.list', { + body: { + token: user.getJwtToken(), + collection: collection.id, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + }); + it('should return backlinks', async () => { const { user, document } = await seed(); const anotherDoc = await buildDocument({ @@ -315,6 +339,64 @@ describe('#documents.list', async () => { }); }); +describe('#documents.pinned', async () => { + it('should return pinned documents', async () => { + const { user, document } = await seed(); + document.pinnedById = user.id; + await document.save(); + + const res = await server.post('/api/documents.pinned', { + body: { token: user.getJwtToken(), collectionId: document.collectionId }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].id).toEqual(document.id); + }); + + it('should return pinned documents in private collections member of', async () => { + const { user, collection, document } = await seed(); + collection.private = true; + await collection.save(); + + document.pinnedById = user.id; + await document.save(); + + await CollectionUser.create({ + collectionId: collection.id, + userId: user.id, + createdById: user.id, + permission: 'read_write', + }); + + const res = await server.post('/api/documents.pinned', { + body: { token: user.getJwtToken(), collectionId: document.collectionId }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].id).toEqual(document.id); + }); + + it('should not return pinned documents in private collections not a member of', async () => { + const { user, collection } = await seed(); + collection.private = true; + await collection.save(); + + const res = await server.post('/api/documents.pinned', { + body: { token: user.getJwtToken(), collectionId: collection.id }, + }); + expect(res.status).toEqual(403); + }); + + it('should require authentication', async () => { + const res = await server.post('/api/documents.pinned'); + expect(res.status).toEqual(401); + }); +}); + describe('#documents.drafts', async () => { it('should return unpublished documents', async () => { const { user, document } = await seed(); @@ -582,6 +664,37 @@ describe('#documents.search', async () => { expect(body.data[0].document.id).toEqual(document.id); }); + it('should return documents for a specific private collection', async () => { + const { user } = await seed(); + const collection = await buildCollection({ private: true }); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + const document = await buildDocument({ + title: 'search term', + text: 'search term', + teamId: user.teamId, + }); + + const res = await server.post('/api/documents.search', { + body: { + token: user.getJwtToken(), + query: 'search term', + collectionId: document.collectionId, + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].document.id).toEqual(document.id); + }); + it('should return documents for a specific collection', async () => { const { user } = await seed(); const collection = await buildCollection(); diff --git a/server/pages/developers/Api.js b/server/pages/developers/Api.js index 03abbd1d41..c90d1e4ff5 100644 --- a/server/pages/developers/Api.js +++ b/server/pages/developers/Api.js @@ -579,7 +579,13 @@ export default function Api() { label="Get pinned documents for a collection" > Return pinned documents for a collection - + + + Date: Sat, 7 Sep 2019 11:52:50 -0700 Subject: [PATCH 08/23] fix: Handle collection privacy change over socket --- app/components/SocketProvider.js | 17 +++++++++++++++-- app/scenes/Collection.js | 2 +- app/stores/MembershipsStore.js | 9 +++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/components/SocketProvider.js b/app/components/SocketProvider.js index d34a1877a6..08ee667883 100644 --- a/app/components/SocketProvider.js +++ b/app/components/SocketProvider.js @@ -4,6 +4,7 @@ import { inject } from 'mobx-react'; import io from 'socket.io-client'; import DocumentsStore from 'stores/DocumentsStore'; import CollectionsStore from 'stores/CollectionsStore'; +import MembershipsStore from 'stores/MembershipsStore'; import AuthStore from 'stores/AuthStore'; import UiStore from 'stores/UiStore'; @@ -13,6 +14,7 @@ type Props = { children: React.Node, documents: DocumentsStore, collections: CollectionsStore, + memberships: MembershipsStore, auth: AuthStore, ui: UiStore, }; @@ -27,7 +29,7 @@ class SocketProvider extends React.Component { path: '/realtime', }); - const { auth, ui, documents, collections } = this.props; + const { auth, ui, documents, collections, memberships } = this.props; if (!auth.token) return; this.socket.on('connect', () => { @@ -66,12 +68,21 @@ class SocketProvider extends React.Component { } if (event.collections) { event.collections.forEach(collection => { + const previous = collections.get(collection.id); + if (collection.deletedAt) { collections.remove(collection.id); documents.removeCollectionDocuments(collection.id); } else { collections.add(collection); } + + // If the collection changed privacy then we need to reload associated + // memberships and policies to reflect any new permissions + if (previous && previous.private !== collection.private) { + collections.fetch(collection.id, { force: true }); + memberships.removeCollectionId(collection.id); + } }); } }); @@ -105,4 +116,6 @@ class SocketProvider extends React.Component { } } -export default inject('auth', 'ui', 'documents', 'collections')(SocketProvider); +export default inject('auth', 'ui', 'documents', 'collections', 'memberships')( + SocketProvider +); diff --git a/app/scenes/Collection.js b/app/scenes/Collection.js index 888122db2b..5c80812f0c 100644 --- a/app/scenes/Collection.js +++ b/app/scenes/Collection.js @@ -79,7 +79,7 @@ class CollectionScene extends React.Component { this.collection = collection; await this.props.documents.fetchPinned({ - collection: id, + collectionId: id, }); } diff --git a/app/stores/MembershipsStore.js b/app/stores/MembershipsStore.js index 500aff70ce..a929316bfd 100644 --- a/app/stores/MembershipsStore.js +++ b/app/stores/MembershipsStore.js @@ -70,4 +70,13 @@ export default class MembershipsStore extends BaseStore { this.remove(`${userId}-${collectionId}`); } + + @action + removeCollectionId(collectionId: string) { + this.data.forEach((membership, key) => { + if (key.includes(collectionId)) { + this.remove(key); + } + }); + } } From cdafc3bb40a60f3b8764818048c75fa5bf8f5db0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Sep 2019 12:21:12 -0700 Subject: [PATCH 09/23] fix: More membership scopes --- app/stores/MembershipsStore.js | 4 ++-- server/api/collections.js | 4 +++- server/api/collections.test.js | 21 ++++++++++++++++++++- server/api/documents.js | 4 +++- server/api/documents.test.js | 8 +++++--- server/index.js | 4 +++- server/models/Document.js | 12 ++++++++---- 7 files changed, 44 insertions(+), 13 deletions(-) diff --git a/app/stores/MembershipsStore.js b/app/stores/MembershipsStore.js index a929316bfd..0849f5b487 100644 --- a/app/stores/MembershipsStore.js +++ b/app/stores/MembershipsStore.js @@ -72,11 +72,11 @@ export default class MembershipsStore extends BaseStore { } @action - removeCollectionId(collectionId: string) { + removeCollectionId = (collectionId: string) => { this.data.forEach((membership, key) => { if (key.includes(collectionId)) { this.remove(key); } }); - } + }; } diff --git a/server/api/collections.js b/server/api/collections.js index 799ccdcf67..ffafed4f84 100644 --- a/server/api/collections.js +++ b/server/api/collections.js @@ -229,7 +229,9 @@ router.post('collections.export', 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, 'export', collection); const filePath = await archiveCollection(collection); diff --git a/server/api/collections.test.js b/server/api/collections.test.js index ddf2af75cc..2c54b8a45c 100644 --- a/server/api/collections.test.js +++ b/server/api/collections.test.js @@ -68,7 +68,7 @@ describe('#collections.list', async () => { }); describe('#collections.export', async () => { - it('should require user to be a member', async () => { + it('should now allow export of private collection not a member', async () => { const { user } = await seed(); const collection = await buildCollection({ private: true, @@ -81,6 +81,25 @@ describe('#collections.export', async () => { expect(res.status).toEqual(403); }); + it('should allow export of private collection', async () => { + const { user, collection } = await seed(); + collection.private = true; + await collection.save(); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + const res = await server.post('/api/collections.export', { + body: { token: user.getJwtToken(), id: collection.id }, + }); + + expect(res.status).toEqual(200); + }); + it('should require authentication', async () => { const res = await server.post('/api/collections.export'); const body = await res.json(); diff --git a/server/api/documents.js b/server/api/documents.js index 9f14880b01..bac761fc43 100644 --- a/server/api/documents.js +++ b/server/api/documents.js @@ -457,7 +457,9 @@ router.post('documents.search', auth(), pagination(), async ctx => { if (collectionId) { ctx.assertUuid(collectionId, 'collectionId must be a UUID'); - const collection = await Collection.findByPk(collectionId); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(collectionId); authorize(user, 'read', collection); } diff --git a/server/api/documents.test.js b/server/api/documents.test.js index 81fd820576..15eb748249 100644 --- a/server/api/documents.test.js +++ b/server/api/documents.test.js @@ -665,8 +665,9 @@ describe('#documents.search', async () => { }); it('should return documents for a specific private collection', async () => { - const { user } = await seed(); - const collection = await buildCollection({ private: true }); + const { user, collection } = await seed(); + collection.private = true; + await collection.save(); await CollectionUser.create({ createdById: user.id, @@ -679,13 +680,14 @@ describe('#documents.search', async () => { title: 'search term', text: 'search term', teamId: user.teamId, + collectionId: collection.id, }); const res = await server.post('/api/documents.search', { body: { token: user.getJwtToken(), query: 'search term', - collectionId: document.collectionId, + collectionId: collection.id, }, }); const body = await res.json(); diff --git a/server/index.js b/server/index.js index a130d17b50..21c2256eca 100644 --- a/server/index.js +++ b/server/index.js @@ -53,7 +53,9 @@ if (process.env.WEBSOCKETS_ENABLED === 'true') { // allow the client to request to join rooms based on // new collections being created. socket.on('join', async event => { - const collection = await Collection.findByPk(event.roomId); + const collection = await Collection.scope({ + method: ['withMembership', user.id], + }).findByPk(event.roomId); if (can(user, 'read', collection)) { socket.join(`collection-${event.roomId}`); diff --git a/server/models/Document.js b/server/models/Document.js index e8fa68e077..641ac49c77 100644 --- a/server/models/Document.js +++ b/server/models/Document.js @@ -303,14 +303,18 @@ Document.searchForUser = async ( }); // Final query to get associated document data - const documents = await Document.scope({ - method: ['withViews', user.id], - }).findAll({ + const documents = await Document.scope( + { + method: ['withViews', user.id], + }, + { + method: ['withCollection', user.id], + } + ).findAll({ where: { id: map(results, 'id'), }, include: [ - { model: Collection, as: 'collection' }, { model: User, as: 'createdBy', paranoid: false }, { model: User, as: 'updatedBy', paranoid: false }, ], From 05b97e015c907e19ac27294412112c0b706c0105 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Sep 2019 10:54:45 -0700 Subject: [PATCH 10/23] fix: view endpoint permissions --- server/api/views.js | 4 ++-- server/api/views.test.js | 47 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/server/api/views.js b/server/api/views.js index 31c8bd73dd..dde61d8bba 100644 --- a/server/api/views.js +++ b/server/api/views.js @@ -13,7 +13,7 @@ router.post('views.list', auth(), async ctx => { ctx.assertUuid(documentId, 'documentId is required'); const user = ctx.state.user; - const document = await Document.findByPk(documentId); + const document = await Document.findByPk(documentId, { userId: user.id }); authorize(user, 'read', document); const views = await View.findAll({ @@ -37,7 +37,7 @@ router.post('views.create', auth(), async ctx => { ctx.assertUuid(documentId, 'documentId is required'); const user = ctx.state.user; - const document = await Document.findByPk(documentId); + const document = await Document.findByPk(documentId, { userId: user.id }); authorize(user, 'read', document); await View.increment({ documentId, userId: user.id }); diff --git a/server/api/views.test.js b/server/api/views.test.js index 43b4d74c60..099d1af47f 100644 --- a/server/api/views.test.js +++ b/server/api/views.test.js @@ -1,7 +1,7 @@ /* eslint-disable flowtype/require-valid-file-annotation */ import TestServer from 'fetch-test-server'; import app from '../app'; -import { View } from '../models'; +import { View, CollectionUser } from '../models'; import { flushdb, seed } from '../test/support'; import { buildUser } from '../test/factories'; @@ -25,6 +25,30 @@ describe('#views.list', async () => { expect(body.data[0].user.name).toBe(user.name); }); + it('should return views for a document in read-only collection', async () => { + const { user, document, collection } = await seed(); + collection.private = true; + await collection.save(); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + await View.increment({ documentId: document.id, userId: user.id }); + + const res = await server.post('/api/views.list', { + body: { token: user.getJwtToken(), documentId: document.id }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data[0].count).toBe(1); + expect(body.data[0].user.name).toBe(user.name); + }); + it('should require authentication', async () => { const { document } = await seed(); const res = await server.post('/api/views.list', { @@ -58,6 +82,27 @@ describe('#views.create', async () => { expect(body.success).toBe(true); }); + it('should allow creating a view record for document in read-only collection', async () => { + const { user, document, collection } = await seed(); + collection.private = true; + await collection.save(); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + const res = await server.post('/api/views.create', { + body: { token: user.getJwtToken(), documentId: 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', { From 6b5c74a056ceea4496e0aa231faf74d701a0d1b1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Sep 2019 10:54:58 -0700 Subject: [PATCH 11/23] fix: respond to privacy change on socket event --- app/components/SocketProvider.js | 5 +++-- app/stores/MembershipsStore.js | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/components/SocketProvider.js b/app/components/SocketProvider.js index 08ee667883..1e4ba6090d 100644 --- a/app/components/SocketProvider.js +++ b/app/components/SocketProvider.js @@ -69,6 +69,7 @@ class SocketProvider extends React.Component { if (event.collections) { event.collections.forEach(collection => { const previous = collections.get(collection.id); + const previousPrivate = previous ? previous.private : undefined; if (collection.deletedAt) { collections.remove(collection.id); @@ -79,9 +80,9 @@ class SocketProvider extends React.Component { // If the collection changed privacy then we need to reload associated // memberships and policies to reflect any new permissions - if (previous && previous.private !== collection.private) { + if (previous && previousPrivate !== collection.private) { collections.fetch(collection.id, { force: true }); - memberships.removeCollectionId(collection.id); + memberships.removeCollectionMemberships(collection.id); } }); } diff --git a/app/stores/MembershipsStore.js b/app/stores/MembershipsStore.js index 0849f5b487..3dfeaa829e 100644 --- a/app/stores/MembershipsStore.js +++ b/app/stores/MembershipsStore.js @@ -72,7 +72,7 @@ export default class MembershipsStore extends BaseStore { } @action - removeCollectionId = (collectionId: string) => { + removeCollectionMemberships = (collectionId: string) => { this.data.forEach((membership, key) => { if (key.includes(collectionId)) { this.remove(key); From 88da8f8792aaeb750d083d6c96ca3460473fa83f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Sep 2019 11:45:02 -0700 Subject: [PATCH 12/23] policy driven menus --- app/menus/DocumentMenu.js | 135 +++++++++++------------ app/scenes/Document/Document.js | 20 +++- app/scenes/Document/components/Header.js | 12 +- app/stores/DocumentsStore.js | 8 +- 4 files changed, 95 insertions(+), 80 deletions(-) diff --git a/app/menus/DocumentMenu.js b/app/menus/DocumentMenu.js index eb7248bfa4..550be5e807 100644 --- a/app/menus/DocumentMenu.js +++ b/app/menus/DocumentMenu.js @@ -8,6 +8,7 @@ import Document from 'models/Document'; import UiStore from 'stores/UiStore'; import AuthStore from 'stores/AuthStore'; import CollectionStore from 'stores/CollectionsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import { documentMoveUrl, documentEditUrl, @@ -22,6 +23,7 @@ type Props = { position?: 'left' | 'right' | 'center', document: Document, collections: CollectionStore, + policies: PoliciesStore, className: string, showPrint?: boolean, showToggleEmbeds?: boolean, @@ -109,6 +111,7 @@ class DocumentMenu extends React.Component { if (this.redirectTo) return ; const { + policies, document, position, className, @@ -118,20 +121,9 @@ class DocumentMenu extends React.Component { onOpen, onClose, } = this.props; - const canShareDocuments = auth.team && auth.team.sharing; - if (document.isArchived) { - return ( - - - Restore - - - Delete… - - - ); - } + const can = policies.abilties(document.id); + const canShareDocuments = can.share && auth.team && auth.team.sharing; return ( { onOpen={onOpen} onClose={onClose} > - {!document.isDraft ? ( - - {showPin && - (document.pinned ? ( + {can.unarchive && ( + + Restore + + )} + {showPin && + (document.pinned + ? can.unpin && ( Unpin - ) : ( + ) + : can.pin && ( Pin to collection ))} - {document.isStarred ? ( + {document.isStarred + ? can.unstar && ( Unstar - ) : ( + ) + : can.star && ( Star )} - {canShareDocuments && ( - - Share link… - - )} -
- - Document history - - - New child document - - Edit - - Duplicate - - - Archive - - - Delete… - - Move… -
- ) : ( - - {canShareDocuments && ( - - Share link… - - )} - - Delete… - - + {canShareDocuments && ( + + Share link… + )}
- - Download - + {can.read && ( + + Document history + + )} + {can.update && ( + + New child document + + )} + {can.update && ( + Edit + )} + {can.update && ( + + Duplicate + + )} + {can.archive && ( + + Archive + + )} + {can.delete && ( + + Delete… + + )} + {can.move && ( + Move… + )} +
+ {can.download && ( + + Download + + )} {showPrint && ( Print )} @@ -218,4 +217,4 @@ class DocumentMenu extends React.Component { } } -export default inject('ui', 'auth', 'collections')(DocumentMenu); +export default inject('ui', 'auth', 'collections', 'policies')(DocumentMenu); diff --git a/app/scenes/Document/Document.js b/app/scenes/Document/Document.js index 37b2b97951..2cad8767e0 100644 --- a/app/scenes/Document/Document.js +++ b/app/scenes/Document/Document.js @@ -37,6 +37,7 @@ import ErrorOffline from 'scenes/ErrorOffline'; import UiStore from 'stores/UiStore'; import AuthStore from 'stores/AuthStore'; import DocumentsStore from 'stores/DocumentsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import RevisionsStore from 'stores/RevisionsStore'; import Document from 'models/Document'; import Revision from 'models/Revision'; @@ -60,6 +61,7 @@ type Props = { match: Object, history: RouterHistory, location: Location, + policies: PoliciesStore, documents: DocumentsStore, revisions: RevisionsStore, newDocument?: boolean, @@ -102,18 +104,26 @@ class DocumentScene extends React.Component { @keydown('m') goToMove(ev) { ev.preventDefault(); + const document = this.document; + if (!document) return; - if (this.document && !this.document.isArchived && !this.document.isDraft) { - this.props.history.push(documentMoveUrl(this.document)); + const can = this.props.policies.abilties(document.id); + + if (can.update) { + this.props.history.push(documentMoveUrl(document)); } } @keydown('e') goToEdit(ev) { ev.preventDefault(); + const document = this.document; + if (!document) return; - if (this.document && !this.document.isArchived) { - this.props.history.push(documentEditUrl(this.document)); + const can = this.props.policies.abilties(document.id); + + if (can.update) { + this.props.history.push(documentEditUrl(document)); } } @@ -451,5 +461,5 @@ const LoadingState = styled(LoadingPlaceholder)` `; export default withRouter( - inject('ui', 'auth', 'documents', 'revisions')(DocumentScene) + inject('ui', 'auth', 'documents', 'policies', 'revisions')(DocumentScene) ); diff --git a/app/scenes/Document/components/Header.js b/app/scenes/Document/components/Header.js index 744f3eecbe..580d2fbcab 100644 --- a/app/scenes/Document/components/Header.js +++ b/app/scenes/Document/components/Header.js @@ -24,8 +24,10 @@ import Modal from 'components/Modal'; import Badge from 'components/Badge'; import Collaborators from 'components/Collaborators'; import { Action, Separator } from 'components/Actions'; +import PoliciesStore from 'stores/PoliciesStore'; type Props = { + policies: PoliciesStore, document: Document, isDraft: boolean, isEditing: boolean, @@ -96,6 +98,7 @@ class Header extends React.Component { const { document, + policies, isEditing, isDraft, isPublishing, @@ -104,10 +107,11 @@ class Header extends React.Component { publishingIsDisabled, auth, } = this.props; - const canShareDocuments = - auth.team && auth.team.sharing && !document.isArchived; + + const can = policies.abilties(document.id); + const canShareDocuments = auth.team && auth.team.sharing && can.share; const canToggleEmbeds = auth.team && auth.team.documentEmbeds; - const canEdit = !document.isArchived && !isEditing; + const canEdit = can.update && !isEditing; return ( { try { const res = await client.post(`/documents.${request}`, options); invariant(res && res.data, 'Document list not available'); - const { data } = res; runInAction('DocumentsStore#fetchNamedPage', () => { - data.forEach(this.add); + res.data.forEach(this.add); + this.addPolicies(res.policies); this.isLoaded = true; }); - return data; + return res.data; } finally { this.isFetching = false; } @@ -425,6 +425,7 @@ export default class DocumentsStore extends BaseStore { runInAction('Document#archive', () => { invariant(res && res.data, 'Data should be available'); document.updateFromJson(res.data); + this.addPolicies(res.policies); }); const collection = this.getCollectionForDocument(document); @@ -440,6 +441,7 @@ export default class DocumentsStore extends BaseStore { runInAction('Document#restore', () => { invariant(res && res.data, 'Data should be available'); document.updateFromJson(res.data); + this.addPolicies(res.policies); }); const collection = this.getCollectionForDocument(document); From b3da93bf4c0c5f69fb6385ed348ebccd65f83486 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Sep 2019 11:45:15 -0700 Subject: [PATCH 13/23] fix: share endpoint policies --- server/api/shares.js | 2 +- server/api/shares.test.js | 22 ++++++++++++++++++++++ server/policies/document.js | 36 +++++++++++++++++++++++++++++++----- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/server/api/shares.js b/server/api/shares.js index 1749635d0f..abb4f11404 100644 --- a/server/api/shares.js +++ b/server/api/shares.js @@ -60,7 +60,7 @@ router.post('shares.create', auth(), async ctx => { ctx.assertPresent(documentId, 'documentId is required'); const user = ctx.state.user; - const document = await Document.findByPk(documentId); + const document = await Document.findByPk(documentId, { userId: user.id }); const team = await Team.findByPk(user.teamId); authorize(user, 'share', document); authorize(user, 'share', team); diff --git a/server/api/shares.test.js b/server/api/shares.test.js index 0a84be4930..0cbba77373 100644 --- a/server/api/shares.test.js +++ b/server/api/shares.test.js @@ -1,6 +1,7 @@ /* eslint-disable flowtype/require-valid-file-annotation */ import TestServer from 'fetch-test-server'; import app from '../app'; +import { CollectionUser } from '../models'; import { flushdb, seed } from '../test/support'; import { buildUser, buildShare } from '../test/factories'; @@ -110,6 +111,27 @@ describe('#shares.create', async () => { expect(body.data.documentTitle).toBe(document.title); }); + it('should allow creating a share record for document in read-only collection', async () => { + const { user, document, collection } = await seed(); + collection.private = true; + await collection.save(); + + await CollectionUser.create({ + createdById: user.id, + collectionId: collection.id, + userId: user.id, + permission: 'read', + }); + + const res = await server.post('/api/shares.create', { + body: { token: user.getJwtToken(), documentId: document.id }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.documentTitle).toBe(document.title); + }); + it('should allow creating a share record if link previously revoked', async () => { const { user, document } = await seed(); const share = await buildShare({ diff --git a/server/policies/document.js b/server/policies/document.js index 49685aee7c..7da610e706 100644 --- a/server/policies/document.js +++ b/server/policies/document.js @@ -7,7 +7,7 @@ const { allow, cannot } = policy; allow(User, 'create', Document); -allow(User, ['read', 'share'], Document, (user, document) => { +allow(User, ['read', 'download'], Document, (user, document) => { // existance of collection option is not required here to account for share tokens if (document.collection && cannot(user, 'read', document.collection)) { return false; @@ -16,9 +16,23 @@ allow(User, ['read', 'share'], Document, (user, document) => { return user.teamId === document.teamId; }); -// 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) => { +allow( + User, + ['share', 'pin', 'unpin', 'star', 'unstar'], + Document, + (user, document) => { + if (document.archivedAt) return false; + + // existance of collection option is not required here to account for share tokens + if (document.collection && cannot(user, 'read', document.collection)) { + return false; + } + + return user.teamId === document.teamId; + } +); + +allow(User, 'update', Document, (user, document) => { invariant( document.collection, 'collection is missing, did you forget to include in the query scope?' @@ -29,7 +43,19 @@ allow(User, ['update', 'move'], Document, (user, document) => { return user.teamId === document.teamId; }); -allow(User, ['delete'], Document, (user, document) => { +allow(User, 'move', Document, (user, document) => { + invariant( + document.collection, + 'collection is missing, did you forget to include in the query scope?' + ); + if (cannot(user, 'update', document.collection)) return false; + if (document.archivedAt) return false; + if (!document.publishedAt) return false; + + return user.teamId === document.teamId; +}); + +allow(User, 'delete', Document, (user, document) => { // allow deleting document without a collection if (document.collection && cannot(user, 'update', document.collection)) return false; From a2145ae3f059623bee50018f31e264094fa274c1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Sep 2019 15:55:07 -0700 Subject: [PATCH 14/23] chore: Use policies to drive documents UI --- .../DropdownMenu/DropdownMenuItem.js | 14 +++++-- app/components/Sidebar/Main.js | 2 +- app/components/Sidebar/Settings.js | 2 +- .../Sidebar/components/Collections.js | 7 +++- app/menus/CollectionMenu.js | 20 ++++++---- app/menus/DocumentMenu.js | 2 +- app/menus/NewDocumentMenu.js | 37 +++++++++++-------- app/scenes/Collection.js | 36 +++++++++++------- app/scenes/Document/Document.js | 4 +- app/scenes/Document/components/Header.js | 2 +- app/stores/PoliciesStore.js | 2 +- 11 files changed, 80 insertions(+), 48 deletions(-) diff --git a/app/components/DropdownMenu/DropdownMenuItem.js b/app/components/DropdownMenu/DropdownMenuItem.js index 0ea5e5a541..fa694db48a 100644 --- a/app/components/DropdownMenu/DropdownMenuItem.js +++ b/app/components/DropdownMenu/DropdownMenuItem.js @@ -8,9 +8,13 @@ type Props = { disabled?: boolean, }; -const DropdownMenuItem = ({ onClick, children, ...rest }: Props) => { +const DropdownMenuItem = ({ onClick, children, disabled, ...rest }: Props) => { return ( - + {children} ); @@ -33,9 +37,13 @@ const MenuItem = styled.a` margin-right: 8px; } + svg { + opacity: ${props => (props.disabled ? '.5' : 1)}; + } + ${props => props.disabled - ? '' + ? 'pointer-events: none;' : ` &:hover { diff --git a/app/components/Sidebar/Main.js b/app/components/Sidebar/Main.js index 30256adf9d..22020cebcf 100644 --- a/app/components/Sidebar/Main.js +++ b/app/components/Sidebar/Main.js @@ -62,7 +62,7 @@ class MainSidebar extends React.Component { if (!user || !team) return null; const draftDocumentsCount = documents.drafts.length; - const can = policies.abilties(team.id); + const can = policies.abilities(team.id); return ( diff --git a/app/components/Sidebar/Settings.js b/app/components/Sidebar/Settings.js index c3c687ad0a..81f6661dcb 100644 --- a/app/components/Sidebar/Settings.js +++ b/app/components/Sidebar/Settings.js @@ -43,7 +43,7 @@ class SettingsSidebar extends React.Component { const { team } = auth; if (!team) return null; - const can = policies.abilties(team.id); + const can = policies.abilities(team.id); return ( diff --git a/app/components/Sidebar/components/Collections.js b/app/components/Sidebar/components/Collections.js index 1b01def476..254e7d6284 100644 --- a/app/components/Sidebar/components/Collections.js +++ b/app/components/Sidebar/components/Collections.js @@ -13,11 +13,13 @@ import CollectionLink from './CollectionLink'; import Fade from 'components/Fade'; import CollectionsStore from 'stores/CollectionsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import UiStore from 'stores/UiStore'; import DocumentsStore from 'stores/DocumentsStore'; type Props = { history: RouterHistory, + policies: PoliciesStore, collections: CollectionsStore, documents: DocumentsStore, onCreateCollection: () => void, @@ -41,6 +43,9 @@ class Collections extends React.Component { const { activeCollectionId } = this.props.ui; if (!activeCollectionId) return; + const can = this.props.policies.abilities(activeCollectionId); + if (!can.update) return; + this.props.history.push(newDocumentUrl(activeCollectionId)); } @@ -75,6 +80,6 @@ class Collections extends React.Component { } } -export default inject('collections', 'ui', 'documents')( +export default inject('collections', 'ui', 'documents', 'policies')( withRouter(Collections) ); diff --git a/app/menus/CollectionMenu.js b/app/menus/CollectionMenu.js index 2597b6d92d..8a827cdf76 100644 --- a/app/menus/CollectionMenu.js +++ b/app/menus/CollectionMenu.js @@ -90,7 +90,7 @@ class CollectionMenu extends React.Component { render() { const { policies, collection, position, onOpen, onClose } = this.props; - const can = policies.abilties(collection.id); + const can = policies.abilities(collection.id); return ( @@ -114,13 +114,17 @@ class CollectionMenu extends React.Component { {collection && ( - - New document - - - Import document - - {(can.update || can.export) &&
} + {can.update && ( + + New document + + )} + {can.update && ( + + Import document + + )} + {can.update &&
} {can.update && ( Edit… )} diff --git a/app/menus/DocumentMenu.js b/app/menus/DocumentMenu.js index 550be5e807..f37eed36b1 100644 --- a/app/menus/DocumentMenu.js +++ b/app/menus/DocumentMenu.js @@ -122,7 +122,7 @@ class DocumentMenu extends React.Component { onClose, } = this.props; - const can = policies.abilties(document.id); + const can = policies.abilities(document.id); const canShareDocuments = can.share && auth.team && auth.team.sharing; return ( diff --git a/app/menus/NewDocumentMenu.js b/app/menus/NewDocumentMenu.js index a8100cb3f7..abc1536634 100644 --- a/app/menus/NewDocumentMenu.js +++ b/app/menus/NewDocumentMenu.js @@ -7,12 +7,14 @@ import { PlusIcon, CollectionIcon, PrivateCollectionIcon } from 'outline-icons'; import { newDocumentUrl } from 'utils/routeHelpers'; import CollectionsStore from 'stores/CollectionsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import { DropdownMenu, DropdownMenuItem } from 'components/DropdownMenu'; import Button from 'components/Button'; type Props = { label?: React.Node, collections: CollectionsStore, + policies: PoliciesStore, }; @observer @@ -38,7 +40,7 @@ class NewDocumentMenu extends React.Component { render() { if (this.redirectTo) return ; - const { collections, label, ...rest } = this.props; + const { collections, policies, label, ...rest } = this.props; return ( { {...rest} > Choose a collection… - {collections.orderedData.map(collection => ( - this.handleNewDocument(collection.id)} - > - {collection.private ? ( - - ) : ( - - )}{' '} - {collection.name} - - ))} + {collections.orderedData.map(collection => { + const can = policies.abilities(collection.id); + + return ( + this.handleNewDocument(collection.id)} + disabled={!can.update} + > + {collection.private ? ( + + ) : ( + + )}{' '} + {collection.name} + + ); + })} ); } } -export default inject('collections')(NewDocumentMenu); +export default inject('collections', 'policies')(NewDocumentMenu); diff --git a/app/scenes/Collection.js b/app/scenes/Collection.js index 5c80812f0c..b215c24148 100644 --- a/app/scenes/Collection.js +++ b/app/scenes/Collection.js @@ -17,6 +17,7 @@ import RichMarkdownEditor from 'rich-markdown-editor'; import { newDocumentUrl, collectionUrl } from 'utils/routeHelpers'; import CollectionsStore from 'stores/CollectionsStore'; import DocumentsStore from 'stores/DocumentsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import UiStore from 'stores/UiStore'; import Collection from 'models/Collection'; @@ -45,6 +46,7 @@ type Props = { ui: UiStore, documents: DocumentsStore, collections: CollectionsStore, + policies: PoliciesStore, match: Object, theme: Object, }; @@ -112,21 +114,27 @@ class CollectionScene extends React.Component { }; renderActions() { + const can = this.props.policies.abilities(this.props.match.params.id); + return ( - - - - - - + {can.update && ( + + + + + + + + + )} @@ -325,6 +333,6 @@ const Wrapper = styled(Flex)` margin: 10px 0; `; -export default inject('collections', 'documents', 'ui')( +export default inject('collections', 'policies', 'documents', 'ui')( withTheme(CollectionScene) ); diff --git a/app/scenes/Document/Document.js b/app/scenes/Document/Document.js index 2cad8767e0..8963d3c124 100644 --- a/app/scenes/Document/Document.js +++ b/app/scenes/Document/Document.js @@ -107,7 +107,7 @@ class DocumentScene extends React.Component { const document = this.document; if (!document) return; - const can = this.props.policies.abilties(document.id); + const can = this.props.policies.abilities(document.id); if (can.update) { this.props.history.push(documentMoveUrl(document)); @@ -120,7 +120,7 @@ class DocumentScene extends React.Component { const document = this.document; if (!document) return; - const can = this.props.policies.abilties(document.id); + const can = this.props.policies.abilities(document.id); if (can.update) { this.props.history.push(documentEditUrl(document)); diff --git a/app/scenes/Document/components/Header.js b/app/scenes/Document/components/Header.js index 580d2fbcab..91350d0e8f 100644 --- a/app/scenes/Document/components/Header.js +++ b/app/scenes/Document/components/Header.js @@ -108,7 +108,7 @@ class Header extends React.Component { auth, } = this.props; - const can = policies.abilties(document.id); + const can = policies.abilities(document.id); const canShareDocuments = auth.team && auth.team.sharing && can.share; const canToggleEmbeds = auth.team && auth.team.documentEmbeds; const canEdit = can.update && !isEditing; diff --git a/app/stores/PoliciesStore.js b/app/stores/PoliciesStore.js index 831a4389dd..3dc2eee61b 100644 --- a/app/stores/PoliciesStore.js +++ b/app/stores/PoliciesStore.js @@ -10,7 +10,7 @@ export default class PoliciesStore extends BaseStore { super(rootStore, Policy); } - abilties(id: string) { + abilities(id: string) { const policy = this.get(id); return policy ? policy.abilities : {}; } From 4d4341d89624c81b027c4f401a9b0aafe19a0c0d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 9 Sep 2019 21:02:21 -0700 Subject: [PATCH 15/23] alignment --- app/scenes/Document/components/Header.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/scenes/Document/components/Header.js b/app/scenes/Document/components/Header.js index 91350d0e8f..f644e00af7 100644 --- a/app/scenes/Document/components/Header.js +++ b/app/scenes/Document/components/Header.js @@ -275,6 +275,7 @@ const Actions = styled(Flex)` ? darken(0.05, props.theme.sidebarBackground) : 'transparent'}; padding: 12px; + height: 32px; transition: all 100ms ease-out; transform: translate3d(0, 0, 0); -webkit-backdrop-filter: blur(20px); From 439ae1e83271882cf83a95e2e4e100dfd1a94b29 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 14:41:34 -0700 Subject: [PATCH 16/23] fix: CSP for client-side editor uploads --- server/app.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/server/app.js b/server/app.js index db97b5059f..19c58ab6a4 100644 --- a/server/app.js +++ b/server/app.js @@ -122,6 +122,11 @@ app.use( styleSrc: ["'self'", "'unsafe-inline'", 'github.githubassets.com'], imgSrc: ['*', 'data:', 'blob:'], frameSrc: ['*'], + connectSrc: [ + "'self'", + process.env.AWS_S3_UPLOAD_BUCKET_URL, + 'www.google-analytics.com', + ], }, }) ); From e2453b5b2aca6c0b7743d0c426204b4c2f78ae32 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 14:42:32 -0700 Subject: [PATCH 17/23] fix: Editor headings offset --- app/components/Editor/Editor.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/components/Editor/Editor.js b/app/components/Editor/Editor.js index 4fa087693c..517a3073c2 100644 --- a/app/components/Editor/Editor.js +++ b/app/components/Editor/Editor.js @@ -91,6 +91,7 @@ class Editor extends React.Component { onShowToast={this.onShowToast} getLinkComponent={this.getLinkComponent} tooltip={EditorTooltip} + headingsOffset={1} {...this.props} />
From f43643f43bf93e85b7cc5e66c13b28aae40cba9b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 14:53:27 -0700 Subject: [PATCH 18/23] fix: Image and horizontal highlight on selected --- app/components/Editor/Embed.js | 2 +- shared/styles/theme.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/components/Editor/Embed.js b/app/components/Editor/Embed.js index d4c227b95d..2e4bb72994 100644 --- a/app/components/Editor/Embed.js +++ b/app/components/Editor/Embed.js @@ -49,5 +49,5 @@ const Container = styled.div` border-radius: 3px; box-shadow: ${props => - props.isSelected ? `0 0 0 2px ${props.theme.primary}` : 'none'}; + props.isSelected ? `0 0 0 2px ${props.theme.selected}` : 'none'}; `; diff --git a/shared/styles/theme.js b/shared/styles/theme.js index ee22f0b1ae..7945586f27 100644 --- a/shared/styles/theme.js +++ b/shared/styles/theme.js @@ -49,6 +49,7 @@ export const base = { backgroundTransition: 'background 100ms ease-in-out', zIndex: 100, + selected: colors.primary, buttonBackground: colors.primary, buttonText: colors.white, }; From a9d46b8e3fe36d63eee1f8fadfc8de5d95cc1213 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 15:40:17 -0700 Subject: [PATCH 19/23] fix: Header height --- app/scenes/Document/components/Header.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/scenes/Document/components/Header.js b/app/scenes/Document/components/Header.js index f644e00af7..fd22c2a2ef 100644 --- a/app/scenes/Document/components/Header.js +++ b/app/scenes/Document/components/Header.js @@ -256,6 +256,7 @@ const Status = styled.div` const Wrapper = styled(Flex)` width: 100%; align-self: flex-end; + height: 32px; ${breakpoint('tablet')` width: 33.3%; @@ -275,7 +276,6 @@ const Actions = styled(Flex)` ? darken(0.05, props.theme.sidebarBackground) : 'transparent'}; padding: 12px; - height: 32px; transition: all 100ms ease-out; transform: translate3d(0, 0, 0); -webkit-backdrop-filter: blur(20px); From c3ac25e648b67185200101e3c1138b1d6e6ed0e3 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 20:09:12 -0700 Subject: [PATCH 20/23] fix: Correct behavior when collection becomes private --- app/components/SocketProvider.js | 39 +++++++++++++++++++------- app/stores/BaseStore.js | 5 ++++ server/services/websockets.js | 47 ++++++++++++++++++++++++++++---- 3 files changed, 76 insertions(+), 15 deletions(-) diff --git a/app/components/SocketProvider.js b/app/components/SocketProvider.js index 1e4ba6090d..ce6d68fb61 100644 --- a/app/components/SocketProvider.js +++ b/app/components/SocketProvider.js @@ -66,34 +66,53 @@ class SocketProvider extends React.Component { } }); } + if (event.collections) { event.collections.forEach(collection => { - const previous = collections.get(collection.id); - const previousPrivate = previous ? previous.private : undefined; - if (collection.deletedAt) { collections.remove(collection.id); documents.removeCollectionDocuments(collection.id); } else { collections.add(collection); } - - // If the collection changed privacy then we need to reload associated - // memberships and policies to reflect any new permissions - if (previous && previousPrivate !== collection.private) { - collections.fetch(collection.id, { force: true }); - memberships.removeCollectionMemberships(collection.id); - } }); } }); + this.socket.on('documents.star', event => { documents.starredIds.set(event.documentId, true); }); + this.socket.on('documents.unstar', event => { documents.starredIds.set(event.documentId, false); }); + this.socket.on('collections.update', event => { + const previous = collections.get(event.collectionId); + const previousPrivate = previous ? previous.private : undefined; + + if (previousPrivate !== event.private) { + collections.fetch(event.collectionId, { force: true }); + memberships.removeCollectionMemberships(event.collectionId); + } + }); + + this.socket.on('collections.add_user', event => { + if (auth.user && event.userId === auth.user.id) { + collections.fetch(event.collectionId, { force: true }); + } + }); + + this.socket.on('collections.remove_user', event => { + if (auth.user && event.userId === auth.user.id) { + collections.remove(event.collectionId); + memberships.removeCollectionMemberships(event.collectionId); + documents.removeCollectionDocuments(event.collectionId); + } else { + memberships.remove(`${event.userId}-${event.collectionId}`); + } + }); + // received a message from the API server that we should request // to join a specific room. Forward that to the ws server. this.socket.on('join', event => { diff --git a/app/stores/BaseStore.js b/app/stores/BaseStore.js index 31e7d1d371..e4cf73a71b 100644 --- a/app/stores/BaseStore.js +++ b/app/stores/BaseStore.js @@ -145,6 +145,11 @@ export default class BaseStore { this.addPolicies(res.policies); return this.add(res.data); + } catch (err) { + if (err.statusCode === 403) { + return this.remove(id); + } + throw err; } finally { this.isFetching = false; } diff --git a/server/services/websockets.js b/server/services/websockets.js index 87081afb13..c0f2bd12c3 100644 --- a/server/services/websockets.js +++ b/server/services/websockets.js @@ -111,22 +111,59 @@ export default class Websockets { }); const collections = [await presentCollection(collection)]; - return socketio.to(`collection-${collection.id}`).emit('entities', { + socketio.to(`team-${collection.teamId}`).emit(event.name, { event: event.name, - collections, + collectionId: event.collectionId, + privacy: collection.privacy, }); + + return socketio + .to( + collection.private + ? `collection-${collection.id}` + : `team-${collection.teamId}` + ) + .emit('entities', { + event: event.name, + collections, + }); } - case 'collections.add_user': + case 'collections.add_user': { + // the user being added isn't yet in the websocket channel for the collection + // so they need to be notified separately + socketio.to(`user-${event.userId}`).emit(event.name, { + event: event.name, + userId: event.userId, + collectionId: event.collectionId, + }); + + // let everyone with access to the collection know a user was added + socketio.to(`collection-${event.collectionId}`).emit(event.name, { + event: event.name, + userId: event.userId, + collectionId: event.collectionId, + }); + + // tell any user clients to connect to the websocket channel for the collection return socketio.to(`user-${event.userId}`).emit('join', { event: event.name, roomId: event.collectionId, }); - case 'collections.remove_user': + } + case 'collections.remove_user': { + // let everyone with access to the collection know a user was removed + socketio.to(`collection-${event.collectionId}`).emit(event.name, { + event: event.name, + userId: event.userId, + collectionId: event.collectionId, + }); + + // tell any user clients to disconnect from the websocket channel for the collection return socketio.to(`user-${event.userId}`).emit('leave', { event: event.name, roomId: event.collectionId, }); - + } default: } } From 45b31232e102eae34d6b036581954545a82ab8f7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 20:33:34 -0700 Subject: [PATCH 21/23] fix: Header height for read-only collection --- app/components/Actions.js | 1 + 1 file changed, 1 insertion(+) diff --git a/app/components/Actions.js b/app/components/Actions.js index f2c57f45bc..ccb5a86891 100644 --- a/app/components/Actions.js +++ b/app/components/Actions.js @@ -7,6 +7,7 @@ export const Action = styled(Flex)` justify-content: center; align-items: center; padding: 0 0 0 12px; + height: 32px; font-size: 15px; flex-shrink: 0; From b624a00b83e427f445c0bdd2e770e407a11e3a9a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 15 Sep 2019 23:32:16 -0700 Subject: [PATCH 22/23] send id's over socket instead of serialized objects --- app/components/Editor/Editor.js | 1 - app/components/SocketProvider.js | 51 ++++++++----------- .../CollectionMembers/CollectionMembers.js | 4 +- app/stores/BaseStore.js | 2 +- server/services/websockets.js | 51 +++++-------------- 5 files changed, 37 insertions(+), 72 deletions(-) diff --git a/app/components/Editor/Editor.js b/app/components/Editor/Editor.js index 517a3073c2..4fa087693c 100644 --- a/app/components/Editor/Editor.js +++ b/app/components/Editor/Editor.js @@ -91,7 +91,6 @@ class Editor extends React.Component { onShowToast={this.onShowToast} getLinkComponent={this.getLinkComponent} tooltip={EditorTooltip} - headingsOffset={1} {...this.props} />
diff --git a/app/components/SocketProvider.js b/app/components/SocketProvider.js index ce6d68fb61..3b53ce7f55 100644 --- a/app/components/SocketProvider.js +++ b/app/components/SocketProvider.js @@ -36,27 +36,25 @@ class SocketProvider extends React.Component { this.socket.emit('authentication', { token: auth.token, }); + this.socket.on('unauthorized', err => { ui.showToast(err.message); throw err; }); - this.socket.on('entities', event => { - if (event.documents) { - event.documents.forEach(doc => { - if (doc.deletedAt) { - documents.remove(doc.id); - } else { - documents.add(doc); - } + + this.socket.on('entities', async event => { + if (event.documentIds) { + for (const documentId of event.documentIds) { + const document = await documents.fetch(documentId); // TODO: Move this to the document scene once data loading // has been refactored to be friendlier there. if ( auth.user && - doc.id === ui.activeDocumentId && - doc.updatedBy.id !== auth.user.id + documentId === ui.activeDocumentId && + document.updatedBy.id !== auth.user.id ) { - ui.showToast(`Document updated by ${doc.updatedBy.name}`, { + ui.showToast(`Document updated by ${document.updatedBy.name}`, { timeout: 30 * 1000, action: { text: 'Refresh', @@ -64,18 +62,21 @@ class SocketProvider extends React.Component { }, }); } - }); + } } - if (event.collections) { - event.collections.forEach(collection => { - if (collection.deletedAt) { - collections.remove(collection.id); - documents.removeCollectionDocuments(collection.id); - } else { - collections.add(collection); + if (event.collectionIds) { + for (const collectionId of event.collectionIds) { + try { + await collections.fetch(collectionId, { force: true }); + } catch (err) { + if (err.statusCode === 404 || err.statusCode === 403) { + collections.remove(collectionId); + documents.removeCollectionDocuments(collectionId); + memberships.removeCollectionMemberships(collectionId); + } } - }); + } } }); @@ -87,16 +88,6 @@ class SocketProvider extends React.Component { documents.starredIds.set(event.documentId, false); }); - this.socket.on('collections.update', event => { - const previous = collections.get(event.collectionId); - const previousPrivate = previous ? previous.private : undefined; - - if (previousPrivate !== event.private) { - collections.fetch(event.collectionId, { force: true }); - memberships.removeCollectionMemberships(event.collectionId); - } - }); - this.socket.on('collections.add_user', event => { if (auth.user && event.userId === auth.user.id) { collections.fetch(event.collectionId, { force: true }); diff --git a/app/scenes/CollectionMembers/CollectionMembers.js b/app/scenes/CollectionMembers/CollectionMembers.js index 73904d6ddb..9bee7037c3 100644 --- a/app/scenes/CollectionMembers/CollectionMembers.js +++ b/app/scenes/CollectionMembers/CollectionMembers.js @@ -68,6 +68,8 @@ class CollectionMembers extends React.Component { const { user } = auth; if (!user) return null; + const key = memberships.orderedData.map(m => m.permission).join('-'); + return ( {collection.private ? ( @@ -104,7 +106,7 @@ class CollectionMembers extends React.Component { Members { return this.add(res.data); } catch (err) { if (err.statusCode === 403) { - return this.remove(id); + this.remove(id); } throw err; } finally { diff --git a/server/services/websockets.js b/server/services/websockets.js index c0f2bd12c3..3d217a8d70 100644 --- a/server/services/websockets.js +++ b/server/services/websockets.js @@ -1,7 +1,6 @@ // @flow import type { Event } from '../events'; import { Document, Collection } from '../models'; -import { presentDocument, presentCollection } from '../presenters'; import { socketio } from '../'; export default class Websockets { @@ -20,26 +19,22 @@ export default class Websockets { const document = await Document.findByPk(event.documentId, { paranoid: false, }); - const documents = [await presentDocument(document)]; - const collections = [await presentCollection(document.collection)]; return socketio .to(`collection-${document.collectionId}`) .emit('entities', { event: event.name, - documents, - collections, + documentIds: [event.documentId], + collectionIds: [document.collectionId], }); } case 'documents.create': { const document = await Document.findByPk(event.documentId); - const documents = [await presentDocument(document)]; - const collections = [await presentCollection(document.collection)]; return socketio.to(`user-${event.actorId}`).emit('entities', { event: event.name, - documents, - collections, + documentIds: [event.documentId], + collectionIds: [document.collectionId], }); } case 'documents.star': @@ -55,24 +50,16 @@ export default class Websockets { }, paranoid: false, }); - const collections = await Collection.findAll({ - where: { - id: event.data.collectionIds, - }, - paranoid: false, - }); - documents.forEach(async document => { - const documents = [await presentDocument(document)]; + documents.forEach(document => { socketio.to(`collection-${document.collectionId}`).emit('entities', { event: event.name, - documents, + documentIds: [document.id], }); }); - collections.forEach(async collection => { - const collections = [await presentCollection(collection)]; - socketio.to(`collection-${collection.id}`).emit('entities', { + event.data.collectionIds.forEach(collectionId => { + socketio.to(`collection-${collectionId}`).emit('entities', { event: event.name, - collections, + collectionIds: [collectionId], }); }); return; @@ -81,7 +68,6 @@ export default class Websockets { const collection = await Collection.findByPk(event.collectionId, { paranoid: false, }); - const collections = [await presentCollection(collection)]; socketio .to( @@ -91,7 +77,7 @@ export default class Websockets { ) .emit('entities', { event: event.name, - collections, + collectionIds: [event.collectionId], }); return socketio .to( @@ -109,24 +95,11 @@ export default class Websockets { const collection = await Collection.findByPk(event.collectionId, { paranoid: false, }); - const collections = [await presentCollection(collection)]; - socketio.to(`team-${collection.teamId}`).emit(event.name, { + return socketio.to(`team-${collection.teamId}`).emit('entities', { event: event.name, - collectionId: event.collectionId, - privacy: collection.privacy, + collectionIds: [event.collectionId], }); - - return socketio - .to( - collection.private - ? `collection-${collection.id}` - : `team-${collection.teamId}` - ) - .emit('entities', { - event: event.name, - collections, - }); } case 'collections.add_user': { // the user being added isn't yet in the websocket channel for the collection From 3f16823f7bf0d1004165d8e5b6d085c98f162f44 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 21 Sep 2019 12:10:49 -0700 Subject: [PATCH 23/23] fix: Remote policy change --- app/components/SocketProvider.js | 27 +++++++++++++++++++++++---- app/scenes/Document/Document.js | 13 +++++++++++++ app/stores/DocumentsStore.js | 5 ++++- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app/components/SocketProvider.js b/app/components/SocketProvider.js index 3b53ce7f55..5c9d067ecc 100644 --- a/app/components/SocketProvider.js +++ b/app/components/SocketProvider.js @@ -5,6 +5,7 @@ import io from 'socket.io-client'; import DocumentsStore from 'stores/DocumentsStore'; import CollectionsStore from 'stores/CollectionsStore'; import MembershipsStore from 'stores/MembershipsStore'; +import PoliciesStore from 'stores/PoliciesStore'; import AuthStore from 'stores/AuthStore'; import UiStore from 'stores/UiStore'; @@ -15,6 +16,7 @@ type Props = { documents: DocumentsStore, collections: CollectionsStore, memberships: MembershipsStore, + policies: PoliciesStore, auth: AuthStore, ui: UiStore, }; @@ -29,7 +31,14 @@ class SocketProvider extends React.Component { path: '/realtime', }); - const { auth, ui, documents, collections, memberships } = this.props; + const { + auth, + ui, + documents, + collections, + memberships, + policies, + } = this.props; if (!auth.token) return; this.socket.on('connect', () => { @@ -92,6 +101,11 @@ class SocketProvider extends React.Component { if (auth.user && event.userId === auth.user.id) { collections.fetch(event.collectionId, { force: true }); } + + // Document policies might need updating as the permission changes + documents.inCollection(event.collectionId).forEach(document => { + policies.remove(document.id); + }); }); this.socket.on('collections.remove_user', event => { @@ -127,6 +141,11 @@ class SocketProvider extends React.Component { } } -export default inject('auth', 'ui', 'documents', 'collections', 'memberships')( - SocketProvider -); +export default inject( + 'auth', + 'ui', + 'documents', + 'collections', + 'memberships', + 'policies' +)(SocketProvider); diff --git a/app/scenes/Document/Document.js b/app/scenes/Document/Document.js index 8963d3c124..2149a26741 100644 --- a/app/scenes/Document/Document.js +++ b/app/scenes/Document/Document.js @@ -93,6 +93,16 @@ class DocumentScene extends React.Component { this.loadEditor(); } + componentDidUpdate() { + if (this.document) { + const policy = this.props.policies.get(this.document.id); + + if (!policy) { + this.loadDocument(this.props); + } + } + } + componentWillUnmount() { clearTimeout(this.viewTimeout); } @@ -345,6 +355,9 @@ class DocumentScene extends React.Component { const embedsDisabled = team && !team.documentEmbeds; + // this line is only here to make MobX understand that policies are a dependency of this component + this.props.policies.abilities(document.id); + return ( { try { const doc: ?Document = this.data.get(id) || this.getByUrl(id); - if (doc) return doc; + const policy = doc ? this.rootStore.policies.get(doc.id) : undefined; + if (doc && policy) { + return doc; + } const res = await client.post('/documents.info', { id,