mirror of
https://github.com/outline/outline.git
synced 2026-11-25 23:24:06 +03:00
* perf: Use FOR NO KEY UPDATE where locked rows are only updated Rows that other tables reference by foreign key are now locked with FOR NO KEY UPDATE when the transaction only updates or soft-deletes them, so concurrent inserts that reference the row are not blocked. * test: Collaborative save does not wait for foreign key inserts
660 lines
16 KiB
TypeScript
660 lines
16 KiB
TypeScript
import Router from "@koa/router";
|
|
import type { WhereOptions } from "sequelize";
|
|
import { Op } from "sequelize";
|
|
import { MAX_AVATAR_DISPLAY } from "@shared/constants";
|
|
import { GroupPermission, UserRole } from "@shared/types";
|
|
import auth from "@server/middlewares/authentication";
|
|
import { rateLimiter } from "@server/middlewares/rateLimiter";
|
|
import { transaction } from "@server/middlewares/transaction";
|
|
import validate from "@server/middlewares/validate";
|
|
import {
|
|
User,
|
|
Group,
|
|
GroupUser,
|
|
ExternalGroup,
|
|
AuthenticationProvider,
|
|
} from "@server/models";
|
|
import { authorize } from "@server/policies";
|
|
import { ValidationError } from "@server/errors";
|
|
import {
|
|
presentGroup,
|
|
presentGroupUser,
|
|
presentPolicies,
|
|
presentUser,
|
|
} from "@server/presenters";
|
|
import type { APIContext } from "@server/types";
|
|
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
|
import { QueryHelper } from "@server/storage/QueryHelper";
|
|
import pagination from "../middlewares/pagination";
|
|
import * as T from "./schema";
|
|
|
|
const router = new Router();
|
|
|
|
/** Standard include for loading ExternalGroup with its AuthenticationProvider. */
|
|
const externalGroupInclude = {
|
|
model: ExternalGroup,
|
|
as: "externalGroups",
|
|
required: false,
|
|
include: [
|
|
{
|
|
model: AuthenticationProvider,
|
|
as: "authenticationProvider",
|
|
attributes: ["id", "name", "providerId"],
|
|
},
|
|
],
|
|
};
|
|
|
|
router.post(
|
|
"groups.list",
|
|
auth(),
|
|
pagination(),
|
|
validate(T.GroupsListSchema),
|
|
async (ctx: APIContext<T.GroupsListReq>) => {
|
|
const { sort, direction, query, userId, externalId, name, source } =
|
|
ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
authorize(user, "listGroups", user.team);
|
|
|
|
let where: WhereOptions<Group> = {
|
|
teamId: user.teamId,
|
|
};
|
|
|
|
if (name) {
|
|
where = {
|
|
...where,
|
|
name: {
|
|
[Op.eq]: name,
|
|
},
|
|
};
|
|
} else if (query) {
|
|
where = {
|
|
...where,
|
|
name: { [Op.iLike]: QueryHelper.likeContains(query) },
|
|
};
|
|
}
|
|
|
|
if (externalId) {
|
|
where = {
|
|
...where,
|
|
externalId,
|
|
};
|
|
}
|
|
|
|
if (userId) {
|
|
const groupIds = await Group.filterByMember(userId)
|
|
.findAll({
|
|
attributes: ["id"],
|
|
})
|
|
.then((groups) => groups.map((g) => g.id));
|
|
|
|
where = {
|
|
...where,
|
|
id: {
|
|
[Op.in]: groupIds,
|
|
},
|
|
};
|
|
}
|
|
|
|
if (source) {
|
|
const externalGroupWhere: WhereOptions<ExternalGroup> = {
|
|
teamId: user.teamId,
|
|
groupId: { [Op.ne]: null },
|
|
};
|
|
|
|
const sourceGroupIds = await ExternalGroup.findAll({
|
|
attributes: ["groupId"],
|
|
where: externalGroupWhere,
|
|
...(source !== "manual" && {
|
|
include: [
|
|
{
|
|
model: AuthenticationProvider,
|
|
as: "authenticationProvider",
|
|
attributes: [],
|
|
where: { name: source },
|
|
},
|
|
],
|
|
}),
|
|
}).then((egs) =>
|
|
egs.map((eg) => eg.groupId).filter((id): id is string => id !== null)
|
|
);
|
|
|
|
where = {
|
|
...where,
|
|
id: {
|
|
...(where.id as object),
|
|
[source === "manual" ? Op.notIn : Op.in]: sourceGroupIds,
|
|
},
|
|
};
|
|
}
|
|
|
|
const [groups, total] = await Promise.all([
|
|
Group.findAll({
|
|
where,
|
|
include: [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: user.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
],
|
|
order: [
|
|
sort === "source"
|
|
? [
|
|
{ model: ExternalGroup, as: "externalGroups" },
|
|
{ model: AuthenticationProvider, as: "authenticationProvider" },
|
|
"name",
|
|
direction,
|
|
]
|
|
: [sort, direction],
|
|
],
|
|
offset: ctx.state.pagination.offset,
|
|
limit: ctx.state.pagination.limit,
|
|
}),
|
|
Group.count({
|
|
where,
|
|
}),
|
|
]);
|
|
|
|
const [presentedGroups, groupUsers] = await Promise.all([
|
|
Promise.all(groups.map(presentGroup)),
|
|
Promise.all(
|
|
groups.map((group) =>
|
|
GroupUser.scope("withUser").findAll({
|
|
where: {
|
|
groupId: group.id,
|
|
},
|
|
order: [["permission", "ASC"]],
|
|
limit: MAX_AVATAR_DISPLAY,
|
|
})
|
|
)
|
|
),
|
|
]);
|
|
|
|
ctx.body = {
|
|
pagination: { ...ctx.state.pagination, total },
|
|
data: {
|
|
groups: presentedGroups,
|
|
// TODO: Deprecated, will remove in the future as language conflicts with GroupMembership
|
|
groupMemberships: groupUsers
|
|
.flat()
|
|
.filter((groupUser) => groupUser.user)
|
|
.map((groupUser) =>
|
|
presentGroupUser(groupUser, { includeUser: true })
|
|
),
|
|
},
|
|
policies: presentPolicies(user, groups),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.info",
|
|
auth(),
|
|
validate(T.GroupsInfoSchema),
|
|
async (ctx: APIContext<T.GroupsInfoReq>) => {
|
|
const { id, externalId } = ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
|
|
const include = [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: user.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
];
|
|
|
|
const group = id
|
|
? await Group.findByPk(id, { include })
|
|
: externalId
|
|
? await Group.findOne({
|
|
include,
|
|
where: { teamId: user.teamId, externalId },
|
|
})
|
|
: null;
|
|
|
|
authorize(user, "read", group);
|
|
|
|
ctx.body = {
|
|
data: await presentGroup(group),
|
|
policies: presentPolicies(user, [group]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.create",
|
|
rateLimiter(RateLimiterStrategy.TenPerMinute),
|
|
auth(),
|
|
validate(T.GroupsCreateSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsCreateReq>) => {
|
|
const { name, description, icon, color, externalId, disableMentions } =
|
|
ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
authorize(user, "createGroup", user.team);
|
|
|
|
const group = await Group.createWithCtx(ctx, {
|
|
name,
|
|
description,
|
|
icon,
|
|
color,
|
|
externalId,
|
|
disableMentions,
|
|
teamId: user.teamId,
|
|
createdById: user.id,
|
|
});
|
|
|
|
group.groupUsers = [];
|
|
group.externalGroups = [];
|
|
|
|
ctx.body = {
|
|
data: await presentGroup(group),
|
|
policies: presentPolicies(user, [group]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.update",
|
|
auth(),
|
|
validate(T.GroupsUpdateSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsUpdateReq>) => {
|
|
const { id } = ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
const { transaction } = ctx.state;
|
|
|
|
const group = await Group.findByPk(id, {
|
|
transaction,
|
|
include: [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: user.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
],
|
|
lock: {
|
|
level: transaction.LOCK.NO_KEY_UPDATE,
|
|
of: Group,
|
|
},
|
|
});
|
|
authorize(user, "update", group);
|
|
|
|
if (group.externalGroups?.length) {
|
|
const { name, description } = ctx.input.body;
|
|
|
|
if (name !== undefined && name !== group.name) {
|
|
throw ValidationError(
|
|
"The name of a group synced from an external provider cannot be changed"
|
|
);
|
|
}
|
|
|
|
if (
|
|
description !== undefined &&
|
|
description !== (group.description ?? "")
|
|
) {
|
|
throw ValidationError(
|
|
"The description of a group synced from an external provider cannot be changed"
|
|
);
|
|
}
|
|
}
|
|
|
|
await group.updateWithCtx(ctx, ctx.input.body);
|
|
|
|
ctx.body = {
|
|
data: await presentGroup(group),
|
|
policies: presentPolicies(user, [group]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.delete",
|
|
auth(),
|
|
validate(T.GroupsDeleteSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsDeleteReq>) => {
|
|
const { id } = ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
const { transaction } = ctx.state;
|
|
|
|
const group = await Group.findByPk(id, {
|
|
transaction,
|
|
include: [externalGroupInclude],
|
|
lock: {
|
|
level: transaction.LOCK.NO_KEY_UPDATE,
|
|
of: Group,
|
|
},
|
|
});
|
|
authorize(user, "delete", group);
|
|
|
|
await group.destroyWithCtx(ctx);
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.deleteAll",
|
|
auth({ role: UserRole.Admin }),
|
|
validate(T.GroupsDeleteAllSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsDeleteAllReq>) => {
|
|
const { authenticationProviderId } = ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
const { transaction } = ctx.state;
|
|
|
|
const authenticationProvider = await AuthenticationProvider.findByPk(
|
|
authenticationProviderId,
|
|
{ transaction }
|
|
);
|
|
authorize(user, "update", authenticationProvider);
|
|
|
|
const groupIds = await ExternalGroup.findAll({
|
|
attributes: ["groupId"],
|
|
where: {
|
|
authenticationProviderId,
|
|
teamId: user.teamId,
|
|
groupId: { [Op.ne]: null },
|
|
},
|
|
transaction,
|
|
}).then((egs) =>
|
|
egs.map((eg) => eg.groupId).filter((id): id is string => id !== null)
|
|
);
|
|
|
|
if (groupIds.length) {
|
|
const groups = await Group.findAll({
|
|
where: { id: groupIds, teamId: user.teamId },
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
|
|
// Each group is destroyed individually so that a delete event is
|
|
// emitted, which revokes the access that its members were granted.
|
|
for (const group of groups) {
|
|
await group.destroyWithCtx(ctx);
|
|
}
|
|
}
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.memberships",
|
|
auth(),
|
|
pagination(),
|
|
validate(T.GroupsMembershipsSchema),
|
|
async (ctx: APIContext<T.GroupsMembershipsReq>) => {
|
|
const { id, query, permission } = ctx.input.body;
|
|
const { user } = ctx.state.auth;
|
|
|
|
const group = await Group.findByPk(id);
|
|
authorize(user, "read", group);
|
|
let userWhere;
|
|
|
|
if (query) {
|
|
userWhere = {
|
|
name: { [Op.iLike]: QueryHelper.likeContains(query) },
|
|
};
|
|
}
|
|
|
|
const groupUserWhere: Record<string, unknown> = {
|
|
groupId: id,
|
|
};
|
|
|
|
if (permission) {
|
|
groupUserWhere.permission = permission;
|
|
}
|
|
|
|
const options = {
|
|
where: groupUserWhere,
|
|
include: [
|
|
{
|
|
model: User,
|
|
as: "user",
|
|
where: userWhere,
|
|
required: true,
|
|
},
|
|
],
|
|
};
|
|
|
|
const [total, groupUsers] = await Promise.all([
|
|
GroupUser.count(options),
|
|
GroupUser.findAll({
|
|
...options,
|
|
order: [["createdAt", "DESC"]],
|
|
include: [
|
|
...options.include,
|
|
{
|
|
model: User,
|
|
as: "createdBy",
|
|
required: false,
|
|
},
|
|
],
|
|
offset: ctx.state.pagination.offset,
|
|
limit: ctx.state.pagination.limit,
|
|
}),
|
|
]);
|
|
|
|
ctx.body = {
|
|
pagination: { ...ctx.state.pagination, total },
|
|
data: {
|
|
groupMemberships: groupUsers.map((groupUser) =>
|
|
presentGroupUser(groupUser, { includeUser: true })
|
|
),
|
|
users: groupUsers.map((groupUser) => presentUser(groupUser.user)),
|
|
},
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.add_user",
|
|
auth(),
|
|
validate(T.GroupsAddUserSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsAddUserReq>) => {
|
|
const { id, userId, permission } = ctx.input.body;
|
|
const actor = ctx.state.auth.user;
|
|
const { transaction } = ctx.state;
|
|
|
|
const user = await User.findByPk(userId, { transaction });
|
|
authorize(actor, "read", user);
|
|
|
|
// Load group with group users for authorization
|
|
const group = await Group.findByPk(id, {
|
|
transaction,
|
|
include: [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: actor.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
],
|
|
});
|
|
authorize(actor, "update", group);
|
|
|
|
if (group.externalGroups?.length) {
|
|
throw ValidationError(
|
|
"This group is managed by an external provider and its membership cannot be modified"
|
|
);
|
|
}
|
|
|
|
const [groupUser, created] = await GroupUser.findOrCreateWithCtx(
|
|
ctx,
|
|
{
|
|
where: {
|
|
groupId: group.id,
|
|
userId: user.id,
|
|
},
|
|
defaults: {
|
|
createdById: actor.id,
|
|
permission: permission ?? GroupPermission.Member,
|
|
},
|
|
},
|
|
{ name: "add_user" }
|
|
);
|
|
|
|
// If the user already exists in the group, update the permission if provided
|
|
if (permission !== undefined && groupUser.permission !== permission) {
|
|
await groupUser.updateWithCtx(ctx, { permission });
|
|
}
|
|
|
|
if (created) {
|
|
await group.reload({ transaction });
|
|
}
|
|
|
|
groupUser.user = user;
|
|
|
|
ctx.body = {
|
|
data: {
|
|
users: [presentUser(user)],
|
|
groupMemberships: [presentGroupUser(groupUser, { includeUser: true })],
|
|
groups: [await presentGroup(group)],
|
|
},
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.remove_user",
|
|
auth(),
|
|
validate(T.GroupsRemoveUserSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsRemoveUserReq>) => {
|
|
const { id, userId } = ctx.input.body;
|
|
const actor = ctx.state.auth.user;
|
|
const { transaction } = ctx.state;
|
|
|
|
const group = await Group.findByPk(id, {
|
|
transaction,
|
|
include: [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: actor.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
],
|
|
});
|
|
authorize(actor, "update", group);
|
|
|
|
if (group.externalGroups?.length) {
|
|
throw ValidationError(
|
|
"This group is managed by an external provider and its membership cannot be modified"
|
|
);
|
|
}
|
|
|
|
const user = await User.findByPk(userId, { transaction });
|
|
authorize(actor, "read", user);
|
|
|
|
const groupUser = await GroupUser.unscoped().findOne({
|
|
where: {
|
|
groupId: group.id,
|
|
userId: user.id,
|
|
},
|
|
transaction,
|
|
lock: transaction.LOCK.UPDATE,
|
|
});
|
|
|
|
if (groupUser) {
|
|
await groupUser.destroyWithCtx(ctx, { name: "remove_user" });
|
|
await group.reload({ transaction });
|
|
}
|
|
|
|
ctx.body = {
|
|
data: {
|
|
groups: [await presentGroup(group)],
|
|
},
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"groups.update_user",
|
|
auth(),
|
|
validate(T.GroupsUpdateUserSchema),
|
|
transaction(),
|
|
async (ctx: APIContext<T.GroupsUpdateUserReq>) => {
|
|
const { id, userId, permission } = ctx.input.body;
|
|
const actor = ctx.state.auth.user;
|
|
const { transaction } = ctx.state;
|
|
|
|
// Load group with group users for authorization
|
|
const group = await Group.findByPk(id, {
|
|
transaction,
|
|
include: [
|
|
{
|
|
model: GroupUser,
|
|
as: "groupUsers",
|
|
required: false,
|
|
where: {
|
|
userId: actor.id,
|
|
},
|
|
},
|
|
externalGroupInclude,
|
|
],
|
|
});
|
|
authorize(actor, "update", group);
|
|
|
|
if (group.externalGroups?.length) {
|
|
throw ValidationError(
|
|
"This group is managed by an external provider and its membership cannot be modified"
|
|
);
|
|
}
|
|
|
|
const user = await User.findByPk(userId, { transaction });
|
|
authorize(actor, "read", user);
|
|
|
|
const groupUser = await GroupUser.unscoped().findOne({
|
|
where: {
|
|
groupId: group.id,
|
|
userId: user.id,
|
|
},
|
|
transaction,
|
|
rejectOnEmpty: true,
|
|
lock: {
|
|
level: transaction.LOCK.UPDATE,
|
|
of: GroupUser,
|
|
},
|
|
});
|
|
|
|
await groupUser.updateWithCtx(ctx, { permission });
|
|
groupUser.user = user;
|
|
|
|
ctx.body = {
|
|
data: {
|
|
users: [presentUser(user)],
|
|
groupMemberships: [presentGroupUser(groupUser, { includeUser: true })],
|
|
groups: [await presentGroup(group)],
|
|
},
|
|
};
|
|
}
|
|
);
|
|
|
|
export default router;
|