Admin endpoints

This commit is contained in:
Jori Lallo
2017-12-26 15:02:26 +02:00
parent a74e90fc09
commit 26d0d815a2
14 changed files with 366 additions and 38 deletions

View File

@@ -0,0 +1,88 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`#team.addAdmin should promote a new admin 1`] = `
Object {
"avatarUrl": "http://example.com/avatar.png",
"email": "user1@example.com",
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
"isAdmin": true,
"name": "User 1",
"ok": true,
"status": 200,
"username": "user1",
}
`;
exports[`#team.addAdmin should require admin 1`] = `
Object {
"error": "only_available_for_admins",
"message": "Only available for admins",
"ok": false,
"status": 403,
}
`;
exports[`#team.removeAdmin should demote an admin 1`] = `
Object {
"avatarUrl": null,
"ok": true,
"status": 200,
}
`;
exports[`#team.removeAdmin should require admin 1`] = `
Object {
"error": "only_available_for_admins",
"message": "Only available for admins",
"ok": false,
"status": 403,
}
`;
exports[`#team.removeAdmin shouldn't demote admins if only one available 1`] = `
Object {
"error": "at_least_one_admin_is_required",
"message": "At least one admin is required",
"ok": false,
"status": 400,
}
`;
exports[`#team.users should require admin 1`] = `
Object {
"error": "only_available_for_admins",
"message": "Only available for admins",
"ok": false,
"status": 403,
}
`;
exports[`#team.users should return teams paginated user list 1`] = `
Object {
"data": Array [
Object {
"avatarUrl": "http://example.com/avatar.png",
"email": "admin@example.com",
"id": "fa952cff-fa64-4d42-a6ea-6955c9689046",
"isAdmin": true,
"name": "Admin User",
"username": "admin",
},
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,
"pagination": Object {
"limit": 15,
"nextPath": "/api/team.users?limit=15&offset=15",
"offset": 0,
},
"status": 200,
}
`;

View File

@@ -13,7 +13,6 @@ exports[`#user.info should return known user 1`] = `
Object {
"data": Object {
"avatarUrl": "http://example.com/avatar.png",
"email": "user1@example.com",
"id": "46fde1d4-0050-428f-9f0b-0bf77f4bdf61",
"name": "User 1",
"username": "user1",

View File

@@ -13,7 +13,7 @@ router.post('auth.info', auth(), async ctx => {
ctx.body = {
data: {
user: await presentUser(ctx, user),
user: await presentUser(ctx, user, { includeDetails: true }),
team: await presentTeam(ctx, team),
},
};
@@ -51,9 +51,14 @@ router.post('auth.slack', async ctx => {
name: data.user.name,
email: data.user.email,
teamId: team.id,
isAdmin: !teamExisted,
slackData: data.user,
slackAccessToken: data.access_token,
});
// Set initial avatar
await user.updateAvatar();
await user.save();
}
if (!teamExisted) {
@@ -68,10 +73,6 @@ router.post('auth.slack', async ctx => {
expires: new Date('2100'),
});
// Update user's avatar
await user.updateAvatar();
await user.save();
ctx.body = {
data: {
user: await presentUser(ctx, user),

View File

@@ -59,6 +59,8 @@ router.post('hooks.slack', async ctx => {
});
if (!user) throw httpErrors.BadRequest('Invalid user');
if (!user.isAdmin)
throw httpErrors.BadRequest('Only admins can add integrations');
const documents = await Document.searchForUser(user, text, {
limit: 5,

70
server/api/team.js Normal file
View File

@@ -0,0 +1,70 @@
// @flow
import Router from 'koa-router';
import httpErrors from 'http-errors';
import User from '../models/User';
import Team from '../models/Team';
import auth from './middlewares/authentication';
import pagination from './middlewares/pagination';
import { presentUser } from '../presenters';
const router = new Router();
router.use(auth({ adminOnly: true }));
router.post('team.users', pagination(), async ctx => {
const user = ctx.state.user;
const users = await User.findAll({
where: {
teamId: user.teamId,
},
order: [['createdAt', 'DESC']],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
ctx.body = {
pagination: ctx.state.pagination,
data: users.map(user => presentUser(ctx, user, { includeDetails: true })),
};
});
router.post('team.addAdmin', async ctx => {
const { user } = ctx.body;
const admin = ctx.state.user;
ctx.assertPresent(user, 'id is required');
const team = await Team.findById(admin.teamId);
const promotedUser = await User.findOne({
where: { id: user, teamId: admin.teamId },
});
if (!promotedUser) throw httpErrors.NotFound();
await team.addAdmin(promotedUser);
ctx.body = presentUser(ctx, promotedUser, { includeDetails: true });
});
router.post('team.removeAdmin', async ctx => {
const { user } = ctx.body;
const admin = ctx.state.user;
ctx.assertPresent(user, 'id is required');
const team = await Team.findById(admin.teamId);
const demotedUser = await User.findOne({
where: { id: user, teamId: admin.teamId },
});
if (!demotedUser) throw httpErrors.NotFound();
try {
await team.removeAdmin(demotedUser);
ctx.body = presentUser(ctx, user, { includeDetails: true });
} catch (e) {
throw httpErrors.BadRequest(e.message);
}
});
export default router;

108
server/api/team.test.js Normal file
View File

@@ -0,0 +1,108 @@
/* eslint-disable flowtype/require-valid-file-annotation */
import TestServer from 'fetch-test-server';
import app from '..';
import { flushdb, seed } from '../test/support';
const server = new TestServer(app.callback());
beforeEach(flushdb);
afterAll(server.close);
describe('#team.users', async () => {
it('should return teams paginated user list', async () => {
const { admin } = await seed();
const res = await server.post('/api/team.users', {
body: { token: admin.getJwtToken() },
});
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.users', {
body: { token: user.getJwtToken() },
});
const body = await res.json();
expect(res.status).toEqual(403);
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() },
});
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() },
});
const body = await res.json();
expect(res.status).toEqual(403);
expect(body).toMatchSnapshot();
});
});

View File

@@ -1,6 +1,7 @@
// @flow
import { DataTypes, sequelize } from '../sequelize';
import { DataTypes, sequelize, Op } from '../sequelize';
import Collection from './Collection';
import User from './User';
const Team = sequelize.define(
'team',
@@ -41,4 +42,26 @@ Team.prototype.createFirstCollection = async function(userId) {
return atlas;
};
Team.prototype.addAdmin = async function(user: User) {
return await user.update({ isAdmin: true });
};
Team.prototype.removeAdmin = async function(user: User) {
const res = await User.findAndCountAll({
where: {
teamId: user.teamId,
isAdmin: true,
id: {
[Op.ne]: user.id,
},
},
limit: 1,
});
if (res.count >= 1) {
return await user.update({ isAdmin: false });
} else {
throw new Error('At least one admin is required');
}
};
export default Team;

View File

@@ -3,7 +3,6 @@
exports[`presents a user 1`] = `
Object {
"avatarUrl": "http://example.com/avatar.png",
"email": undefined,
"id": "123",
"name": "Test User",
"username": "testuser",
@@ -13,7 +12,6 @@ Object {
exports[`presents a user without slack data 1`] = `
Object {
"avatarUrl": null,
"email": undefined,
"id": "123",
"name": "Test User",
"username": "testuser",

View File

@@ -1,5 +1,6 @@
// @flow
import _ from 'lodash';
import { Op } from 'sequelize';
import { User, Document } from '../models';
import presentUser from './user';
import presentCollection from './collection';
@@ -57,7 +58,7 @@ async function present(ctx: Object, document: Document, options: ?Options) {
// This could be further optimized by using ctx.cache
data.collaborators = await User.findAll({
where: {
id: { $in: _.takeRight(document.collaboratorIds, 10) || [] },
id: { [Op.in]: _.takeRight(document.collaboratorIds, 10) || [] },
},
}).map(user => presentUser(ctx, user));

View File

@@ -1,17 +1,37 @@
// @flow
import User from '../models/User';
function present(ctx: Object, user: User) {
type Options = {
includeDetails?: boolean,
};
type UserPresentation = {
id: string,
username: string,
name: string,
avatarUrl: ?string,
email?: string,
isAdmin?: boolean,
};
export default (
ctx: Object,
user: User,
options: Options = {}
): UserPresentation => {
ctx.cache.set(user.id, user);
return {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
avatarUrl:
user.avatarUrl || (user.slackData ? user.slackData.image_192 : null),
};
}
const userData = {};
userData.id = user.id;
userData.username = user.username;
userData.name = user.name;
userData.avatarUrl =
user.avatarUrl || (user.slackData ? user.slackData.image_192 : null);
export default present;
if (options.includeDetails) {
userData.isAdmin = user.isAdmin;
userData.email = user.email;
}
return userData;
};

View File

@@ -8,8 +8,10 @@ const secretKey = process.env.SECRET_KEY;
export const encryptedFields = EncryptedField(Sequelize, secretKey);
export const DataTypes = Sequelize;
export const Op = Sequelize.Op;
export const sequelize = new Sequelize(process.env.DATABASE_URL, {
logging: debug('sql'),
typeValidation: true,
operatorsAliases: false,
});

View File

@@ -36,6 +36,21 @@ const seed = async () => {
},
});
const admin = await User.create({
id: 'fa952cff-fa64-4d42-a6ea-6955c9689046',
email: 'admin@example.com',
username: 'admin',
name: 'Admin User',
password: 'test123!',
teamId: team.id,
isAdmin: true,
slackId: 'U2399UF1P',
slackData: {
id: 'U2399UF1P',
image_192: 'http://example.com/avatar.png',
},
});
let collection = await Collection.create({
id: '26fde1d4-0050-428f-9f0b-0bf77f8bdf62',
name: 'Collection',
@@ -59,6 +74,7 @@ const seed = async () => {
return {
user,
admin,
collection,
document,
team,