Merge pull request #614 from outline/jori/billing-suspended
Suspended accounts and settings changes
This commit is contained in:
commit
c7d50c4a78
@ -2,7 +2,8 @@
|
||||
import React from 'react';
|
||||
import { Provider } from 'mobx-react';
|
||||
import stores from 'stores';
|
||||
import SettingsStore from 'stores/SettingsStore';
|
||||
import ApiKeysStore from 'stores/ApiKeysStore';
|
||||
import UsersStore from 'stores/UsersStore';
|
||||
import DocumentsStore from 'stores/DocumentsStore';
|
||||
import CollectionsStore from 'stores/CollectionsStore';
|
||||
import CacheStore from 'stores/CacheStore';
|
||||
@ -22,7 +23,8 @@ const Auth = ({ children }: Props) => {
|
||||
const { user, team } = stores.auth;
|
||||
const cache = new CacheStore(user.id);
|
||||
authenticatedStores = {
|
||||
settings: new SettingsStore(),
|
||||
apiKeys: new ApiKeysStore(),
|
||||
users: new UsersStore(),
|
||||
documents: new DocumentsStore({
|
||||
ui: stores.ui,
|
||||
cache,
|
||||
|
@ -17,6 +17,7 @@ import Sidebar from 'components/Sidebar';
|
||||
import SettingsSidebar from 'components/Sidebar/Settings';
|
||||
import Modals from 'components/Modals';
|
||||
import Toasts from 'components/Toasts';
|
||||
import ErrorSuspended from 'scenes/ErrorSuspended';
|
||||
|
||||
import AuthStore from 'stores/AuthStore';
|
||||
import UiStore from 'stores/UiStore';
|
||||
@ -71,6 +72,8 @@ class Layout extends React.Component {
|
||||
const { user, team } = auth;
|
||||
const showSidebar = auth.authenticated && user && team;
|
||||
|
||||
if (auth.isSuspended) return <ErrorSuspended />;
|
||||
|
||||
return (
|
||||
<Container column auto>
|
||||
<Helmet>
|
||||
|
@ -53,8 +53,8 @@ class SettingsSidebar extends Component {
|
||||
</Section>
|
||||
<Section>
|
||||
<Header>Team</Header>
|
||||
<SidebarLink to="/settings/members" icon={<UserIcon />}>
|
||||
Members
|
||||
<SidebarLink to="/settings/users" icon={<UserIcon />}>
|
||||
Users
|
||||
</SidebarLink>
|
||||
<SidebarLink
|
||||
to="/settings/integrations/slack"
|
||||
|
@ -21,7 +21,7 @@ import Collection from 'scenes/Collection';
|
||||
import Document from 'scenes/Document';
|
||||
import Search from 'scenes/Search';
|
||||
import Settings from 'scenes/Settings';
|
||||
import Members from 'scenes/Settings/Members';
|
||||
import Users from 'scenes/Settings/Users';
|
||||
import Slack from 'scenes/Settings/Slack';
|
||||
import Tokens from 'scenes/Settings/Tokens';
|
||||
import SlackAuth from 'scenes/SlackAuth';
|
||||
@ -68,7 +68,7 @@ render(
|
||||
<Route exact path="/starred" component={Starred} />
|
||||
<Route exact path="/drafts" component={Drafts} />
|
||||
<Route exact path="/settings" component={Settings} />
|
||||
<Route exact path="/settings/members" component={Members} />
|
||||
<Route exact path="/settings/users" component={Users} />
|
||||
<Route exact path="/settings/tokens" component={Tokens} />
|
||||
<Route
|
||||
exact
|
||||
|
29
app/scenes/ErrorSuspended/ErrorSuspended.js
Normal file
29
app/scenes/ErrorSuspended/ErrorSuspended.js
Normal file
@ -0,0 +1,29 @@
|
||||
// @flow
|
||||
import React from 'react';
|
||||
import { inject, observer } from 'mobx-react';
|
||||
|
||||
import CenteredContent from 'components/CenteredContent';
|
||||
import PageTitle from 'components/PageTitle';
|
||||
import AuthStore from 'stores/AuthStore';
|
||||
|
||||
const ErrorSuspended = observer(({ auth }: { auth: AuthStore }) => {
|
||||
return (
|
||||
<CenteredContent>
|
||||
<PageTitle title="Your account has been suspended" />
|
||||
<h1>
|
||||
<span role="img" aria-label="Warning sign">
|
||||
⚠️
|
||||
</span>{' '}
|
||||
Your account has been suspended
|
||||
</h1>
|
||||
|
||||
<p>
|
||||
A team admin (<strong>{auth.suspendedContactEmail}</strong>) has
|
||||
suspended your account. To re-activate your account, please reach out to
|
||||
them directly.
|
||||
</p>
|
||||
</CenteredContent>
|
||||
);
|
||||
});
|
||||
|
||||
export default inject('auth')(ErrorSuspended);
|
3
app/scenes/ErrorSuspended/index.js
Normal file
3
app/scenes/ErrorSuspended/index.js
Normal file
@ -0,0 +1,3 @@
|
||||
// @flow
|
||||
import ErrorSuspended from './ErrorSuspended';
|
||||
export default ErrorSuspended;
|
@ -1,95 +0,0 @@
|
||||
// @flow
|
||||
import React, { Component } from 'react';
|
||||
import { observable } from 'mobx';
|
||||
import { observer, inject } from 'mobx-react';
|
||||
import styled from 'styled-components';
|
||||
import Flex from 'shared/components/Flex';
|
||||
import Avatar from 'components/Avatar';
|
||||
import { color } from 'shared/styles/constants';
|
||||
|
||||
import ErrorsStore from 'stores/ErrorsStore';
|
||||
import SettingsStore from 'stores/SettingsStore';
|
||||
import CenteredContent from 'components/CenteredContent';
|
||||
import LoadingPlaceholder from 'components/LoadingPlaceholder';
|
||||
import PageTitle from 'components/PageTitle';
|
||||
|
||||
@observer
|
||||
class Members extends Component {
|
||||
props: {
|
||||
errors: ErrorsStore,
|
||||
settings: SettingsStore,
|
||||
};
|
||||
|
||||
@observable members;
|
||||
@observable isLoaded: boolean = false;
|
||||
|
||||
@observable inviteEmails: string = '';
|
||||
@observable isInviting: boolean = false;
|
||||
|
||||
componentDidMount() {
|
||||
this.props.settings.fetchMembers();
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<CenteredContent>
|
||||
<PageTitle title="Members" />
|
||||
<h1>Members</h1>
|
||||
|
||||
{!this.props.settings.isFetching ? (
|
||||
<Flex column>
|
||||
{this.props.settings.members && (
|
||||
<MemberList column>
|
||||
{this.props.settings.members.map(member => (
|
||||
<Member key={member.id} justify="space-between" auto>
|
||||
<Flex>
|
||||
<Avatar src={member.avatarUrl} />
|
||||
<UserName>
|
||||
{member.name} {member.email && `(${member.email})`}
|
||||
{member.isAdmin && <AdminBadge>Admin</AdminBadge>}
|
||||
</UserName>
|
||||
</Flex>
|
||||
</Member>
|
||||
))}
|
||||
</MemberList>
|
||||
)}
|
||||
</Flex>
|
||||
) : (
|
||||
<LoadingPlaceholder />
|
||||
)}
|
||||
</CenteredContent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const MemberList = styled(Flex)`
|
||||
border: 1px solid ${color.smoke};
|
||||
border-radius: 4px;
|
||||
|
||||
margin-top: 20px;
|
||||
margin-bottom: 40px;
|
||||
`;
|
||||
|
||||
const Member = styled(Flex)`
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid ${color.smoke};
|
||||
font-size: 15px;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
`;
|
||||
|
||||
const UserName = styled.span`
|
||||
padding-left: 8px;
|
||||
`;
|
||||
|
||||
const AdminBadge = styled.span`
|
||||
margin-left: 10px;
|
||||
color: #777;
|
||||
font-size: 13px;
|
||||
text-transform: uppercase;
|
||||
font-weight: normal;
|
||||
`;
|
||||
|
||||
export default inject('errors', 'settings')(Members);
|
@ -5,7 +5,7 @@ import { observer, inject } from 'mobx-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
import ApiToken from './components/ApiToken';
|
||||
import SettingsStore from 'stores/SettingsStore';
|
||||
import ApiKeysStore from 'stores/ApiKeysStore';
|
||||
import { color } from 'shared/styles/constants';
|
||||
|
||||
import Button from 'components/Button';
|
||||
@ -19,11 +19,11 @@ import Subheading from 'components/Subheading';
|
||||
class Tokens extends Component {
|
||||
@observable name: string = '';
|
||||
props: {
|
||||
settings: SettingsStore,
|
||||
apiKeys: ApiKeysStore,
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
this.props.settings.fetchApiKeys();
|
||||
this.props.apiKeys.fetchPage({ limit: 100 });
|
||||
}
|
||||
|
||||
handleUpdate = (ev: SyntheticInputEvent) => {
|
||||
@ -32,13 +32,13 @@ class Tokens extends Component {
|
||||
|
||||
handleSubmit = async (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
await this.props.settings.createApiKey(this.name);
|
||||
await this.props.apiKeys.createApiKey(this.name);
|
||||
this.name = '';
|
||||
};
|
||||
|
||||
render() {
|
||||
const { settings } = this.props;
|
||||
const hasApiKeys = settings.apiKeys.length > 0;
|
||||
const { apiKeys } = this.props;
|
||||
const hasApiKeys = apiKeys.data.length > 0;
|
||||
|
||||
return (
|
||||
<CenteredContent>
|
||||
@ -49,13 +49,13 @@ class Tokens extends Component {
|
||||
<Subheading>Your tokens</Subheading>,
|
||||
<Table>
|
||||
<tbody>
|
||||
{settings.apiKeys.map(key => (
|
||||
{apiKeys.data.map(key => (
|
||||
<ApiToken
|
||||
id={key.id}
|
||||
key={key.id}
|
||||
name={key.name}
|
||||
secret={key.secret}
|
||||
onDelete={settings.deleteApiKey}
|
||||
onDelete={apiKeys.deleteApiKey}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
@ -78,7 +78,7 @@ class Tokens extends Component {
|
||||
<Button
|
||||
type="submit"
|
||||
value="Create Token"
|
||||
disabled={settings.isSaving}
|
||||
disabled={apiKeys.isSaving}
|
||||
/>
|
||||
</form>
|
||||
</CenteredContent>
|
||||
@ -96,4 +96,4 @@ const Table = styled.table`
|
||||
}
|
||||
`;
|
||||
|
||||
export default inject('settings')(Tokens);
|
||||
export default inject('apiKeys')(Tokens);
|
||||
|
108
app/scenes/Settings/Users.js
Normal file
108
app/scenes/Settings/Users.js
Normal file
@ -0,0 +1,108 @@
|
||||
// @flow
|
||||
import React, { Component } from 'react';
|
||||
import invariant from 'invariant';
|
||||
import { observer, inject } from 'mobx-react';
|
||||
import styled from 'styled-components';
|
||||
import Flex from 'shared/components/Flex';
|
||||
import Avatar from 'components/Avatar';
|
||||
import { color } from 'shared/styles/constants';
|
||||
|
||||
import AuthStore from 'stores/AuthStore';
|
||||
import ErrorsStore from 'stores/ErrorsStore';
|
||||
import UsersStore from 'stores/UsersStore';
|
||||
import CenteredContent from 'components/CenteredContent';
|
||||
import LoadingPlaceholder from 'components/LoadingPlaceholder';
|
||||
import PageTitle from 'components/PageTitle';
|
||||
import UserMenu from './components/UserMenu';
|
||||
|
||||
@observer
|
||||
class Users extends Component {
|
||||
props: {
|
||||
auth: AuthStore,
|
||||
errors: ErrorsStore,
|
||||
users: UsersStore,
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
this.props.users.fetchPage({ limit: 100 });
|
||||
}
|
||||
|
||||
render() {
|
||||
const currentUser = this.props.auth.user;
|
||||
invariant(currentUser, 'User should exist');
|
||||
|
||||
return (
|
||||
<CenteredContent>
|
||||
<PageTitle title="Users" />
|
||||
<h1>Users</h1>
|
||||
|
||||
{!this.props.users.isLoaded ? (
|
||||
<Flex column>
|
||||
{this.props.users.data && (
|
||||
<UserList column>
|
||||
{this.props.users.data.map(user => (
|
||||
<User key={user.id} justify="space-between" auto>
|
||||
<UserDetails suspended={user.isSuspended}>
|
||||
<Avatar src={user.avatarUrl} />
|
||||
<UserName>
|
||||
{user.name} {user.email && `(${user.email})`}
|
||||
{user.isAdmin && (
|
||||
<Badge admin={user.isAdmin}>Admin</Badge>
|
||||
)}
|
||||
{user.isSuspended && <Badge>Suspended</Badge>}
|
||||
</UserName>
|
||||
</UserDetails>
|
||||
<Flex>
|
||||
{currentUser.id !== user.id && <UserMenu user={user} />}
|
||||
</Flex>
|
||||
</User>
|
||||
))}
|
||||
</UserList>
|
||||
)}
|
||||
</Flex>
|
||||
) : (
|
||||
<LoadingPlaceholder />
|
||||
)}
|
||||
</CenteredContent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const UserList = styled(Flex)`
|
||||
border: 1px solid ${color.smoke};
|
||||
border-radius: 4px;
|
||||
|
||||
margin-top: 20px;
|
||||
margin-bottom: 40px;
|
||||
`;
|
||||
|
||||
const User = styled(Flex)`
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid ${color.smoke};
|
||||
font-size: 15px;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
`;
|
||||
|
||||
const UserDetails = styled(Flex)`
|
||||
opacity: ${({ suspended }) => (suspended ? 0.5 : 1)};
|
||||
`;
|
||||
|
||||
const UserName = styled.span`
|
||||
padding-left: 8px;
|
||||
`;
|
||||
|
||||
const Badge = styled.span`
|
||||
margin-left: 10px;
|
||||
padding: 2px 6px 3px;
|
||||
background-color: ${({ admin }) => (admin ? color.primary : color.smokeDark)};
|
||||
color: ${({ admin }) => (admin ? color.white : color.text)};
|
||||
border-radius: 2px;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
font-weight: normal;
|
||||
`;
|
||||
|
||||
export default inject('auth', 'errors', 'users')(Users);
|
93
app/scenes/Settings/components/UserMenu.js
Normal file
93
app/scenes/Settings/components/UserMenu.js
Normal file
@ -0,0 +1,93 @@
|
||||
// @flow
|
||||
import React, { Component } from 'react';
|
||||
import { inject, observer } from 'mobx-react';
|
||||
|
||||
import UsersStore from 'stores/UsersStore';
|
||||
import MoreIcon from 'components/Icon/MoreIcon';
|
||||
import { DropdownMenu, DropdownMenuItem } from 'components/DropdownMenu';
|
||||
import type { User } from 'types';
|
||||
|
||||
type Props = {
|
||||
user: User,
|
||||
users: UsersStore,
|
||||
};
|
||||
|
||||
@observer
|
||||
class UserMenu extends Component {
|
||||
props: Props;
|
||||
|
||||
handlePromote = (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
const { user, users } = this.props;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Are you want to make ${
|
||||
user.name
|
||||
} an admin? Admins can modify team and billing information.`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
users.promote(user);
|
||||
};
|
||||
|
||||
handleDemote = (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
const { user, users } = this.props;
|
||||
if (!window.confirm(`Are you want to make ${user.name} a member?`)) {
|
||||
return;
|
||||
}
|
||||
users.demote(user);
|
||||
};
|
||||
|
||||
handleSuspend = (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
const { user, users } = this.props;
|
||||
if (
|
||||
!window.confirm(
|
||||
"Are you want to suspend this account? Suspended users won't be able to access Outline."
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
users.suspend(user);
|
||||
};
|
||||
|
||||
handleActivate = (ev: SyntheticEvent) => {
|
||||
ev.preventDefault();
|
||||
const { user, users } = this.props;
|
||||
users.activate(user);
|
||||
};
|
||||
|
||||
render() {
|
||||
const { user } = this.props;
|
||||
|
||||
return (
|
||||
<span>
|
||||
<DropdownMenu label={<MoreIcon />}>
|
||||
{!user.isSuspended &&
|
||||
(user.isAdmin ? (
|
||||
<DropdownMenuItem onClick={this.handleDemote}>
|
||||
Make {user.name} a member…
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem onClick={this.handlePromote}>
|
||||
Make {user.name} an admin…
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{user.isSuspended ? (
|
||||
<DropdownMenuItem onClick={this.handleActivate}>
|
||||
Activate account
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem onClick={this.handleSuspend}>
|
||||
Suspend account…
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenu>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default inject('users')(UserMenu);
|
@ -2,25 +2,24 @@
|
||||
import { observable, action, runInAction } from 'mobx';
|
||||
import invariant from 'invariant';
|
||||
import { client } from 'utils/ApiClient';
|
||||
import type { ApiKey, User } from 'types';
|
||||
import type { ApiKey, PaginationParams } from 'types';
|
||||
|
||||
class SettingsStore {
|
||||
@observable apiKeys: ApiKey[] = [];
|
||||
@observable members: User[] = [];
|
||||
class ApiKeysStore {
|
||||
@observable data: ApiKey[] = [];
|
||||
@observable isFetching: boolean = false;
|
||||
@observable isSaving: boolean = false;
|
||||
|
||||
@action
|
||||
fetchApiKeys = async () => {
|
||||
fetchPage = async (options: ?PaginationParams): Promise<*> => {
|
||||
this.isFetching = true;
|
||||
|
||||
try {
|
||||
const res = await client.post('/apiKeys.list');
|
||||
const res = await client.post('/apiKeys.list', options);
|
||||
invariant(res && res.data, 'Data should be available');
|
||||
const { data } = res;
|
||||
|
||||
runInAction('fetchApiKeys', () => {
|
||||
this.apiKeys = data;
|
||||
this.data = data;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
@ -37,7 +36,7 @@ class SettingsStore {
|
||||
invariant(res && res.data, 'Data should be available');
|
||||
const { data } = res;
|
||||
runInAction('createApiKey', () => {
|
||||
this.apiKeys.push(data);
|
||||
this.data.push(data);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
@ -50,30 +49,12 @@ class SettingsStore {
|
||||
try {
|
||||
await client.post('/apiKeys.delete', { id });
|
||||
runInAction('deleteApiKey', () => {
|
||||
this.fetchApiKeys();
|
||||
this.fetchPage();
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
}
|
||||
};
|
||||
|
||||
@action
|
||||
fetchMembers = async () => {
|
||||
this.isFetching = true;
|
||||
|
||||
try {
|
||||
const res = await client.post('/team.users');
|
||||
invariant(res && res.data, 'Data should be available');
|
||||
const { data } = res;
|
||||
|
||||
runInAction('fetchMembers', () => {
|
||||
this.members = data.reverse();
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
}
|
||||
this.isFetching = false;
|
||||
};
|
||||
}
|
||||
|
||||
export default SettingsStore;
|
||||
export default ApiKeysStore;
|
@ -14,6 +14,8 @@ class AuthStore {
|
||||
@observable token: ?string;
|
||||
@observable oauthState: string;
|
||||
@observable isLoading: boolean = false;
|
||||
@observable isSuspended: boolean = false;
|
||||
@observable suspendedContactEmail: ?string;
|
||||
|
||||
/* Computed */
|
||||
|
||||
@ -43,8 +45,10 @@ class AuthStore {
|
||||
this.team = res.data.team;
|
||||
});
|
||||
} catch (err) {
|
||||
// Failure to update user info is a non-fatal error.
|
||||
console.error(err);
|
||||
if (err.error.error === 'user_suspended') {
|
||||
this.isSuspended = true;
|
||||
this.suspendedContactEmail = err.error.data.adminEmail;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
65
app/stores/UsersStore.js
Normal file
65
app/stores/UsersStore.js
Normal file
@ -0,0 +1,65 @@
|
||||
// @flow
|
||||
import { observable, action, runInAction } from 'mobx';
|
||||
import invariant from 'invariant';
|
||||
import { client } from 'utils/ApiClient';
|
||||
import type { User, PaginationParams } from 'types';
|
||||
|
||||
class UsersStore {
|
||||
@observable data: User[] = [];
|
||||
@observable isLoaded: boolean = false;
|
||||
@observable isSaving: boolean = false;
|
||||
|
||||
@action
|
||||
fetchPage = async (options: ?PaginationParams): Promise<*> => {
|
||||
try {
|
||||
const res = await client.post('/team.users', options);
|
||||
invariant(res && res.data, 'Data should be available');
|
||||
const { data } = res;
|
||||
|
||||
runInAction('fetchUsers', () => {
|
||||
this.data = data.reverse();
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
}
|
||||
this.isLoaded = false;
|
||||
};
|
||||
|
||||
@action
|
||||
promote = async (user: User) => {
|
||||
return this.actionOnUser('promote', user);
|
||||
};
|
||||
|
||||
@action
|
||||
demote = async (user: User) => {
|
||||
return this.actionOnUser('demote', user);
|
||||
};
|
||||
|
||||
@action
|
||||
suspend = async (user: User) => {
|
||||
return this.actionOnUser('suspend', user);
|
||||
};
|
||||
|
||||
@action
|
||||
activate = async (user: User) => {
|
||||
return this.actionOnUser('activate', user);
|
||||
};
|
||||
|
||||
actionOnUser = async (action: string, user: User) => {
|
||||
try {
|
||||
const res = await client.post(`/user.${action}`, {
|
||||
id: user.id,
|
||||
});
|
||||
invariant(res && res.data, 'Data should be available');
|
||||
const { data } = res;
|
||||
|
||||
runInAction(`UsersStore#${action}`, () => {
|
||||
this.data = this.data.map(user => (user.id === data.id ? data : user));
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Something went wrong');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default UsersStore;
|
@ -5,6 +5,8 @@ export type User = {
|
||||
name: string,
|
||||
email: string,
|
||||
username: string,
|
||||
isAdmin?: boolean,
|
||||
isSuspended?: boolean,
|
||||
};
|
||||
|
||||
export type Team = {
|
||||
|
@ -84,7 +84,7 @@ class ApiClient {
|
||||
})
|
||||
.catch(error => {
|
||||
error.response.json().then(json => {
|
||||
error.data = json;
|
||||
error.error = json;
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
@ -1,62 +1,5 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`#team.addAdmin should promote a new admin 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": true,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.addAdmin should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.removeAdmin should demote an admin 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.removeAdmin should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.removeAdmin shouldn't demote admins if only one available 1`] = `
|
||||
Object {
|
||||
"error": "validation_error",
|
||||
"message": "At least one admin is required",
|
||||
"ok": false,
|
||||
"status": 400,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#team.users should require admin for detailed info 1`] = `
|
||||
Object {
|
||||
"data": Array [
|
||||
@ -91,6 +34,7 @@ Object {
|
||||
"email": "admin@example.com",
|
||||
"id": "fa952cff-fa64-4d42-a6ea-6955c9689046",
|
||||
"isAdmin": true,
|
||||
"isSuspended": false,
|
||||
"name": "Admin User",
|
||||
"username": "admin",
|
||||
},
|
||||
@ -99,6 +43,7 @@ Object {
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"isSuspended": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
|
@ -1,5 +1,64 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`#user.activate should activate a suspended user 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"isSuspended": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.activate should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.demote should demote an admin 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"isSuspended": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.demote should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.demote shouldn't demote admins if only one available 1`] = `
|
||||
Object {
|
||||
"error": "validation_error",
|
||||
"message": "At least one admin is required",
|
||||
"ok": false,
|
||||
"status": 400,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.info should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
@ -22,6 +81,65 @@ Object {
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.promote should promote a new admin 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": true,
|
||||
"isSuspended": false,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.promote should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.suspend should require admin 1`] = `
|
||||
Object {
|
||||
"error": "admin_required",
|
||||
"message": "An admin role is required to access this resource",
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.suspend should suspend an user 1`] = `
|
||||
Object {
|
||||
"data": Object {
|
||||
"avatarUrl": "http://example.com/avatar.png",
|
||||
"email": "user1@example.com",
|
||||
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
|
||||
"isAdmin": false,
|
||||
"isSuspended": true,
|
||||
"name": "User 1",
|
||||
"username": "user1",
|
||||
},
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.suspend shouldn't allow suspending the user themselves 1`] = `
|
||||
Object {
|
||||
"error": "validation_error",
|
||||
"message": "Unable to suspend the current user",
|
||||
"ok": false,
|
||||
"status": 400,
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`#user.update should require authentication 1`] = `
|
||||
Object {
|
||||
"error": "authentication_required",
|
||||
|
@ -29,6 +29,7 @@ api.use(async (ctx, next) => {
|
||||
} catch (err) {
|
||||
ctx.status = err.status || 500;
|
||||
let message = err.message || err.name;
|
||||
let error;
|
||||
|
||||
if (err instanceof Sequelize.ValidationError) {
|
||||
// super basic form error handling
|
||||
@ -40,18 +41,21 @@ api.use(async (ctx, next) => {
|
||||
|
||||
if (message.match('Authorization error')) {
|
||||
ctx.status = 403;
|
||||
error = 'authorization_error';
|
||||
}
|
||||
|
||||
if (ctx.status === 500) {
|
||||
message = 'Internal Server Error';
|
||||
error = 'internal_server_error';
|
||||
ctx.app.emit('error', err, ctx);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
error: _.snakeCase(err.id || err.message),
|
||||
error: _.snakeCase(err.id || error),
|
||||
status: err.status,
|
||||
message,
|
||||
data: err.errorData ? err.errorData : undefined,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
@ -2,7 +2,7 @@
|
||||
import JWT from 'jsonwebtoken';
|
||||
import { type Context } from 'koa';
|
||||
import { User, ApiKey } from '../../models';
|
||||
import { AuthenticationError } from '../../errors';
|
||||
import { AuthenticationError, UserSuspendedError } from '../../errors';
|
||||
|
||||
export default function auth() {
|
||||
return async function authMiddleware(
|
||||
@ -35,53 +35,56 @@ export default function auth() {
|
||||
|
||||
if (!token) throw new AuthenticationError('Authentication required');
|
||||
|
||||
if (token) {
|
||||
let user;
|
||||
let user;
|
||||
|
||||
if (String(token).match(/^[\w]{38}$/)) {
|
||||
// API key
|
||||
let apiKey;
|
||||
try {
|
||||
apiKey = await ApiKey.findOne({
|
||||
where: {
|
||||
secret: token,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Invalid API key');
|
||||
}
|
||||
|
||||
if (!apiKey) throw new AuthenticationError('Invalid API key');
|
||||
|
||||
user = await User.findById(apiKey.userId);
|
||||
if (!user) throw new AuthenticationError('Invalid API key');
|
||||
} else {
|
||||
// JWT
|
||||
// Get user without verifying payload signature
|
||||
let payload;
|
||||
try {
|
||||
payload = JWT.decode(token);
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Unable to decode JWT token');
|
||||
}
|
||||
|
||||
if (!payload) throw new AuthenticationError('Invalid token');
|
||||
|
||||
user = await User.findById(payload.id);
|
||||
|
||||
try {
|
||||
JWT.verify(token, user.jwtSecret);
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Invalid token');
|
||||
}
|
||||
if (String(token).match(/^[\w]{38}$/)) {
|
||||
// API key
|
||||
let apiKey;
|
||||
try {
|
||||
apiKey = await ApiKey.findOne({
|
||||
where: {
|
||||
secret: token,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Invalid API key');
|
||||
}
|
||||
|
||||
ctx.state.token = token;
|
||||
ctx.state.user = user;
|
||||
// $FlowFixMe
|
||||
ctx.cache[user.id] = user;
|
||||
if (!apiKey) throw new AuthenticationError('Invalid API key');
|
||||
|
||||
user = await User.findById(apiKey.userId);
|
||||
if (!user) throw new AuthenticationError('Invalid API key');
|
||||
} else {
|
||||
// JWT
|
||||
// Get user without verifying payload signature
|
||||
let payload;
|
||||
try {
|
||||
payload = JWT.decode(token);
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Unable to decode JWT token');
|
||||
}
|
||||
|
||||
if (!payload) throw new AuthenticationError('Invalid token');
|
||||
|
||||
user = await User.findById(payload.id);
|
||||
|
||||
try {
|
||||
JWT.verify(token, user.jwtSecret);
|
||||
} catch (e) {
|
||||
throw new AuthenticationError('Invalid token');
|
||||
}
|
||||
}
|
||||
|
||||
if (user.isSuspended) {
|
||||
const suspendingAdmin = await User.findById(user.suspendedById);
|
||||
throw new UserSuspendedError({ adminEmail: suspendingAdmin.email });
|
||||
}
|
||||
|
||||
ctx.state.token = token;
|
||||
ctx.state.user = user;
|
||||
// $FlowFixMe
|
||||
ctx.cache[user.id] = user;
|
||||
|
||||
return next();
|
||||
};
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
/* eslint-disable flowtype/require-valid-file-annotation */
|
||||
import { flushdb, seed } from '../../test/support';
|
||||
import { buildUser } from '../../test/factories';
|
||||
import { ApiKey } from '../../models';
|
||||
import randomstring from 'randomstring';
|
||||
import auth from './authentication';
|
||||
@ -155,4 +156,32 @@ describe('Authentication middleware', async () => {
|
||||
);
|
||||
expect(state.user.id).toEqual(user.id);
|
||||
});
|
||||
|
||||
it('should return an error for suspended users', async () => {
|
||||
const state = {};
|
||||
const admin = await buildUser({});
|
||||
const user = await buildUser({
|
||||
suspendedAt: new Date(),
|
||||
suspendedById: admin.id,
|
||||
});
|
||||
const authMiddleware = auth();
|
||||
|
||||
try {
|
||||
await authMiddleware(
|
||||
{
|
||||
request: {
|
||||
get: jest.fn(() => `Bearer ${user.getJwtToken()}`),
|
||||
},
|
||||
state,
|
||||
cache: {},
|
||||
},
|
||||
jest.fn()
|
||||
);
|
||||
} catch (e) {
|
||||
expect(e.message).toEqual(
|
||||
'Your access has been suspended by the team admin'
|
||||
);
|
||||
expect(e.errorData.adminEmail).toEqual(admin.email);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -1,14 +1,11 @@
|
||||
// @flow
|
||||
import Router from 'koa-router';
|
||||
import { ValidationError } from '../errors';
|
||||
import { Team, User } from '../models';
|
||||
import { User } from '../models';
|
||||
|
||||
import auth from './middlewares/authentication';
|
||||
import pagination from './middlewares/pagination';
|
||||
import { presentUser } from '../presenters';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('team.users', auth(), pagination(), async ctx => {
|
||||
@ -31,41 +28,4 @@ router.post('team.users', auth(), pagination(), async ctx => {
|
||||
};
|
||||
});
|
||||
|
||||
router.post('team.addAdmin', auth(), async ctx => {
|
||||
const userId = ctx.body.user;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'promote', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
await team.addAdmin(user);
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
router.post('team.removeAdmin', auth(), async ctx => {
|
||||
const userId = ctx.body.user;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'demote', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
|
||||
try {
|
||||
await team.removeAdmin(user);
|
||||
} catch (err) {
|
||||
throw new ValidationError(err.message);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
@ -34,72 +34,3 @@ describe('#team.users', async () => {
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#team.addAdmin', async () => {
|
||||
it('should promote a new admin', async () => {
|
||||
const { admin, user } = await seed();
|
||||
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: { token: admin.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: { token: user.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#team.removeAdmin', async () => {
|
||||
it('should demote an admin', async () => {
|
||||
const { admin, user } = await seed();
|
||||
await user.update({ isAdmin: true }); // Make another admin
|
||||
|
||||
const res = await server.post('/api/team.removeAdmin', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
user: user.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("shouldn't demote admins if only one available ", async () => {
|
||||
const { admin } = await seed();
|
||||
|
||||
const res = await server.post('/api/team.removeAdmin', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
user: admin.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(400);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/team.addAdmin', {
|
||||
body: { token: user.getJwtToken(), user: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
@ -2,10 +2,13 @@
|
||||
import uuid from 'uuid';
|
||||
import Router from 'koa-router';
|
||||
import { makePolicy, signPolicy, publicS3Endpoint } from '../utils/s3';
|
||||
import { Event } from '../models';
|
||||
import { ValidationError } from '../errors';
|
||||
import { Event, User, Team } from '../models';
|
||||
import auth from './middlewares/authentication';
|
||||
import { presentUser } from '../presenters';
|
||||
import policy from '../policies';
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post('user.info', auth(), async ctx => {
|
||||
@ -75,4 +78,91 @@ router.post('user.s3Upload', auth(), async ctx => {
|
||||
};
|
||||
});
|
||||
|
||||
// Admin specific
|
||||
|
||||
router.post('user.promote', auth(), async ctx => {
|
||||
const userId = ctx.body.id;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'promote', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
await team.addAdmin(user);
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
router.post('user.demote', auth(), async ctx => {
|
||||
const userId = ctx.body.id;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'demote', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
try {
|
||||
await team.removeAdmin(user);
|
||||
} catch (err) {
|
||||
throw new ValidationError(err.message);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Suspend user
|
||||
*
|
||||
* Admin can suspend users to reduce the number of accounts on their billing plan
|
||||
*/
|
||||
router.post('user.suspend', auth(), async ctx => {
|
||||
const admin = ctx.state.user;
|
||||
const userId = ctx.body.id;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'suspend', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
try {
|
||||
await team.suspendUser(user, admin);
|
||||
} catch (err) {
|
||||
throw new ValidationError(err.message);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Activate user
|
||||
*
|
||||
* Admin can activate users to let them access resources. These users will also
|
||||
* account towards the billing plan limits.
|
||||
*/
|
||||
router.post('user.activate', auth(), async ctx => {
|
||||
const admin = ctx.state.user;
|
||||
const userId = ctx.body.id;
|
||||
const teamId = ctx.state.user.teamId;
|
||||
ctx.assertPresent(userId, 'id is required');
|
||||
|
||||
const user = await User.findById(userId);
|
||||
authorize(ctx.state.user, 'activate', user);
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
await team.activateUser(user, admin);
|
||||
|
||||
ctx.body = {
|
||||
data: presentUser(ctx, user, { includeDetails: true }),
|
||||
};
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
@ -66,3 +66,148 @@ describe('#user.update', async () => {
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#user.promote', async () => {
|
||||
it('should promote a new admin', async () => {
|
||||
const { admin, user } = await seed();
|
||||
|
||||
const res = await server.post('/api/user.promote', {
|
||||
body: { token: admin.getJwtToken(), id: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/user.promote', {
|
||||
body: { token: user.getJwtToken(), id: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#user.demote', async () => {
|
||||
it('should demote an admin', async () => {
|
||||
const { admin, user } = await seed();
|
||||
await user.update({ isAdmin: true }); // Make another admin
|
||||
|
||||
const res = await server.post('/api/user.demote', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
id: user.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("shouldn't demote admins if only one available ", async () => {
|
||||
const { admin } = await seed();
|
||||
|
||||
const res = await server.post('/api/user.demote', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
id: admin.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(400);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/user.promote', {
|
||||
body: { token: user.getJwtToken(), id: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#user.suspend', async () => {
|
||||
it('should suspend an user', async () => {
|
||||
const { admin, user } = await seed();
|
||||
|
||||
const res = await server.post('/api/user.suspend', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
id: user.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("shouldn't allow suspending the user themselves", async () => {
|
||||
const { admin } = await seed();
|
||||
|
||||
const res = await server.post('/api/user.suspend', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
id: admin.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(400);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/user.suspend', {
|
||||
body: { token: user.getJwtToken(), id: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#user.activate', async () => {
|
||||
it('should activate a suspended user', async () => {
|
||||
const { admin, user } = await seed();
|
||||
await user.update({
|
||||
suspendedById: admin.id,
|
||||
suspendedAt: new Date(),
|
||||
});
|
||||
|
||||
expect(user.isSuspended).toBe(true);
|
||||
const res = await server.post('/api/user.activate', {
|
||||
body: {
|
||||
token: admin.getJwtToken(),
|
||||
id: user.id,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should require admin', async () => {
|
||||
const { user } = await seed();
|
||||
const res = await server.post('/api/user.activate', {
|
||||
body: { token: user.getJwtToken(), id: user.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(403);
|
||||
expect(body).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
@ -19,6 +19,15 @@ export function AdminRequiredError(
|
||||
return httpErrors(403, message, { id: 'admin_required' });
|
||||
}
|
||||
|
||||
export function UserSuspendedError({ adminEmail }: { adminEmail: string }) {
|
||||
return httpErrors(403, 'Your access has been suspended by the team admin', {
|
||||
id: 'user_suspended',
|
||||
errorData: {
|
||||
adminEmail,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function InvalidRequestError(message: string = 'Request invalid') {
|
||||
return httpErrors(400, message, { id: 'invalid_request' });
|
||||
}
|
||||
|
22
server/migrations/20180303193036-suspended-users.js
Normal file
22
server/migrations/20180303193036-suspended-users.js
Normal file
@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn('users', 'suspendedById', {
|
||||
type: Sequelize.UUID,
|
||||
allowNull: true,
|
||||
references: {
|
||||
model: 'users',
|
||||
},
|
||||
});
|
||||
await queryInterface.addColumn('users', 'suspendedAt', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.removeColumn('users', 'suspendedById');
|
||||
await queryInterface.removeColumn('users', 'suspendedAt');
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -63,4 +63,20 @@ Team.prototype.removeAdmin = async function(user: User) {
|
||||
}
|
||||
};
|
||||
|
||||
Team.prototype.suspendUser = async function(user: User, admin: User) {
|
||||
if (user.id === admin.id)
|
||||
throw new Error('Unable to suspend the current user');
|
||||
return user.update({
|
||||
suspendedById: admin.id,
|
||||
suspendedAt: new Date(),
|
||||
});
|
||||
};
|
||||
|
||||
Team.prototype.activateUser = async function(user: User, admin: User) {
|
||||
return user.update({
|
||||
suspendedById: null,
|
||||
suspendedAt: null,
|
||||
});
|
||||
};
|
||||
|
||||
export default Team;
|
||||
|
@ -28,8 +28,15 @@ const User = sequelize.define(
|
||||
slackId: { type: DataTypes.STRING, allowNull: true, unique: true },
|
||||
slackData: DataTypes.JSONB,
|
||||
jwtSecret: encryptedFields.vault('jwtSecret'),
|
||||
suspendedAt: DataTypes.DATE,
|
||||
suspendedById: DataTypes.UUID,
|
||||
},
|
||||
{
|
||||
getterMethods: {
|
||||
isSuspended() {
|
||||
return !!this.suspendedAt;
|
||||
},
|
||||
},
|
||||
indexes: [
|
||||
{
|
||||
fields: ['email'],
|
||||
|
@ -202,6 +202,58 @@ export default function Pricing() {
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method method="user.promote" label="Promote a new admin user">
|
||||
<Description>
|
||||
Promote a user to be a team admin. This endpoint is only available
|
||||
for admin users.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument id="id" description="User ID to be promoted" required />
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method method="user.demote" label="Demote existing admin user">
|
||||
<Description>
|
||||
Demote existing team admin if there are more than one as one admin
|
||||
is always required. This endpoint is only available for admin
|
||||
users.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument id="id" description="User ID to be demoted" required />
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method method="user.suspend" label="Suspend user account">
|
||||
<Description>
|
||||
Admin can suspend users to reduce the number of accounts on their
|
||||
billing plan or prevent them from accessing documention.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument
|
||||
id="id"
|
||||
description="User ID to be suspended"
|
||||
required
|
||||
/>
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method
|
||||
method="user.activate"
|
||||
label="Activate a suspended user account"
|
||||
>
|
||||
<Description>
|
||||
Admin can re-active a suspended user. This will update the billing
|
||||
plan and re-enable their access to the documention.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument
|
||||
id="id"
|
||||
description="User ID to be activated"
|
||||
required
|
||||
/>
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method
|
||||
method="collections.list"
|
||||
label="List your document collections"
|
||||
@ -527,35 +579,6 @@ export default function Pricing() {
|
||||
</Description>
|
||||
<Arguments pagination />
|
||||
</Method>
|
||||
|
||||
<Method method="team.addAdmin" label="Promote a new admin user">
|
||||
<Description>
|
||||
Promote a user to be a team admin. This endpoint is only available
|
||||
for admin users.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument
|
||||
id="user"
|
||||
description="User ID to be promoted"
|
||||
required
|
||||
/>
|
||||
</Arguments>
|
||||
</Method>
|
||||
|
||||
<Method method="team.removeAdmin" label="Demote existing admin user">
|
||||
<Description>
|
||||
Demote existing team admin if there are more than one as one admin
|
||||
is always required. This endpoint is only available for admin
|
||||
users.
|
||||
</Description>
|
||||
<Arguments pagination>
|
||||
<Argument
|
||||
id="user"
|
||||
description="User ID to be demoted"
|
||||
required
|
||||
/>
|
||||
</Arguments>
|
||||
</Method>
|
||||
</Methods>
|
||||
</Container>
|
||||
</Grid>
|
||||
|
@ -19,8 +19,13 @@ allow(User, ['update', 'delete'], User, (actor, user) => {
|
||||
throw new AdminRequiredError();
|
||||
});
|
||||
|
||||
allow(User, ['promote', 'demote'], User, (actor, user) => {
|
||||
if (!user || user.teamId !== actor.teamId) return false;
|
||||
if (actor.isAdmin) return true;
|
||||
throw new AdminRequiredError();
|
||||
});
|
||||
allow(
|
||||
User,
|
||||
['promote', 'demote', 'activate', 'suspend'],
|
||||
User,
|
||||
(actor, user) => {
|
||||
if (!user || user.teamId !== actor.teamId) return false;
|
||||
if (actor.isAdmin) return true;
|
||||
throw new AdminRequiredError();
|
||||
}
|
||||
);
|
||||
|
@ -29,8 +29,9 @@ export default (
|
||||
user.avatarUrl || (user.slackData ? user.slackData.image_192 : null);
|
||||
|
||||
if (options.includeDetails) {
|
||||
userData.isAdmin = user.isAdmin;
|
||||
userData.email = user.email;
|
||||
userData.isAdmin = user.isAdmin;
|
||||
userData.isSuspended = user.isSuspended;
|
||||
}
|
||||
|
||||
return userData;
|
||||
|
Reference in New Issue
Block a user