mirror of
https://github.com/outline/outline.git
synced 2026-11-30 17:10:36 +03:00
670 lines
17 KiB
TypeScript
670 lines
17 KiB
TypeScript
import Router from "@koa/router";
|
|
import type { WhereOptions } from "sequelize";
|
|
import { Op, Sequelize } from "sequelize";
|
|
import { NotificationEventType, UserRole } from "@shared/types";
|
|
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
|
|
import { settingsPath } from "@shared/utils/routeHelpers";
|
|
import { UserValidation } from "@shared/validations";
|
|
import userInviter from "@server/commands/userInviter";
|
|
import ConfirmUpdateEmail from "@server/emails/templates/ConfirmUpdateEmail";
|
|
import ConfirmUserDeleteEmail from "@server/emails/templates/ConfirmUserDeleteEmail";
|
|
import InviteEmail from "@server/emails/templates/InviteEmail";
|
|
import env from "@server/env";
|
|
import { AuthorizationError, ValidationError } from "@server/errors";
|
|
import logger from "@server/logging/Logger";
|
|
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 { GroupUser, User, Team } from "@server/models";
|
|
import {
|
|
buildWhere,
|
|
combineFilters,
|
|
hasFieldInFilter,
|
|
legacyUserParamsToFilter,
|
|
} from "@server/models/helpers/Filters";
|
|
import { UserFlag } from "@server/models/User";
|
|
import { can, authorize } from "@server/policies";
|
|
import { presentUser, presentPolicies } from "@server/presenters";
|
|
import type { Context } from "@server/types";
|
|
import { AuthenticationType } from "@server/types";
|
|
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
|
|
import { safeEqual } from "@server/utils/crypto";
|
|
import { QueryHelper } from "@server/storage/QueryHelper";
|
|
import { getDetailsForEmailUpdateToken } from "@server/utils/jwt";
|
|
import pagination from "../middlewares/pagination";
|
|
import * as T from "./schema";
|
|
|
|
const router = new Router();
|
|
|
|
router.post(
|
|
"users.list",
|
|
auth(),
|
|
pagination(),
|
|
validate(T.UsersListSchema),
|
|
async (ctx: Context<T.UsersListReq>) => {
|
|
const {
|
|
sort,
|
|
direction,
|
|
query,
|
|
role,
|
|
filter: statusFilter,
|
|
ids,
|
|
emails,
|
|
filters: rawFilters,
|
|
} = ctx.input.body;
|
|
|
|
const actor = ctx.auth.user;
|
|
authorize(actor, "listUsers", actor.team);
|
|
|
|
const where: WhereOptions<User> & {
|
|
[Op.and]: WhereOptions<User>[];
|
|
} = {
|
|
teamId: actor.teamId,
|
|
[Op.and]: [],
|
|
};
|
|
|
|
// The schema rejects callers that combine `filters` with the deprecated
|
|
// top-level params, so exactly one of these is set.
|
|
const filter =
|
|
combineFilters(rawFilters) ??
|
|
legacyUserParamsToFilter({
|
|
ids,
|
|
emails,
|
|
role,
|
|
status: statusFilter,
|
|
isAdmin: actor.isAdmin,
|
|
});
|
|
|
|
// Suspended users are only ever visible to admins, and then only when the
|
|
// request targets a specific status or references suspendedAt itself.
|
|
const includeSuspended =
|
|
actor.isAdmin &&
|
|
(!!statusFilter ||
|
|
(filter !== undefined && hasFieldInFilter(filter, "suspendedAt")));
|
|
if (!includeSuspended) {
|
|
where[Op.and].push({ suspendedAt: { [Op.is]: null } });
|
|
}
|
|
|
|
// Filtering or sorting by email would reveal addresses the actor may not see.
|
|
const canReadEmails = can(actor, "readEmail", actor.team);
|
|
if (
|
|
!canReadEmails &&
|
|
(sort === "email" ||
|
|
(filter !== undefined && hasFieldInFilter(filter, "email")))
|
|
) {
|
|
throw AuthorizationError();
|
|
}
|
|
|
|
if (filter) {
|
|
where[Op.and].push(buildWhere<User>(filter));
|
|
}
|
|
|
|
if (query) {
|
|
where[Op.and].push({
|
|
[Op.or]: [
|
|
...(canReadEmails
|
|
? [
|
|
Sequelize.literal(
|
|
`unaccent(LOWER("user"."email")) like unaccent(LOWER(:query))`
|
|
),
|
|
]
|
|
: []),
|
|
Sequelize.literal(
|
|
`unaccent(LOWER("user"."name")) like unaccent(LOWER(:query))`
|
|
),
|
|
],
|
|
});
|
|
}
|
|
|
|
const replacements = { query: QueryHelper.likeContains(query ?? "") };
|
|
|
|
const [users, total] = await Promise.all([
|
|
User.findAll({
|
|
where,
|
|
replacements,
|
|
// Only admins can see who invited a user.
|
|
include: actor.isAdmin
|
|
? [{ association: "invitedBy", required: false }]
|
|
: undefined,
|
|
order: [[sort, direction]],
|
|
offset: ctx.state.pagination.offset,
|
|
limit: ctx.state.pagination.limit,
|
|
}),
|
|
User.count({
|
|
where,
|
|
replacements,
|
|
}),
|
|
]);
|
|
|
|
ctx.body = {
|
|
pagination: { ...ctx.state.pagination, total },
|
|
data: users.map((user) =>
|
|
presentUser(user, {
|
|
includeEmail: !!can(actor, "readEmail", user),
|
|
includeDetails: !!can(actor, "readDetails", user),
|
|
})
|
|
),
|
|
policies: presentPolicies(actor, users),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.info",
|
|
auth(),
|
|
validate(T.UsersInfoSchema),
|
|
async (ctx: Context<T.UsersInfoReq>) => {
|
|
const { id } = ctx.input.body;
|
|
const actor = ctx.auth.user;
|
|
const user = id ? await User.findByPk(id) : actor;
|
|
authorize(actor, "read", user);
|
|
const includeDetails = !!can(actor, "readDetails", user);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, {
|
|
includeDetails,
|
|
}),
|
|
policies: presentPolicies(actor, [user]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.updateEmail",
|
|
rateLimiter(RateLimiterStrategy.TenPerHour),
|
|
auth({ type: AuthenticationType.APP }),
|
|
validate(T.UsersUpdateEmailSchema),
|
|
async (ctx: Context<T.UsersUpdateEmailReq>) => {
|
|
if (!env.EMAIL_ENABLED) {
|
|
throw ValidationError("Email support is not set up for this instance");
|
|
}
|
|
|
|
const { user: actor } = ctx.auth;
|
|
const { id } = ctx.input.body;
|
|
const { team } = actor;
|
|
const user = id ? await User.findByPk(id) : actor;
|
|
const email = ctx.input.body.email.trim().toLowerCase();
|
|
|
|
authorize(actor, "update", user);
|
|
|
|
// Check if email domain is allowed
|
|
if (!(await team.isDomainAllowed(email))) {
|
|
throw ValidationError("The domain is not allowed for this workspace");
|
|
}
|
|
|
|
// Check if email already exists in workspace
|
|
if (await User.findByEmail(ctx, email)) {
|
|
throw ValidationError("User with email already exists");
|
|
}
|
|
|
|
await new ConfirmUpdateEmail({
|
|
to: email,
|
|
language: user.language,
|
|
previous: user.email,
|
|
code: user.getEmailUpdateToken(email),
|
|
teamUrl: team.url,
|
|
}).schedule();
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.get(
|
|
"users.updateEmail",
|
|
rateLimiter(RateLimiterStrategy.TenPerHour),
|
|
auth({ type: AuthenticationType.APP }),
|
|
transaction(),
|
|
validate(T.UsersUpdateEmailConfirmSchema),
|
|
async (ctx: Context<T.UsersUpdateEmailConfirmReq>) => {
|
|
if (!env.EMAIL_ENABLED) {
|
|
throw ValidationError("Email support is not set up for this instance");
|
|
}
|
|
|
|
const { transaction } = ctx;
|
|
const { code, follow } = ctx.input.query;
|
|
|
|
// The link in the email does not include the follow query param, this
|
|
// is to help prevent anti-virus, and email clients from pre-fetching the link
|
|
if (!follow) {
|
|
return ctx.redirectOnClient(ctx.request.href + "&follow=true");
|
|
}
|
|
let user: User;
|
|
let email: string;
|
|
|
|
try {
|
|
const res = await getDetailsForEmailUpdateToken(code as string, {
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
user = res.user;
|
|
email = res.email;
|
|
} catch (_err) {
|
|
ctx.redirect(`/?notice=expired-token`);
|
|
return;
|
|
}
|
|
|
|
const { user: actor } = ctx.auth;
|
|
authorize(actor, "update", user);
|
|
|
|
// Check if email domain is allowed
|
|
if (!(await actor.team.isDomainAllowed(email))) {
|
|
throw ValidationError("The domain is not allowed for this workspace");
|
|
}
|
|
|
|
// Check if email already exists in workspace
|
|
if (await User.findByEmail(ctx, email)) {
|
|
throw ValidationError("User with email already exists");
|
|
}
|
|
|
|
await user.updateWithCtx(ctx, { email });
|
|
|
|
ctx.redirect(settingsPath());
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.update",
|
|
auth(),
|
|
validate(T.UsersUpdateSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersUpdateReq>) => {
|
|
const { auth, transaction } = ctx;
|
|
const actor = auth.user;
|
|
const { id, name, avatarUrl, language, preferences, timezone } =
|
|
ctx.input.body;
|
|
|
|
let user: User | null = actor;
|
|
if (id) {
|
|
user = await User.findByPk(id, {
|
|
rejectOnEmpty: true,
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
}
|
|
authorize(actor, "update", user);
|
|
const includeDetails = !!can(actor, "readDetails", user);
|
|
|
|
user.fill({
|
|
name: name || undefined,
|
|
avatarUrl,
|
|
language: language || undefined,
|
|
timezone: timezone || undefined,
|
|
});
|
|
|
|
// Mark that the user has manually changed their avatar
|
|
// This prevents automatic syncing from identity providers
|
|
if (avatarUrl !== undefined) {
|
|
user.setFlag(UserFlag.AvatarUpdated, avatarUrl ? true : false);
|
|
}
|
|
if (preferences) {
|
|
user.preferences = {
|
|
...user.preferences,
|
|
...preferences,
|
|
};
|
|
}
|
|
|
|
await user.saveWithCtx(ctx);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, {
|
|
includeDetails,
|
|
}),
|
|
};
|
|
}
|
|
);
|
|
|
|
// Admin specific
|
|
|
|
router.post(
|
|
"users.update_role",
|
|
auth({ role: UserRole.Admin }),
|
|
validate(T.UsersChangeRoleSchema),
|
|
transaction(),
|
|
updateRole
|
|
);
|
|
|
|
async function updateRole(ctx: Context<T.UsersChangeRoleReq>) {
|
|
const { transaction } = ctx;
|
|
const userId = ctx.input.body.id;
|
|
const role = ctx.input.body.role;
|
|
const actor = ctx.auth.user;
|
|
|
|
const user = await User.findByPk(userId, {
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
authorize(actor, "update", user);
|
|
|
|
const team = await Team.findByPk(user.teamId, {
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
rejectOnEmpty: true,
|
|
});
|
|
|
|
let name;
|
|
|
|
if (user.role === role) {
|
|
throw ValidationError("User is already in that role");
|
|
}
|
|
if (user.id === actor.id) {
|
|
throw ValidationError("You cannot change your own role");
|
|
}
|
|
|
|
if (UserRoleHelper.canDemote(user, role)) {
|
|
name = "demote";
|
|
authorize(actor, "demote", user);
|
|
}
|
|
if (UserRoleHelper.canPromote(user, role)) {
|
|
name = "promote";
|
|
authorize(actor, "promote", user);
|
|
}
|
|
if (role === UserRole.Guest) {
|
|
authorize(actor, "addGuest", actor.team);
|
|
|
|
if (user.email && (await team.isTeamDomain(user.email, { transaction }))) {
|
|
throw ValidationError(
|
|
"Users with an email on a workspace domain cannot be added as guests"
|
|
);
|
|
}
|
|
}
|
|
|
|
await user.updateWithCtx(ctx, { role }, { name });
|
|
|
|
// Guests cannot be members of groups, remove any existing memberships
|
|
if (role === UserRole.Guest) {
|
|
const groupUsers = await GroupUser.unscoped().findAll({
|
|
where: { userId: user.id },
|
|
transaction,
|
|
lock: transaction.LOCK.UPDATE,
|
|
});
|
|
|
|
for (const groupUser of groupUsers) {
|
|
await groupUser.destroyWithCtx(ctx, { name: "remove_user" });
|
|
}
|
|
}
|
|
|
|
const includeDetails = !!can(actor, "readDetails", user);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, {
|
|
includeDetails,
|
|
}),
|
|
policies: presentPolicies(actor, [user]),
|
|
};
|
|
}
|
|
|
|
router.post(
|
|
"users.suspend",
|
|
auth(),
|
|
validate(T.UsersSuspendSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersSuspendReq>) => {
|
|
const { transaction } = ctx;
|
|
const userId = ctx.input.body.id;
|
|
const actor = ctx.auth.user;
|
|
const user = await User.findByPk(userId, {
|
|
rejectOnEmpty: true,
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
authorize(actor, "suspend", user);
|
|
|
|
await user.updateWithCtx(
|
|
ctx,
|
|
{
|
|
suspendedById: actor.id,
|
|
suspendedAt: new Date(),
|
|
},
|
|
{
|
|
name: "suspend",
|
|
}
|
|
);
|
|
const includeDetails = !!can(actor, "readDetails", user);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, {
|
|
includeDetails,
|
|
}),
|
|
policies: presentPolicies(actor, [user]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.activate",
|
|
auth(),
|
|
validate(T.UsersActivateSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersActivateReq>) => {
|
|
const { transaction } = ctx;
|
|
const userId = ctx.input.body.id;
|
|
const actor = ctx.auth.user;
|
|
const user = await User.findByPk(userId, {
|
|
rejectOnEmpty: true,
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
authorize(actor, "activate", user);
|
|
|
|
await user.updateWithCtx(
|
|
ctx,
|
|
{
|
|
suspendedById: null,
|
|
suspendedAt: null,
|
|
},
|
|
{
|
|
name: "activate",
|
|
}
|
|
);
|
|
const includeDetails = !!can(actor, "readDetails", user);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, {
|
|
includeDetails,
|
|
}),
|
|
policies: presentPolicies(actor, [user]),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.invite",
|
|
rateLimiter(RateLimiterStrategy.FiftyPerHour),
|
|
auth(),
|
|
validate(T.UsersInviteSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersInviteReq>) => {
|
|
const { invites, suppressEmail } = ctx.input.body;
|
|
const { user } = ctx.auth;
|
|
|
|
if (invites.length > UserValidation.maxInvitesPerRequest) {
|
|
throw ValidationError(
|
|
`You can only invite up to ${UserValidation.maxInvitesPerRequest} users at a time`
|
|
);
|
|
}
|
|
authorize(user, "inviteUser", user.team);
|
|
|
|
const response = await userInviter(ctx, { invites, suppressEmail });
|
|
|
|
ctx.body = {
|
|
data: {
|
|
sent: response.sent,
|
|
unsent: response.unsent,
|
|
users: response.users.map((invitee) =>
|
|
presentUser(invitee, {
|
|
includeEmail: !!can(user, "readEmail", invitee),
|
|
})
|
|
),
|
|
},
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.resendInvite",
|
|
auth(),
|
|
validate(T.UsersResendInviteSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersResendInviteReq>) => {
|
|
const { id } = ctx.input.body;
|
|
const { auth, transaction } = ctx;
|
|
const actor = auth.user;
|
|
|
|
const user = await User.findByPk(id, {
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
transaction,
|
|
});
|
|
authorize(actor, "resendInvite", user);
|
|
|
|
if (user.getFlag(UserFlag.InviteSent) > 2) {
|
|
throw ValidationError("This invite has been sent too many times");
|
|
}
|
|
|
|
await new InviteEmail({
|
|
to: user.email,
|
|
language: user.language,
|
|
name: user.name,
|
|
actorName: actor.name,
|
|
actorEmail: actor.email,
|
|
teamName: actor.team.name,
|
|
teamUrl: actor.team.url,
|
|
}).schedule();
|
|
|
|
user.incrementFlag(UserFlag.InviteSent);
|
|
await user.save({ transaction });
|
|
|
|
if (env.isDevelopment) {
|
|
logger.info(
|
|
"email",
|
|
`Sign in immediately: ${
|
|
env.URL
|
|
}/auth/email.callback?token=${user.getEmailSigninToken(ctx)}`
|
|
);
|
|
}
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.requestDelete",
|
|
rateLimiter(RateLimiterStrategy.FivePerHour),
|
|
auth(),
|
|
async (ctx: Context) => {
|
|
if (!env.EMAIL_ENABLED) {
|
|
throw ValidationError("Email support is not set up for this instance");
|
|
}
|
|
|
|
const { user } = ctx.auth;
|
|
authorize(user, "delete", user);
|
|
|
|
await new ConfirmUserDeleteEmail({
|
|
to: user.email,
|
|
language: user.language,
|
|
deleteConfirmationCode: user.deleteConfirmationCode,
|
|
teamName: user.team.name,
|
|
teamUrl: user.team.url,
|
|
}).schedule();
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.delete",
|
|
rateLimiter(RateLimiterStrategy.TenPerHour),
|
|
auth(),
|
|
validate(T.UsersDeleteSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersDeleteSchemaReq>) => {
|
|
const { transaction } = ctx;
|
|
const { id, code } = ctx.input.body;
|
|
const actor = ctx.auth.user;
|
|
let user: User;
|
|
|
|
if (id) {
|
|
user = await User.findByPk(id, {
|
|
rejectOnEmpty: true,
|
|
transaction,
|
|
lock: transaction.LOCK.NO_KEY_UPDATE,
|
|
});
|
|
} else {
|
|
user = actor;
|
|
}
|
|
authorize(actor, "delete", user);
|
|
|
|
// If we're attempting to delete our own account then a confirmation code
|
|
// is required. This acts as CSRF protection.
|
|
if ((!id || id === actor.id) && env.EMAIL_ENABLED) {
|
|
const deleteConfirmationCode = user.deleteConfirmationCode;
|
|
|
|
if (!safeEqual(code, deleteConfirmationCode)) {
|
|
throw ValidationError("The confirmation code was incorrect");
|
|
}
|
|
}
|
|
|
|
await user.destroyWithCtx(ctx);
|
|
|
|
ctx.body = {
|
|
success: true,
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.notificationsSubscribe",
|
|
auth(),
|
|
validate(T.UsersNotificationsSubscribeSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersNotificationsSubscribeReq>) => {
|
|
const { eventType } = ctx.input.body;
|
|
const { user } = ctx.auth;
|
|
const eventTypes = eventType
|
|
? [eventType]
|
|
: Object.values(NotificationEventType);
|
|
|
|
for (const type of eventTypes) {
|
|
user.setNotificationEventType(type, true);
|
|
}
|
|
|
|
await user.saveWithCtx(ctx);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, { includeDetails: true }),
|
|
};
|
|
}
|
|
);
|
|
|
|
router.post(
|
|
"users.notificationsUnsubscribe",
|
|
auth(),
|
|
validate(T.UsersNotificationsUnsubscribeSchema),
|
|
transaction(),
|
|
async (ctx: Context<T.UsersNotificationsUnsubscribeReq>) => {
|
|
const { eventType } = ctx.input.body;
|
|
const { user } = ctx.auth;
|
|
const eventTypes = eventType
|
|
? [eventType]
|
|
: Object.values(NotificationEventType);
|
|
|
|
for (const type of eventTypes) {
|
|
user.setNotificationEventType(type, false);
|
|
}
|
|
|
|
await user.saveWithCtx(ctx);
|
|
|
|
ctx.body = {
|
|
data: presentUser(user, { includeDetails: true }),
|
|
};
|
|
}
|
|
);
|
|
|
|
export default router;
|