Merge pull request #1034 from outline/maintainers

WIP: Read-only Memberships
This commit is contained in:
Tom Moor authored and GitHub committed 2019-09-23 23:02:07 -07:00
commit 097b4b4770
44 files changed
+1205 -346

No files matched your search

+1
View File
@@ -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;
@@ -8,9 +8,13 @@ type Props = {
disabled?: boolean,
};
const DropdownMenuItem = ({ onClick, children, ...rest }: Props) => {
const DropdownMenuItem = ({ onClick, children, disabled, ...rest }: Props) => {
return (
<MenuItem onClick={onClick} {...rest}>
<MenuItem
onClick={disabled ? undefined : onClick}
disabled={disabled}
{...rest}
>
{children}
</MenuItem>
);
@@ -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 {
+1 -1
View File
@@ -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'};
`;
+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;
+1 -1
View File
@@ -62,7 +62,7 @@ class MainSidebar extends React.Component<Props> {
if (!user || !team) return null;
const draftDocumentsCount = documents.drafts.length;
const can = policies.abilties(team.id);
const can = policies.abilities(team.id);
return (
<Sidebar>
+1 -1
View File
@@ -43,7 +43,7 @@ class SettingsSidebar extends React.Component<Props> {
const { team } = auth;
if (!team) return null;
const can = policies.abilties(team.id);
const can = policies.abilities(team.id);
return (
<Sidebar>
@@ -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<Props> {
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<Props> {
}
}
export default inject('collections', 'ui', 'documents')(
export default inject('collections', 'ui', 'documents', 'policies')(
withRouter(Collections)
);
+65 -22
View File
@@ -4,6 +4,8 @@ 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 PoliciesStore from 'stores/PoliciesStore';
import AuthStore from 'stores/AuthStore';
import UiStore from 'stores/UiStore';
@@ -13,6 +15,8 @@ type Props = {
children: React.Node,
documents: DocumentsStore,
collections: CollectionsStore,
memberships: MembershipsStore,
policies: PoliciesStore,
auth: AuthStore,
ui: UiStore,
};
@@ -27,34 +31,39 @@ class SocketProvider extends React.Component<Props> {
path: '/realtime',
});
const { auth, ui, documents, collections } = this.props;
const {
auth,
ui,
documents,
collections,
memberships,
policies,
} = this.props;
if (!auth.token) return;
this.socket.on('connect', () => {
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',
@@ -62,26 +71,53 @@ class SocketProvider extends React.Component<Props> {
},
});
}
});
}
}
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);
}
}
});
}
}
});
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.add_user', event => {
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 => {
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 => {
@@ -105,4 +141,11 @@ class SocketProvider extends React.Component<Props> {
}
}
export default inject('auth', 'ui', 'documents', 'collections')(SocketProvider);
export default inject(
'auth',
'ui',
'documents',
'collections',
'memberships',
'policies'
)(SocketProvider);
+12 -8
View File
@@ -90,7 +90,7 @@ class CollectionMenu extends React.Component<Props> {
render() {
const { policies, collection, position, onOpen, onClose } = this.props;
const can = policies.abilties(collection.id);
const can = policies.abilities(collection.id);
return (
<React.Fragment>
@@ -114,13 +114,17 @@ class CollectionMenu extends React.Component<Props> {
<DropdownMenu onOpen={onOpen} onClose={onClose} position={position}>
{collection && (
<React.Fragment>
<DropdownMenuItem onClick={this.onNewDocument}>
New document
</DropdownMenuItem>
<DropdownMenuItem onClick={this.onImportDocument}>
Import document
</DropdownMenuItem>
{(can.update || can.export) && <hr />}
{can.update && (
<DropdownMenuItem onClick={this.onNewDocument}>
New document
</DropdownMenuItem>
)}
{can.update && (
<DropdownMenuItem onClick={this.onImportDocument}>
Import document
</DropdownMenuItem>
)}
{can.update && <hr />}
{can.update && (
<DropdownMenuItem onClick={this.onEdit}>Edit…</DropdownMenuItem>
)}
+67 -68
View File
@@ -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<Props> {
if (this.redirectTo) return <Redirect to={this.redirectTo} push />;
const {
policies,
document,
position,
className,
@@ -118,20 +121,9 @@ class DocumentMenu extends React.Component<Props> {
onOpen,
onClose,
} = this.props;
const canShareDocuments = auth.team && auth.team.sharing;
if (document.isArchived) {
return (
<DropdownMenu className={className}>
<DropdownMenuItem onClick={this.handleRestore}>
Restore
</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleDelete}>
Delete…
</DropdownMenuItem>
</DropdownMenu>
);
}
const can = policies.abilities(document.id);
const canShareDocuments = can.share && auth.team && auth.team.sharing;
return (
<DropdownMenu
@@ -140,76 +132,83 @@ class DocumentMenu extends React.Component<Props> {
onOpen={onOpen}
onClose={onClose}
>
{!document.isDraft ? (
<React.Fragment>
{showPin &&
(document.pinned ? (
{can.unarchive && (
<DropdownMenuItem onClick={this.handleRestore}>
Restore
</DropdownMenuItem>
)}
{showPin &&
(document.pinned
? can.unpin && (
<DropdownMenuItem onClick={this.handleUnpin}>
Unpin
</DropdownMenuItem>
) : (
)
: can.pin && (
<DropdownMenuItem onClick={this.handlePin}>
Pin to collection
</DropdownMenuItem>
))}
{document.isStarred ? (
{document.isStarred
? can.unstar && (
<DropdownMenuItem onClick={this.handleUnstar}>
Unstar
</DropdownMenuItem>
) : (
)
: can.star && (
<DropdownMenuItem onClick={this.handleStar}>
Star
</DropdownMenuItem>
)}
{canShareDocuments && (
<DropdownMenuItem
onClick={this.handleShareLink}
title="Create a public share link"
>
Share link…
</DropdownMenuItem>
)}
<hr />
<DropdownMenuItem onClick={this.handleDocumentHistory}>
Document history
</DropdownMenuItem>
<DropdownMenuItem
onClick={this.handleNewChild}
title="Create a new child document for the current document"
>
New child document
</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleEdit}>Edit</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleDuplicate}>
Duplicate
</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleArchive}>
Archive
</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleDelete}>
Delete…
</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleMove}>Move…</DropdownMenuItem>
</React.Fragment>
) : (
<React.Fragment>
{canShareDocuments && (
<DropdownMenuItem
onClick={this.handleShareLink}
title="Create a public share link"
>
Share link…
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={this.handleDelete}>
Delete…
</DropdownMenuItem>
</React.Fragment>
{canShareDocuments && (
<DropdownMenuItem
onClick={this.handleShareLink}
title="Create a public share link"
>
Share link…
</DropdownMenuItem>
)}
<hr />
<DropdownMenuItem onClick={this.handleExport}>
Download
</DropdownMenuItem>
{can.read && (
<DropdownMenuItem onClick={this.handleDocumentHistory}>
Document history
</DropdownMenuItem>
)}
{can.update && (
<DropdownMenuItem
onClick={this.handleNewChild}
title="Create a new child document for the current document"
>
New child document
</DropdownMenuItem>
)}
{can.update && (
<DropdownMenuItem onClick={this.handleEdit}>Edit</DropdownMenuItem>
)}
{can.update && (
<DropdownMenuItem onClick={this.handleDuplicate}>
Duplicate
</DropdownMenuItem>
)}
{can.archive && (
<DropdownMenuItem onClick={this.handleArchive}>
Archive
</DropdownMenuItem>
)}
{can.delete && (
<DropdownMenuItem onClick={this.handleDelete}>
Delete…
</DropdownMenuItem>
)}
{can.move && (
<DropdownMenuItem onClick={this.handleMove}>Move…</DropdownMenuItem>
)}
<hr />
{can.download && (
<DropdownMenuItem onClick={this.handleExport}>
Download
</DropdownMenuItem>
)}
{showPrint && (
<DropdownMenuItem onClick={window.print}>Print</DropdownMenuItem>
)}
@@ -218,4 +217,4 @@ class DocumentMenu extends React.Component<Props> {
}
}
export default inject('ui', 'auth', 'collections')(DocumentMenu);
export default inject('ui', 'auth', 'collections', 'policies')(DocumentMenu);
+22 -15
View File
@@ -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<Props> {
render() {
if (this.redirectTo) return <Redirect to={this.redirectTo} push />;
const { collections, label, ...rest } = this.props;
const { collections, policies, label, ...rest } = this.props;
return (
<DropdownMenu
@@ -53,22 +55,27 @@ class NewDocumentMenu extends React.Component<Props> {
{...rest}
>
<DropdownMenuItem disabled>Choose a collection…</DropdownMenuItem>
{collections.orderedData.map(collection => (
<DropdownMenuItem
key={collection.id}
onClick={() => this.handleNewDocument(collection.id)}
>
{collection.private ? (
<PrivateCollectionIcon color={collection.color} />
) : (
<CollectionIcon color={collection.color} />
)}{' '}
{collection.name}
</DropdownMenuItem>
))}
{collections.orderedData.map(collection => {
const can = policies.abilities(collection.id);
return (
<DropdownMenuItem
key={collection.id}
onClick={() => this.handleNewDocument(collection.id)}
disabled={!can.update}
>
{collection.private ? (
<PrivateCollectionIcon color={collection.color} />
) : (
<CollectionIcon color={collection.color} />
)}{' '}
{collection.name}
</DropdownMenuItem>
);
})}
</DropdownMenu>
);
}
}
export default inject('collections')(NewDocumentMenu);
export default inject('collections', 'policies')(NewDocumentMenu);
+23 -15
View File
@@ -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,
};
@@ -79,7 +81,7 @@ class CollectionScene extends React.Component<Props> {
this.collection = collection;
await this.props.documents.fetchPinned({
collection: id,
collectionId: id,
});
}
@@ -112,21 +114,27 @@ class CollectionScene extends React.Component<Props> {
};
renderActions() {
const can = this.props.policies.abilities(this.props.match.params.id);
return (
<Actions align="center" justify="flex-end">
<Action>
<Tooltip
tooltip="New document"
shortcut="n"
delay={500}
placement="bottom"
>
<Button onClick={this.onNewDocument} icon={<PlusIcon />}>
New doc
</Button>
</Tooltip>
</Action>
<Separator />
{can.update && (
<React.Fragment>
<Action>
<Tooltip
tooltip="New document"
shortcut="n"
delay={500}
placement="bottom"
>
<Button onClick={this.onNewDocument} icon={<PlusIcon />}>
New doc
</Button>
</Tooltip>
</Action>
<Separator />
</React.Fragment>
)}
<Action>
<CollectionMenu collection={this.collection} />
</Action>
@@ -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)
);
@@ -55,6 +55,7 @@ class AddPeopleToCollection extends React.Component<Props> {
this.props.memberships.create({
collectionId: this.props.collection.id,
userId: user.id,
permission: 'read_write',
});
this.props.ui.showToast(`${user.name} was added to the collection`);
} catch (err) {
@@ -50,11 +50,26 @@ 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;
if (!user) return null;
const key = memberships.orderedData.map(m => m.permission).join('-');
return (
<Flex column>
{collection.private ? (
@@ -91,7 +106,7 @@ class CollectionMembers extends React.Component<Props> {
<Subheading>Members</Subheading>
<PaginatedList
key={collection.private}
key={key}
items={
collection.private
? users.inCollection(collection.id)
@@ -103,8 +118,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 ? membership.permission : undefined}
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;
+28 -5
View File
@@ -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,
@@ -91,6 +93,16 @@ class DocumentScene extends React.Component<Props> {
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);
}
@@ -102,18 +114,26 @@ class DocumentScene extends React.Component<Props> {
@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.abilities(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.abilities(document.id);
if (can.update) {
this.props.history.push(documentEditUrl(document));
}
}
@@ -335,6 +355,9 @@ class DocumentScene extends React.Component<Props> {
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 (
<ErrorBoundary>
<Container
@@ -451,5 +474,5 @@ const LoadingState = styled(LoadingPlaceholder)`
`;
export default withRouter(
inject('ui', 'auth', 'documents', 'revisions')(DocumentScene)
inject('ui', 'auth', 'documents', 'policies', 'revisions')(DocumentScene)
);
+9 -4
View File
@@ -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<Props> {
const {
document,
policies,
isEditing,
isDraft,
isPublishing,
@@ -104,10 +107,11 @@ class Header extends React.Component<Props> {
publishingIsDisabled,
auth,
} = this.props;
const canShareDocuments =
auth.team && auth.team.sharing && !document.isArchived;
const can = policies.abilities(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 (
<Actions
@@ -252,6 +256,7 @@ const Status = styled.div`
const Wrapper = styled(Flex)`
width: 100%;
align-self: flex-end;
height: 32px;
${breakpoint('tablet')`
width: 33.3%;
@@ -305,4 +310,4 @@ const Title = styled.div`
`};
`;
export default inject('auth')(Header);
export default inject('auth', 'policies')(Header);
+5
View File
@@ -145,6 +145,11 @@ export default class BaseStore<T: BaseModel> {
this.addPolicies(res.policies);
return this.add(res.data);
} catch (err) {
if (err.statusCode === 403) {
this.remove(id);
}
throw err;
} finally {
this.isFetching = false;
}
+9 -4
View File
@@ -173,12 +173,12 @@ export default class DocumentsStore extends BaseStore<Document> {
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;
}
@@ -313,7 +313,10 @@ export default class DocumentsStore extends BaseStore<Document> {
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,
@@ -425,6 +428,7 @@ export default class DocumentsStore extends BaseStore<Document> {
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 +444,7 @@ export default class DocumentsStore extends BaseStore<Document> {
runInAction('Document#restore', () => {
invariant(res && res.data, 'Data should be available');
document.updateFromJson(res.data);
this.addPolicies(res.policies);
});
const collection = this.getCollectionForDocument(document);
+12
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');
@@ -67,4 +70,13 @@ export default class MembershipsStore extends BaseStore<Membership> {
this.remove(`${userId}-${collectionId}`);
}
@action
removeCollectionMemberships = (collectionId: string) => {
this.data.forEach((membership, key) => {
if (key.includes(collectionId)) {
this.remove(key);
}
});
};
}
+1 -1
View File
@@ -10,7 +10,7 @@ export default class PoliciesStore extends BaseStore<Policy> {
super(rootStore, Policy);
}
abilties(id: string) {
abilities(id: string) {
const policy = this.get(id);
return policy ? policy.abilities : {};
}
@@ -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",
+54 -27
View File
@@ -50,7 +50,7 @@ router.post('collections.create', auth(), async ctx => {
});
ctx.body = {
data: await presentCollection(collection),
data: presentCollection(collection),
policies: presentPolicies(user, [collection]),
};
});
@@ -60,11 +60,13 @@ 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 = {
data: await presentCollection(collection),
data: presentCollection(collection),
policies: presentPolicies(user, [collection]),
};
});
@@ -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);
@@ -149,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();
@@ -163,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,
@@ -216,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);
@@ -272,15 +287,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: {
@@ -294,6 +314,8 @@ router.post('collections.update', auth(), async ctx => {
});
}
const isPrivacyChanged = isPrivate !== collection.private;
collection.name = name;
collection.description = description;
collection.color = color;
@@ -309,8 +331,15 @@ 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
// 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),
@@ -320,9 +349,10 @@ 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,
@@ -332,15 +362,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),
};
});
@@ -349,7 +374,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();
+175 -3
View File
@@ -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,11 +62,13 @@ 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);
});
});
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,
@@ -77,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();
@@ -274,11 +297,14 @@ 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,
userId: user.id,
permission: 'read_write',
permission: 'read',
});
const res = await server.post('/api/collections.users', {
@@ -311,6 +337,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,
@@ -431,6 +460,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();
@@ -472,6 +522,128 @@ 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('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', {
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 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;
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');
@@ -490,7 +662,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 },
+53 -34
View File
@@ -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,
@@ -324,7 +337,10 @@ router.post('documents.info', auth({ required: false }), async ctx => {
}
document = share.document;
} else {
document = await Document.findByPk(id);
document = await Document.findByPk(
id,
user ? { userId: user.id } : undefined
);
authorize(user, 'read', document);
}
@@ -341,8 +357,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 = await Document.findByPk(id, { userId: user.id });
authorize(user, 'read', document);
const revision = await Revision.findOne({
where: {
@@ -361,9 +378,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 = await Document.findByPk(id, { userId: user.id });
authorize(user, 'read', document);
const revisions = await Revision.findAll({
where: { documentId: id },
@@ -383,7 +401,7 @@ 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 = await Document.findByPk(id, { userId: user.id });
if (document.archivedAt) {
authorize(user, 'unarchive', document);
@@ -439,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);
}
@@ -486,9 +506,9 @@ 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);
const user = ctx.state.user;
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'update', document);
document.pinnedById = user.id;
@@ -513,9 +533,9 @@ 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);
const user = ctx.state.user;
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'update', document);
document.pinnedById = null;
@@ -540,9 +560,9 @@ 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);
const user = ctx.state.user;
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'read', document);
await Star.findOrCreate({
@@ -563,9 +583,9 @@ 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);
const user = ctx.state.user;
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'read', document);
await Star.destroy({
@@ -603,7 +623,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 +641,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 +708,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 = await Document.findByPk(id, { userId: user.id });
authorize(user, 'update', document);
if (lastRevision && lastRevision !== document.revisionCount) {
throw new InvalidRequestError('Document has changed since last revision');
@@ -771,12 +792,10 @@ router.post('documents.move', auth(), async ctx => {
}
const user = ctx.state.user;
const document = await Document.findByPk(id);
const document = await Document.findByPk(id, { userId: user.id });
const { collection } = document;
authorize(user, 'move', document);
const collection = await Collection.findByPk(collectionId);
authorize(user, 'update', collection);
if (collection.type !== 'atlas' && parentDocumentId) {
throw new InvalidRequestError(
'Document cannot be nested in this collection type'
@@ -784,7 +803,7 @@ router.post('documents.move', auth(), async ctx => {
}
if (parentDocumentId) {
const parent = await Document.findByPk(parentDocumentId);
const parent = await Document.findByPk(parentDocumentId, user.id);
authorize(user, 'update', parent);
}
@@ -815,7 +834,7 @@ router.post('documents.archive', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'archive', document);
await document.archive(user.id);
@@ -841,7 +860,7 @@ router.post('documents.delete', auth(), async ctx => {
ctx.assertPresent(id, 'id is required');
const user = ctx.state.user;
const document = await Document.findByPk(id);
const document = await Document.findByPk(id, { userId: user.id });
authorize(user, 'delete', document);
await document.delete();
+188 -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,
@@ -274,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({
@@ -308,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();
@@ -575,6 +664,39 @@ 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, collection } = await seed();
collection.private = true;
await collection.save();
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,
collectionId: collection.id,
});
const res = await server.post('/api/documents.search', {
body: {
token: user.getJwtToken(),
query: 'search term',
collectionId: collection.id,
},
});
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();
@@ -817,6 +939,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 +1058,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 +1160,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 +1376,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 +1462,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 -1
View File
@@ -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);
+22
View File
@@ -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({
+2 -2
View File
@@ -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 });
+46 -1
View File
@@ -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', {
+5
View File
@@ -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',
],
},
})
);
+3 -1
View File
@@ -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}`);
@@ -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']],
},
+47 -21
View File
@@ -155,25 +155,43 @@ 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', userId => {
if (userId) {
return {
include: [
{
model: models.Collection,
as: 'collection',
include: [
{
model: models.CollectionUser,
as: 'memberships',
where: { userId },
required: false,
},
],
},
],
};
}
return {
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 +208,12 @@ Document.associate = models => {
}));
};
Document.findByPk = async (id, options) => {
const scope = Document.scope('withUnpublished');
Document.findByPk = async function(id, options = {}) {
// allow default preloading of collection membership if `userId` is passed in find options
// almost every endpoint needs the collection membership to determine policy permissions.
const scope = this.scope('withUnpublished', {
method: ['withCollection', options.userId],
});
if (isUUID(id)) {
return scope.findOne({
@@ -281,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 },
],
+5 -1
View File
@@ -51,6 +51,11 @@ 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
@@ -61,7 +66,6 @@ User.prototype.collectionIds = async function(paranoid: boolean = true) {
include: [
{
model: User,
through: 'collection_users',
as: 'users',
where: { id: this.id },
required: false,
+7 -1
View File
@@ -579,7 +579,13 @@ export default function Api() {
label="Get pinned documents for a collection"
>
<Description>Return pinned documents for a collection</Description>
<Arguments pagination />
<Arguments pagination>
<Argument
id="collectionId"
description="Collection ID"
required
/>
</Arguments>
</Method>
<Method
+43 -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,56 @@ 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;
return ['read_write', 'maintainer'].includes(
collection.memberships[0].permission
);
}
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;
+59 -12
View File
@@ -1,4 +1,5 @@
// @flow
import invariant from 'invariant';
import policy from './policy';
import { Document, Revision, User } from '../models';
@@ -6,27 +7,70 @@ 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', '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;
}
return user.teamId === document.teamId;
});
allow(User, ['update', 'move', 'share'], Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
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?'
);
if (cannot(user, 'update', document.collection)) return false;
if (document.archivedAt) return false;
return user.teamId === document.teamId;
});
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;
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;
}
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.publishedAt) return false;
if (document.archivedAt) return false;
@@ -34,9 +78,12 @@ allow(User, 'archive', Document, (user, document) => {
});
allow(User, 'unarchive', Document, (user, document) => {
if (document.collection) {
if (cannot(user, 'read', document.collection)) return false;
}
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;
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(),
+40 -30
View File
@@ -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,48 @@ export default class Websockets {
const collection = await Collection.findByPk(event.collectionId, {
paranoid: false,
});
const collections = [await presentCollection(collection)];
return socketio.to(`collection-${collection.id}`).emit('entities', {
return socketio.to(`team-${collection.teamId}`).emit('entities', {
event: event.name,
collections,
collectionIds: [event.collectionId],
});
}
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:
}
}
+1
View File
@@ -49,6 +49,7 @@ export const base = {
backgroundTransition: 'background 100ms ease-in-out',
zIndex: 100,
selected: colors.primary,
buttonBackground: colors.primary,
buttonText: colors.white,
};