This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
outline/server/api/users.js

299 lines
6.8 KiB
JavaScript
Raw Normal View History

// @flow
2016-05-20 06:51:22 +00:00
import uuid from 'uuid';
2016-04-29 05:25:37 +00:00
import Router from 'koa-router';
import format from 'date-fns/format';
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
import { Op } from '../sequelize';
import {
makePolicy,
getSignature,
publicS3Endpoint,
makeCredential,
} from '../utils/s3';
2018-03-04 23:38:51 +00:00
import { ValidationError } from '../errors';
import { Attachment, Event, User, Team } from '../models';
import auth from '../middlewares/authentication';
import pagination from './middlewares/pagination';
import userInviter from '../commands/userInviter';
2016-04-29 05:25:37 +00:00
import { presentUser } from '../presenters';
2018-03-04 23:38:51 +00:00
import policy from '../policies';
2016-04-29 05:25:37 +00:00
2018-03-04 23:38:51 +00:00
const { authorize } = policy;
2016-04-29 05:25:37 +00:00
const router = new Router();
router.post('users.list', auth(), pagination(), async ctx => {
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
const { query } = ctx.body;
const user = ctx.state.user;
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
let where = {
teamId: user.teamId,
};
if (query) {
where = {
...where,
name: {
[Op.iLike]: `%${query}%`,
},
};
}
const users = await User.findAll({
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
where,
order: [['createdAt', 'DESC']],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
ctx.body = {
pagination: ctx.state.pagination,
data: users.map(listUser =>
presentUser(listUser, { includeDetails: user.isAdmin })
),
};
});
router.post('users.info', auth(), async ctx => {
2019-04-19 01:51:16 +00:00
ctx.body = {
data: presentUser(ctx.state.user),
};
2016-05-20 06:51:22 +00:00
});
router.post('users.update', auth(), async ctx => {
const { user } = ctx.state;
2017-12-14 07:17:08 +00:00
const { name, avatarUrl } = ctx.body;
2017-12-14 07:32:45 +00:00
const endpoint = publicS3Endpoint();
if (name) user.name = name;
2018-05-31 19:44:32 +00:00
if (avatarUrl && avatarUrl.startsWith(`${endpoint}/uploads/${user.id}`)) {
2017-12-14 07:17:08 +00:00
user.avatarUrl = avatarUrl;
2018-05-31 19:44:32 +00:00
}
await user.save();
2019-04-19 01:51:16 +00:00
ctx.body = {
data: presentUser(user, { includeDetails: true }),
};
});
router.post('users.s3Upload', auth(), async ctx => {
let { name, filename, documentId, contentType, kind, size } = ctx.body;
// backwards compatability
name = name || filename;
contentType = contentType || kind;
ctx.assertPresent(name, 'name is required');
ctx.assertPresent(contentType, 'contentType is required');
2016-05-20 06:51:22 +00:00
ctx.assertPresent(size, 'size is required');
const { user } = ctx.state;
2016-05-20 06:51:22 +00:00
const s3Key = uuid.v4();
const key = `uploads/${user.id}/${s3Key}/${name}`;
const credential = makeCredential();
const longDate = format(new Date(), 'YYYYMMDDTHHmmss\\Z');
const policy = makePolicy(credential, longDate);
2017-12-11 06:58:52 +00:00
const endpoint = publicS3Endpoint();
2017-12-14 07:17:08 +00:00
const url = `${endpoint}/${key}`;
await Attachment.create({
key,
size,
url,
contentType,
documentId,
teamId: user.teamId,
userId: user.id,
});
2017-12-14 07:17:08 +00:00
await Event.create({
name: 'user.s3Upload',
data: { name },
teamId: user.teamId,
userId: user.id,
ip: ctx.request.ip,
2017-12-14 07:17:08 +00:00
});
2016-05-20 06:51:22 +00:00
2017-04-27 04:47:03 +00:00
ctx.body = {
data: {
maxUploadSize: process.env.AWS_S3_UPLOAD_MAX_SIZE,
2017-12-11 06:58:52 +00:00
uploadUrl: endpoint,
2017-04-27 04:47:03 +00:00
form: {
'Cache-Control': 'max-age=31557600',
'Content-Type': contentType,
2017-04-27 04:47:03 +00:00
acl: 'public-read',
key,
2017-04-27 04:47:03 +00:00
policy,
'x-amz-algorithm': 'AWS4-HMAC-SHA256',
'x-amz-credential': credential,
'x-amz-date': longDate,
'x-amz-signature': getSignature(policy),
2017-04-27 04:47:03 +00:00
},
asset: {
contentType,
name,
2017-12-14 07:17:08 +00:00
url,
2017-04-27 04:47:03 +00:00
size,
},
2016-05-20 06:51:22 +00:00
},
2017-04-27 04:47:03 +00:00
};
2016-04-29 05:25:37 +00:00
});
2018-03-04 23:38:51 +00:00
// Admin specific
router.post('users.promote', auth(), async ctx => {
2018-03-04 23:38:51 +00:00
const userId = ctx.body.id;
const teamId = ctx.state.user.teamId;
ctx.assertPresent(userId, 'id is required');
const user = await User.findByPk(userId);
2018-03-04 23:38:51 +00:00
authorize(ctx.state.user, 'promote', user);
const team = await Team.findByPk(teamId);
2018-03-04 23:38:51 +00:00
await team.addAdmin(user);
await Event.create({
name: 'users.promote',
actorId: ctx.state.user.id,
userId,
teamId,
data: { name: user.name },
ip: ctx.request.ip,
});
2018-03-04 23:38:51 +00:00
ctx.body = {
data: presentUser(user, { includeDetails: true }),
2018-03-04 23:38:51 +00:00
};
});
router.post('users.demote', auth(), async ctx => {
2018-03-04 23:38:51 +00:00
const userId = ctx.body.id;
const teamId = ctx.state.user.teamId;
ctx.assertPresent(userId, 'id is required');
const user = await User.findByPk(userId);
2018-03-04 23:38:51 +00:00
authorize(ctx.state.user, 'demote', user);
const team = await Team.findByPk(teamId);
2018-03-04 23:38:51 +00:00
try {
await team.removeAdmin(user);
} catch (err) {
throw new ValidationError(err.message);
}
await Event.create({
name: 'users.demote',
actorId: ctx.state.user.id,
userId,
teamId,
data: { name: user.name },
ip: ctx.request.ip,
});
2018-03-04 23:38:51 +00:00
ctx.body = {
data: presentUser(user, { includeDetails: true }),
2018-03-04 23:38:51 +00:00
};
});
router.post('users.suspend', auth(), async ctx => {
2018-03-04 23:38:51 +00:00
const admin = ctx.state.user;
const userId = ctx.body.id;
const teamId = ctx.state.user.teamId;
2018-03-05 00:53:57 +00:00
ctx.assertPresent(userId, 'id is required');
2018-03-04 23:38:51 +00:00
const user = await User.findByPk(userId);
2018-03-04 23:38:51 +00:00
authorize(ctx.state.user, 'suspend', user);
const team = await Team.findByPk(teamId);
2018-03-04 23:38:51 +00:00
try {
await team.suspendUser(user, admin);
} catch (err) {
throw new ValidationError(err.message);
}
await Event.create({
name: 'users.suspend',
actorId: ctx.state.user.id,
userId,
teamId,
data: { name: user.name },
ip: ctx.request.ip,
});
2018-03-04 23:38:51 +00:00
ctx.body = {
data: presentUser(user, { includeDetails: true }),
2018-03-04 23:38:51 +00:00
};
});
router.post('users.activate', auth(), async ctx => {
2018-03-04 23:38:51 +00:00
const admin = ctx.state.user;
const userId = ctx.body.id;
const teamId = ctx.state.user.teamId;
2018-03-05 00:53:57 +00:00
ctx.assertPresent(userId, 'id is required');
2018-03-04 23:38:51 +00:00
const user = await User.findByPk(userId);
2018-03-04 23:38:51 +00:00
authorize(ctx.state.user, 'activate', user);
const team = await Team.findByPk(teamId);
2018-03-04 23:38:51 +00:00
await team.activateUser(user, admin);
await Event.create({
name: 'users.activate',
actorId: ctx.state.user.id,
userId,
teamId,
data: { name: user.name },
ip: ctx.request.ip,
});
2018-03-04 23:38:51 +00:00
ctx.body = {
data: presentUser(user, { includeDetails: true }),
2018-03-04 23:38:51 +00:00
};
});
router.post('users.invite', auth(), async ctx => {
const { invites } = ctx.body;
ctx.assertPresent(invites, 'invites is required');
const user = ctx.state.user;
authorize(user, 'invite', User);
2019-12-22 22:54:12 +00:00
const response = await userInviter({ user, invites, ip: ctx.request.ip });
ctx.body = {
2019-12-22 22:54:12 +00:00
data: {
sent: response.sent,
users: response.users.map(user => presentUser(user)),
},
};
});
router.post('users.delete', auth(), async ctx => {
const { confirmation, id } = ctx.body;
2018-07-07 22:38:22 +00:00
ctx.assertPresent(confirmation, 'confirmation is required');
let user = ctx.state.user;
if (id) user = await User.findByPk(id);
authorize(ctx.state.user, 'delete', user);
2018-07-07 22:38:22 +00:00
try {
await user.destroy();
} catch (err) {
throw new ValidationError(err.message);
}
await Event.create({
name: 'users.delete',
actorId: user.id,
userId: user.id,
teamId: user.teamId,
data: { name: user.name },
ip: ctx.request.ip,
});
2018-07-07 22:38:22 +00:00
ctx.body = {
success: true,
};
});
2016-07-22 07:11:54 +00:00
export default router;