Merge branch 'main' into feat/dropdown-pagination

This commit is contained in:
CuriousCorrelation committed 2022-07-13 14:54:57 +05:30
commit 64992aab51
18 files changed
+387 -98

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
+11 -2
View File
@@ -4,6 +4,7 @@ import * as React from "react";
import { Helmet } from "react-helmet";
import { RouteComponentProps, useLocation } from "react-router-dom";
import { useTheme } from "styled-components";
import { setCookie } from "tiny-cookie";
import DocumentModel from "~/models/Document";
import Error404 from "~/scenes/Error404";
import ErrorOffline from "~/scenes/ErrorOffline";
@@ -11,7 +12,8 @@ import Layout from "~/components/Layout";
import Sidebar from "~/components/Sidebar/Shared";
import useStores from "~/hooks/useStores";
import { NavigationNode } from "~/types";
import { OfflineError } from "~/utils/errors";
import { AuthorizationError, OfflineError } from "~/utils/errors";
import Login from "../Login";
import Document from "./components/Document";
import Loading from "./components/Loading";
@@ -105,7 +107,14 @@ function SharedDocumentScene(props: Props) {
}, [documents, documentSlug, shareId, ui]);
if (error) {
return error instanceof OfflineError ? <ErrorOffline /> : <Error404 />;
if (error instanceof OfflineError) {
return <ErrorOffline />;
} else if (error instanceof AuthorizationError) {
setCookie("postLoginRedirectPath", props.location.pathname);
return <Login />;
} else {
return <Error404 />;
}
}
if (!response) {
@@ -1,6 +1,9 @@
import { compact } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import useCurrentUser from "~/hooks/useCurrentUser";
type Props = {
activeKey: string;
@@ -9,34 +12,41 @@ type Props = {
const UserStatusFilter = ({ activeKey, onSelect, ...rest }: Props) => {
const { t } = useTranslation();
const user = useCurrentUser();
const options = React.useMemo(
() => [
{
key: "",
label: t("Active"),
},
{
key: "all",
label: t("Everyone"),
},
{
key: "admins",
label: t("Admins"),
},
{
key: "suspended",
label: t("Suspended"),
},
{
key: "invited",
label: t("Invited"),
},
{
key: "viewers",
label: t("Viewers"),
},
],
[t]
() =>
compact([
{
key: "",
label: t("Active"),
},
{
key: "all",
label: t("Everyone"),
},
{
key: "admins",
label: t("Admins"),
},
...(user.isAdmin
? [
{
key: "suspended",
label: t("Suspended"),
},
]
: []),
{
key: "invited",
label: t("Invited"),
},
{
key: "viewers",
label: t("Viewers"),
},
]),
[t, user.isAdmin]
);
return (
@@ -50,4 +60,4 @@ const UserStatusFilter = ({ activeKey, onSelect, ...rest }: Props) => {
);
};
export default UserStatusFilter;
export default observer(UserStatusFilter);
+2 -2
View File
@@ -98,7 +98,7 @@
"fs-extra": "^4.0.2",
"fuzzy-search": "^3.2.1",
"gemoji": "6.x",
"http-errors": "1.4.0",
"http-errors": "2.0.0",
"i18next": "^20.6.1",
"i18next-http-backend": "^1.3.2",
"immutable": "^4.0.0",
@@ -226,7 +226,7 @@
"@types/emoji-regex": "^9.2.0",
"@types/enzyme": "^3.10.10",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@types/formidable": "^2.0.0",
"@types/formidable": "^2.0.5",
"@types/fs-extra": "^9.0.13",
"@types/fuzzy-search": "^2.1.2",
"@types/google.analytics": "^0.0.42",
+36
View File
@@ -0,0 +1,36 @@
import { sequelize } from "@server/database/sequelize";
import { ValidationError } from "@server/errors";
import { Event, User } from "@server/models";
import type { UserRole } from "@server/models/User";
import CleanupDemotedUserTask from "@server/queues/tasks/CleanupDemotedUserTask";
type Props = {
user: User;
actorId: string;
to: UserRole;
ip: string;
};
export default async function userDemoter({ user, actorId, to, ip }: Props) {
if (user.id === actorId) {
throw ValidationError("Unable to demote the current user");
}
return sequelize.transaction(async (transaction) => {
await user.demote(to, { transaction });
await Event.create(
{
name: "users.demote",
actorId,
userId: user.id,
teamId: user.teamId,
data: {
name: user.name,
},
ip,
},
{ transaction }
);
await CleanupDemotedUserTask.schedule({ userId: user.id });
});
}
+3
View File
@@ -1,6 +1,7 @@
import { Transaction } from "sequelize";
import { sequelize } from "@server/database/sequelize";
import { User, Event, GroupUser } from "@server/models";
import CleanupDemotedUserTask from "@server/queues/tasks/CleanupDemotedUserTask";
import { ValidationError } from "../errors";
type Props = {
@@ -49,5 +50,7 @@ export default async function userSuspender({
transaction,
}
);
await CleanupDemotedUserTask.schedule({ userId: user.id });
});
}
+21 -10
View File
@@ -46,6 +46,11 @@ export enum UserFlag {
InviteReminderSent = "inviteReminderSent",
}
export enum UserRole {
Member = "member",
Viewer = "viewer",
}
@Scopes(() => ({
withAuthentications: {
include: [
@@ -373,10 +378,10 @@ class User extends ParanoidModel {
);
};
demote = async (teamId: string, to: "member" | "viewer") => {
demote = async (to: UserRole, options?: SaveOptions<User>) => {
const res = await (this.constructor as typeof User).findAndCountAll({
where: {
teamId,
teamId: this.teamId,
isAdmin: true,
id: {
[Op.ne]: this.id,
@@ -387,15 +392,21 @@ class User extends ParanoidModel {
if (res.count >= 1) {
if (to === "member") {
return this.update({
isAdmin: false,
isViewer: false,
});
return this.update(
{
isAdmin: false,
isViewer: false,
},
options
);
} else if (to === "viewer") {
return this.update({
isAdmin: false,
isViewer: true,
});
return this.update(
{
isAdmin: false,
isViewer: true,
},
options
);
}
return undefined;
+13 -1
View File
@@ -8,6 +8,7 @@ import {
DataType,
IsUrl,
} from "sequelize-typescript";
import { SaveOptions } from "sequelize/types";
import { Event } from "@server/types";
import Team from "./Team";
import User from "./User";
@@ -55,7 +56,18 @@ class WebhookSubscription extends ParanoidModel {
teamId: string;
// methods
validForEvent = (event: Event): bool => {
/**
* Disables the webhook subscription
*
* @param options Save options
* @returns Promise<void>
*/
public async disable(options?: SaveOptions<WebhookSubscription>) {
return this.update({ enabled: false }, options);
}
public validForEvent = (event: Event): bool => {
if (this.events.length === 1 && this.events[0] === "*") {
return true;
}
@@ -0,0 +1,102 @@
import { ApiKey } from "@server/models";
import {
buildUser,
buildApiKey,
buildAdmin,
buildWebhookSubscription,
buildViewer,
} from "@server/test/factories";
import { flushdb } from "@server/test/support";
import CleanupDemotedUserTask from "./CleanupDemotedUserTask";
beforeEach(() => flushdb());
describe("CleanupDemotedUserTask", () => {
it("should delete api keys for suspended user", async () => {
const admin = await buildAdmin();
const user = await buildUser({
teamId: admin.teamId,
suspendedAt: new Date(),
suspendedById: admin.id,
});
const apiKey = await buildApiKey({
userId: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
expect(await ApiKey.findByPk(apiKey.id)).toBeNull();
});
it("should delete api keys for viewer", async () => {
const user = await buildViewer();
const apiKey = await buildApiKey({
userId: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
expect(await ApiKey.findByPk(apiKey.id)).toBeNull();
});
it("should retain api keys for member", async () => {
const user = await buildUser();
const apiKey = await buildApiKey({
userId: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
expect(await ApiKey.findByPk(apiKey.id)).toBeTruthy();
});
it("should disable webhooks for suspended user", async () => {
const admin = await buildAdmin();
const user = await buildUser({
teamId: admin.teamId,
suspendedAt: new Date(),
suspendedById: admin.id,
});
const webhook = await buildWebhookSubscription({
teamId: user.teamId,
createdById: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
await webhook.reload();
expect(webhook.enabled).toEqual(false);
});
it("should disable webhooks for member", async () => {
const admin = await buildAdmin();
const user = await buildUser({
teamId: admin.teamId,
});
const webhook = await buildWebhookSubscription({
teamId: user.teamId,
createdById: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
await webhook.reload();
expect(webhook.enabled).toEqual(false);
});
it("should retain webhooks for admin", async () => {
const user = await buildAdmin();
const webhook = await buildWebhookSubscription({
teamId: user.teamId,
createdById: user.id,
});
const task = new CleanupDemotedUserTask();
await task.perform({ userId: user.id });
await webhook.reload();
expect(webhook.enabled).toEqual(true);
});
});
@@ -0,0 +1,57 @@
import { sequelize } from "@server/database/sequelize";
import Logger from "@server/logging/Logger";
import { WebhookSubscription, ApiKey, User } from "@server/models";
import BaseTask from "./BaseTask";
type Props = {
userId: string;
};
/**
* Task to disable mechanisms for exporting data from a suspended or demoted user,
* currently this is done by destroying associated Api Keys and disabling webhooks.
*/
export default class CleanupDemotedUserTask extends BaseTask<Props> {
public async perform(props: Props) {
await sequelize.transaction(async (transaction) => {
const user = await User.findByPk(props.userId, { rejectOnEmpty: true });
if (user.isSuspended || !user.isAdmin) {
const subscriptions = await WebhookSubscription.findAll({
where: {
createdById: props.userId,
enabled: true,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
await Promise.all(
subscriptions.map((subscription) =>
subscription.disable({ transaction })
)
);
Logger.info(
"task",
`Disabled ${subscriptions.length} webhooks for user ${props.userId}`
);
}
if (user.isSuspended || user.isViewer) {
const apiKeys = await ApiKey.findAll({
where: {
userId: props.userId,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
await Promise.all(
apiKeys.map((apiKey) => apiKey.destroy({ transaction }))
);
Logger.info(
"task",
`Destroyed ${apiKeys.length} api keys for user ${props.userId}`
);
}
});
}
}
+1 -1
View File
@@ -586,7 +586,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
if (recentDeliveries.length === 25 && allFailed) {
// If the last 25 deliveries failed, disable the subscription
await subscription.update({ enabled: false });
await subscription.disable();
// Send an email to the creator of the webhook to let them know
const [createdBy, team] = await Promise.all([
@@ -166,10 +166,10 @@ Object {
}
`;
exports[`#users.demote should not demote admins if only one available 1`] = `
exports[`#users.demote should not allow demoting self 1`] = `
Object {
"error": "validation_error",
"message": "At least one admin is required",
"message": "Unable to demote the current user",
"ok": false,
"status": 400,
}
+20 -4
View File
@@ -39,9 +39,26 @@ describe("#users.list", () => {
});
it("should allow filtering to suspended users", async () => {
const user = await buildUser({
const admin = await buildAdmin();
await buildUser({
name: "Tester",
teamId: admin.teamId,
suspendedAt: new Date(),
});
const res = await server.post("/api/users.list", {
body: {
query: "test",
filter: "suspended",
token: admin.getJwtToken(),
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
});
it("should not allow members to view suspended users", async () => {
const user = await buildUser();
await buildUser({
name: "Tester",
teamId: user.teamId,
@@ -50,13 +67,12 @@ describe("#users.list", () => {
const res = await server.post("/api/users.list", {
body: {
query: "test",
filter: "suspended",
token: user.getJwtToken(),
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
expect(body.data.length).toEqual(0);
});
it("should allow filtering to invited", async () => {
@@ -467,7 +483,7 @@ describe("#users.demote", () => {
expect(body).toMatchSnapshot();
});
it("should not demote admins if only one available", async () => {
it("should not allow demoting self", async () => {
const admin = await buildAdmin();
const res = await server.post("/api/users.demote", {
body: {
+33 -20
View File
@@ -1,5 +1,6 @@
import Router from "koa-router";
import { Op, WhereOptions } from "sequelize";
import userDemoter from "@server/commands/userDemoter";
import userDestroyer from "@server/commands/userDestroyer";
import userInviter from "@server/commands/userInviter";
import userSuspender from "@server/commands/userSuspender";
@@ -10,7 +11,7 @@ import { ValidationError } from "@server/errors";
import logger from "@server/logging/Logger";
import auth from "@server/middlewares/authentication";
import { Event, User, Team } from "@server/models";
import { UserFlag } from "@server/models/User";
import { UserFlag, UserRole } from "@server/models/User";
import { can, authorize } from "@server/policies";
import { presentUser, presentPolicies } from "@server/presenters";
import {
@@ -44,6 +45,16 @@ router.post("users.list", auth(), pagination(), async (ctx) => {
teamId: actor.teamId,
};
// Filter out suspended users if we're not an admin
if (!actor.isAdmin) {
where = {
...where,
suspendedAt: {
[Op.eq]: null,
},
};
}
switch (filter) {
case "invited": {
where = { ...where, lastActiveAt: null };
@@ -61,12 +72,14 @@ router.post("users.list", auth(), pagination(), async (ctx) => {
}
case "suspended": {
where = {
...where,
suspendedAt: {
[Op.ne]: null,
},
};
if (actor.isAdmin) {
where = {
...where,
suspendedAt: {
[Op.ne]: null,
},
};
}
break;
}
@@ -211,23 +224,21 @@ router.post("users.promote", auth(), async (ctx) => {
router.post("users.demote", auth(), async (ctx) => {
const userId = ctx.body.id;
const teamId = ctx.state.user.teamId;
let { to } = ctx.body;
const actor = ctx.state.user;
const actor = ctx.state.user as User;
assertPresent(userId, "id is required");
to = to === "viewer" ? "viewer" : "member";
const user = await User.findByPk(userId);
to = (to === "viewer" ? "viewer" : "member") as UserRole;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
});
authorize(actor, "demote", user);
await user.demote(teamId, to);
await Event.create({
name: "users.demote",
await userDemoter({
to,
user,
actorId: actor.id,
userId,
teamId,
data: {
name: user.name,
},
ip: ctx.request.ip,
});
const includeDetails = can(actor, "readDetails", user);
@@ -244,7 +255,9 @@ router.post("users.suspend", auth(), async (ctx) => {
const userId = ctx.body.id;
const actor = ctx.state.user;
assertPresent(userId, "id is required");
const user = await User.findByPk(userId);
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
});
authorize(actor, "suspend", user);
await userSuspender({
+13
View File
@@ -16,6 +16,7 @@ import {
FileOperation,
WebhookSubscription,
WebhookDelivery,
ApiKey,
} from "@server/models";
import {
FileOperationState,
@@ -24,6 +25,18 @@ import {
let count = 1;
export async function buildApiKey(overrides: Partial<ApiKey> = {}) {
if (!overrides.userId) {
const user = await buildUser();
overrides.userId = user.id;
}
return ApiKey.create({
name: "My API Key",
...overrides,
});
}
export async function buildShare(overrides: Partial<Share> = {}) {
if (!overrides.teamId) {
const team = await buildTeam();
+1
View File
@@ -226,6 +226,7 @@ export const getSignedUrl = async (key: string, expiresInMs = 60) => {
Bucket: AWS_S3_UPLOAD_BUCKET_NAME,
Key: key,
Expires: expiresInMs,
ResponseContentDisposition: "attachment",
};
const url = isDocker
+1 -1
View File
@@ -119,7 +119,7 @@ const downloadImageNode = async (node: ProsemirrorNode) => {
const image = await fetch(node.attrs.src);
const imageBlob = await image.blob();
const imageURL = URL.createObjectURL(imageBlob);
const extension = imageBlob.type.split("/")[1];
const extension = imageBlob.type.split(/\/|\+/g)[1];
const potentialName = node.attrs.alt || "image";
// create a temporary link node and click it with our image data
+22 -27
View File
@@ -2523,10 +2523,10 @@
"@types/events" "*"
"@types/node" "*"
"@types/formidable@^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@types/formidable/-/formidable-2.0.0.tgz#7100d6121871c6300e16c89cf4002f3b66157359"
integrity sha512-oqgX7AxK7R+NxI2kEGHV2ZqKHJ2MgGOSp2rZxpq2DMrX59h5FVkEJpUhscvqMktDCY3CQ1uqIdC+heVmJ0xTbg==
"@types/formidable@^2.0.5":
version "2.0.5"
resolved "https://registry.yarnpkg.com/@types/formidable/-/formidable-2.0.5.tgz#e54e31d242ef750ac2d05aa163fa0274c8e6ef9c"
integrity sha512-uvMcdn/KK3maPOaVUAc3HEYbCEhjaGFwww4EsX6IJfWIJ1tzHtDHczuImH3GKdusPnAAmzB07St90uabZeCKPA==
dependencies:
"@types/node" "*"
@@ -6100,7 +6100,7 @@ denque@^1.1.0, denque@^1.5.0:
resolved "https://registry.yarnpkg.com/denque/-/denque-1.5.0.tgz#773de0686ff2d8ec2ff92914316a47b73b1c73de"
integrity sha512-CYiCSgIF1p6EUByQPlGkKnP1M9g0ZV3qMIrqMqZqdwazygIA/YP2vrbcyl1h/WppKJTdl1F85cXIle+394iDAQ==
depd@^2.0.0, depd@~2.0.0:
depd@2.0.0, depd@^2.0.0, depd@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df"
integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==
@@ -8189,14 +8189,6 @@ http-cache-semantics@^4.0.0:
resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz#49e91c5cbf36c9b94bcfcd71c23d5249ec74e390"
integrity sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==
http-errors@1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.4.0.tgz#6c0242dea6b3df7afda153c71089b31c6e82aabf"
integrity sha1-bAJC3qaz33r9oVPHEImzHG6Cqr8=
dependencies:
inherits "2.0.1"
statuses ">= 1.2.1 < 2"
http-errors@1.7.3, http-errors@~1.7.2:
version "1.7.3"
resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.7.3.tgz#6c619e4f9c60308c38519498c14fbb10aacebb06"
@@ -8208,6 +8200,17 @@ http-errors@1.7.3, http-errors@~1.7.2:
statuses ">= 1.5.0 < 2"
toidentifier "1.0.0"
http-errors@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3"
integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==
dependencies:
depd "2.0.0"
inherits "2.0.4"
setprototypeof "1.2.0"
statuses "2.0.1"
toidentifier "1.0.1"
http-errors@^1.3.1, http-errors@^1.6.1, http-errors@^1.6.3, http-errors@^1.7.3, http-errors@^1.8.0:
version "1.8.1"
resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.8.1.tgz#7c3f28577cbc8a207388455dbd62295ed07bd68c"
@@ -9792,14 +9795,6 @@ koa-compress@^5.1.0:
koa-is-json "^1.0.0"
statuses "^2.0.1"
koa-convert@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/koa-convert/-/koa-convert-1.2.0.tgz#da40875df49de0539098d1700b50820cebcd21d0"
integrity sha1-2kCHXfSd4FOQmNFwC1CCDOvNIdA=
dependencies:
co "^4.6.0"
koa-compose "^3.0.0"
koa-convert@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/koa-convert/-/koa-convert-2.0.0.tgz#86a0c44d81d40551bae22fee6709904573eea4f5"
@@ -13790,16 +13785,16 @@ static-extend@^0.1.1:
define-property "^0.2.5"
object-copy "^0.1.0"
"statuses@>= 1.2.1 < 2", "statuses@>= 1.4.0 < 2", "statuses@>= 1.5.0 < 2", statuses@^1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c"
integrity sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=
statuses@^2.0.1:
statuses@2.0.1, statuses@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63"
integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==
"statuses@>= 1.4.0 < 2", "statuses@>= 1.5.0 < 2", statuses@^1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c"
integrity sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=
stoppable@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/stoppable/-/stoppable-1.1.0.tgz#32da568e83ea488b08e4d7ea2c3bcc9d75015d5b"