Improve validation on api/users endpoints (#5752)

This commit is contained in:
Tom Moor
2023-08-31 18:06:18 -04:00
committed by GitHub
parent dec03b9d84
commit 7abb4f9ad6
15 changed files with 395 additions and 309 deletions

View File

@@ -1,5 +1,6 @@
import * as React from "react"; import * as React from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { UserRole } from "@shared/types";
import User from "~/models/User"; import User from "~/models/User";
import ConfirmationDialog from "~/components/ConfirmationDialog"; import ConfirmationDialog from "~/components/ConfirmationDialog";
import Input from "~/components/Input"; import Input from "~/components/Input";
@@ -15,7 +16,7 @@ export function UserChangeToViewerDialog({ user, onSubmit }: Props) {
const { users } = useStores(); const { users } = useStores();
const handleSubmit = async () => { const handleSubmit = async () => {
await users.demote(user, "viewer"); await users.demote(user, UserRole.Viewer);
onSubmit(); onSubmit();
}; };
@@ -41,7 +42,7 @@ export function UserChangeToMemberDialog({ user, onSubmit }: Props) {
const { users } = useStores(); const { users } = useStores();
const handleSubmit = async () => { const handleSubmit = async () => {
await users.demote(user, "member"); await users.demote(user, UserRole.Member);
onSubmit(); onSubmit();
}; };

View File

@@ -7,8 +7,9 @@ import {
NotificationEventType, NotificationEventType,
UserPreference, UserPreference,
UserPreferences, UserPreferences,
UserRole,
} from "@shared/types"; } from "@shared/types";
import type { Role, NotificationSettings } from "@shared/types"; import type { NotificationSettings } from "@shared/types";
import { client } from "~/utils/ApiClient"; import { client } from "~/utils/ApiClient";
import ParanoidModel from "./ParanoidModel"; import ParanoidModel from "./ParanoidModel";
import Field from "./decorators/Field"; import Field from "./decorators/Field";
@@ -74,13 +75,13 @@ class User extends ParanoidModel {
} }
@computed @computed
get role(): Role { get role(): UserRole {
if (this.isAdmin) { if (this.isAdmin) {
return "admin"; return UserRole.Admin;
} else if (this.isViewer) { } else if (this.isViewer) {
return "viewer"; return UserRole.Viewer;
} else { } else {
return "member"; return UserRole.Member;
} }
} }

View File

@@ -5,7 +5,7 @@ import { useTranslation, Trans } from "react-i18next";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import styled from "styled-components"; import styled from "styled-components";
import { s } from "@shared/styles"; import { s } from "@shared/styles";
import { Role } from "@shared/types"; import { UserRole } from "@shared/types";
import { UserValidation } from "@shared/validations"; import { UserValidation } from "@shared/validations";
import Button from "~/components/Button"; import Button from "~/components/Button";
import CopyToClipboard from "~/components/CopyToClipboard"; import CopyToClipboard from "~/components/CopyToClipboard";
@@ -28,7 +28,7 @@ type Props = {
type InviteRequest = { type InviteRequest = {
email: string; email: string;
name: string; name: string;
role: Role; role: UserRole;
}; };
function Invite({ onSubmit }: Props) { function Invite({ onSubmit }: Props) {
@@ -38,17 +38,17 @@ function Invite({ onSubmit }: Props) {
{ {
email: "", email: "",
name: "", name: "",
role: "member", role: UserRole.Member,
}, },
{ {
email: "", email: "",
name: "", name: "",
role: "member", role: UserRole.Member,
}, },
{ {
email: "", email: "",
name: "", name: "",
role: "member", role: UserRole.Member,
}, },
]); ]);
const { users } = useStores(); const { users } = useStores();
@@ -65,7 +65,7 @@ function Invite({ onSubmit }: Props) {
setIsSaving(true); setIsSaving(true);
try { try {
const data = await users.invite(invites); const data = await users.invite(invites.filter((i) => i.email));
onSubmit(); onSubmit();
if (data.sent.length > 0) { if (data.sent.length > 0) {
@@ -113,7 +113,7 @@ function Invite({ onSubmit }: Props) {
newInvites.push({ newInvites.push({
email: "", email: "",
name: "", name: "",
role: "member", role: UserRole.Member,
}); });
return newInvites; return newInvites;
}); });
@@ -138,13 +138,16 @@ function Invite({ onSubmit }: Props) {
}); });
}, [showToast, t]); }, [showToast, t]);
const handleRoleChange = React.useCallback((role: Role, index: number) => { const handleRoleChange = React.useCallback(
setInvites((prevInvites) => { (role: UserRole, index: number) => {
const newInvites = [...prevInvites]; setInvites((prevInvites) => {
newInvites[index]["role"] = role; const newInvites = [...prevInvites];
return newInvites; newInvites[index]["role"] = role;
}); return newInvites;
}, []); });
},
[]
);
return ( return (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
@@ -224,7 +227,7 @@ function Invite({ onSubmit }: Props) {
flex flex
/> />
<InputSelectRole <InputSelectRole
onChange={(role: Role) => handleRoleChange(role, index)} onChange={(role: UserRole) => handleRoleChange(role, index)}
value={invite.role} value={invite.role}
labelHidden={index !== 0} labelHidden={index !== 0}
short short

View File

@@ -39,8 +39,8 @@ function Members() {
const [totalPages, setTotalPages] = React.useState(0); const [totalPages, setTotalPages] = React.useState(0);
const [userIds, setUserIds] = React.useState<string[]>([]); const [userIds, setUserIds] = React.useState<string[]>([]);
const can = usePolicy(team); const can = usePolicy(team);
const query = params.get("query") || ""; const query = params.get("query") || undefined;
const filter = params.get("filter") || ""; const filter = params.get("filter") || undefined;
const sort = params.get("sort") || "name"; const sort = params.get("sort") || "name";
const direction = (params.get("direction") || "asc").toUpperCase() as const direction = (params.get("direction") || "asc").toUpperCase() as
| "ASC" | "ASC"
@@ -176,11 +176,14 @@ function Members() {
<Flex gap={8}> <Flex gap={8}>
<InputSearch <InputSearch
short short
value={query} value={query ?? ""}
placeholder={`${t("Filter")}`} placeholder={`${t("Filter")}`}
onChange={handleSearch} onChange={handleSearch}
/> />
<LargeUserStatusFilter activeKey={filter} onSelect={handleFilter} /> <LargeUserStatusFilter
activeKey={filter ?? ""}
onSelect={handleFilter}
/>
</Flex> </Flex>
<PeopleTable <PeopleTable
data={data} data={data}

View File

@@ -2,7 +2,7 @@ import invariant from "invariant";
import filter from "lodash/filter"; import filter from "lodash/filter";
import orderBy from "lodash/orderBy"; import orderBy from "lodash/orderBy";
import { observable, computed, action, runInAction } from "mobx"; import { observable, computed, action, runInAction } from "mobx";
import { Role } from "@shared/types"; import { UserRole } from "@shared/types";
import User from "~/models/User"; import User from "~/models/User";
import { client } from "~/utils/ApiClient"; import { client } from "~/utils/ApiClient";
import BaseStore from "./BaseStore"; import BaseStore from "./BaseStore";
@@ -82,15 +82,15 @@ export default class UsersStore extends BaseStore<User> {
@action @action
promote = async (user: User) => { promote = async (user: User) => {
try { try {
this.updateCounts("admin", user.role); this.updateCounts(UserRole.Admin, user.role);
await this.actionOnUser("promote", user); await this.actionOnUser("promote", user);
} catch { } catch {
this.updateCounts(user.role, "admin"); this.updateCounts(user.role, UserRole.Admin);
} }
}; };
@action @action
demote = async (user: User, to: Role) => { demote = async (user: User, to: UserRole) => {
try { try {
this.updateCounts(to, user.role); this.updateCounts(to, user.role);
await this.actionOnUser("demote", user, to); await this.actionOnUser("demote", user, to);
@@ -128,7 +128,7 @@ export default class UsersStore extends BaseStore<User> {
invites: { invites: {
email: string; email: string;
name: string; name: string;
role: Role; role: UserRole;
}[] }[]
) => { ) => {
const res = await client.post(`/users.invite`, { const res = await client.post(`/users.invite`, {
@@ -206,29 +206,29 @@ export default class UsersStore extends BaseStore<User> {
} }
@action @action
updateCounts = (to: Role, from: Role) => { updateCounts = (to: UserRole, from: UserRole) => {
if (to === "admin") { if (to === UserRole.Admin) {
this.counts.admins += 1; this.counts.admins += 1;
if (from === "viewer") { if (from === UserRole.Viewer) {
this.counts.viewers -= 1; this.counts.viewers -= 1;
} }
} }
if (to === "viewer") { if (to === UserRole.Viewer) {
this.counts.viewers += 1; this.counts.viewers += 1;
if (from === "admin") { if (from === UserRole.Admin) {
this.counts.admins -= 1; this.counts.admins -= 1;
} }
} }
if (to === "member") { if (to === UserRole.Member) {
if (from === "viewer") { if (from === UserRole.Viewer) {
this.counts.viewers -= 1; this.counts.viewers -= 1;
} }
if (from === "admin") { if (from === UserRole.Admin) {
this.counts.admins -= 1; this.counts.admins -= 1;
} }
} }
@@ -296,7 +296,7 @@ export default class UsersStore extends BaseStore<User> {
return queriedUsers(users, query); return queriedUsers(users, query);
}; };
actionOnUser = async (action: string, user: User, to?: Role) => { actionOnUser = async (action: string, user: User, to?: UserRole) => {
const res = await client.post(`/users.${action}`, { const res = await client.post(`/users.${action}`, {
id: user.id, id: user.id,
to, to,

View File

@@ -1,6 +1,5 @@
import { CollectionPermission } from "@shared/types"; import { CollectionPermission, UserRole } from "@shared/types";
import { CollectionUser } from "@server/models"; import { CollectionUser } from "@server/models";
import { UserRole } from "@server/models/User";
import { buildUser, buildAdmin, buildCollection } from "@server/test/factories"; import { buildUser, buildAdmin, buildCollection } from "@server/test/factories";
import { setupTestDatabase } from "@server/test/support"; import { setupTestDatabase } from "@server/test/support";
import userDemoter from "./userDemoter"; import userDemoter from "./userDemoter";

View File

@@ -1,6 +1,6 @@
import { UserRole } from "@shared/types";
import { ValidationError } from "@server/errors"; import { ValidationError } from "@server/errors";
import { Event, User } from "@server/models"; import { Event, User } from "@server/models";
import type { UserRole } from "@server/models/User";
import CleanupDemotedUserTask from "@server/queues/tasks/CleanupDemotedUserTask"; import CleanupDemotedUserTask from "@server/queues/tasks/CleanupDemotedUserTask";
import { sequelize } from "@server/storage/database"; import { sequelize } from "@server/storage/database";

View File

@@ -1,3 +1,4 @@
import { UserRole } from "@shared/types";
import { buildUser } from "@server/test/factories"; import { buildUser } from "@server/test/factories";
import { setupTestDatabase } from "@server/test/support"; import { setupTestDatabase } from "@server/test/support";
import userInviter from "./userInviter"; import userInviter from "./userInviter";
@@ -12,7 +13,7 @@ describe("userInviter", () => {
const response = await userInviter({ const response = await userInviter({
invites: [ invites: [
{ {
role: "member", role: UserRole.Member,
email: "test@example.com", email: "test@example.com",
name: "Test", name: "Test",
}, },
@@ -28,7 +29,7 @@ describe("userInviter", () => {
const response = await userInviter({ const response = await userInviter({
invites: [ invites: [
{ {
role: "member", role: UserRole.Member,
email: " ", email: " ",
name: "Test", name: "Test",
}, },
@@ -44,7 +45,7 @@ describe("userInviter", () => {
const response = await userInviter({ const response = await userInviter({
invites: [ invites: [
{ {
role: "member", role: UserRole.Member,
email: "notanemail", email: "notanemail",
name: "Test", name: "Test",
}, },
@@ -60,12 +61,12 @@ describe("userInviter", () => {
const response = await userInviter({ const response = await userInviter({
invites: [ invites: [
{ {
role: "member", role: UserRole.Member,
email: "the@same.com", email: "the@same.com",
name: "Test", name: "Test",
}, },
{ {
role: "member", role: UserRole.Member,
email: "the@SAME.COM", email: "the@SAME.COM",
name: "Test", name: "Test",
}, },
@@ -81,7 +82,7 @@ describe("userInviter", () => {
const response = await userInviter({ const response = await userInviter({
invites: [ invites: [
{ {
role: "member", role: UserRole.Member,
email: user.email!, email: user.email!,
name: user.name, name: user.name,
}, },

View File

@@ -1,5 +1,5 @@
import uniqBy from "lodash/uniqBy"; import uniqBy from "lodash/uniqBy";
import { Role } from "@shared/types"; import { UserRole } from "@shared/types";
import InviteEmail from "@server/emails/templates/InviteEmail"; import InviteEmail from "@server/emails/templates/InviteEmail";
import env from "@server/env"; import env from "@server/env";
import Logger from "@server/logging/Logger"; import Logger from "@server/logging/Logger";
@@ -9,7 +9,7 @@ import { UserFlag } from "@server/models/User";
export type Invite = { export type Invite = {
name: string; name: string;
email: string; email: string;
role: Role; role: UserRole;
}; };
export default async function userInviter({ export default async function userInviter({
@@ -59,8 +59,8 @@ export default async function userInviter({
name: invite.name, name: invite.name,
email: invite.email, email: invite.email,
service: null, service: null,
isAdmin: invite.role === "admin", isAdmin: invite.role === UserRole.Admin,
isViewer: invite.role === "viewer", isViewer: invite.role === UserRole.Viewer,
invitedById: user.id, invitedById: user.id,
flags: { flags: {
[UserFlag.InviteSent]: 1, [UserFlag.InviteSent]: 1,

View File

@@ -31,6 +31,7 @@ import {
UserPreferences, UserPreferences,
NotificationEventType, NotificationEventType,
NotificationEventDefaults, NotificationEventDefaults,
UserRole,
} from "@shared/types"; } from "@shared/types";
import { stringToColor } from "@shared/utils/color"; import { stringToColor } from "@shared/utils/color";
import env from "@server/env"; import env from "@server/env";
@@ -65,11 +66,6 @@ export enum UserFlag {
MobileWeb = "mobileWeb", MobileWeb = "mobileWeb",
} }
export enum UserRole {
Member = "member",
Viewer = "viewer",
}
@Scopes(() => ({ @Scopes(() => ({
withAuthentications: { withAuthentications: {
include: [ include: [
@@ -532,7 +528,7 @@ class User extends ParanoidModel {
}); });
if (res.count >= 1) { if (res.count >= 1) {
if (to === "member") { if (to === UserRole.Member) {
await this.update( await this.update(
{ {
isAdmin: false, isAdmin: false,
@@ -540,7 +536,7 @@ class User extends ParanoidModel {
}, },
options options
); );
} else if (to === "viewer") { } else if (to === UserRole.Viewer) {
await this.update( await this.update(
{ {
isAdmin: false, isAdmin: false,

View File

@@ -1,5 +1,5 @@
import { z } from "zod"; import { z } from "zod";
import { UserRole } from "@server/models/User"; import { UserRole } from "@shared/types";
import BaseSchema from "@server/routes/api/BaseSchema"; import BaseSchema from "@server/routes/api/BaseSchema";
export const TeamsUpdateSchema = BaseSchema.extend({ export const TeamsUpdateSchema = BaseSchema.extend({
@@ -21,10 +21,7 @@ export const TeamsUpdateSchema = BaseSchema.extend({
/** The default landing collection for the team */ /** The default landing collection for the team */
defaultCollectionId: z.string().uuid().nullish(), defaultCollectionId: z.string().uuid().nullish(),
/** The default user role */ /** The default user role */
defaultUserRole: z defaultUserRole: z.nativeEnum(UserRole).optional(),
.string()
.refine((val) => Object.values(UserRole).includes(val as UserRole))
.optional(),
/** Whether new users must be invited to join the team */ /** Whether new users must be invited to join the team */
inviteRequired: z.boolean().optional(), inviteRequired: z.boolean().optional(),
/** Domains allowed to sign-in with SSO */ /** Domains allowed to sign-in with SSO */

View File

@@ -1,7 +1,48 @@
import { z } from "zod"; import { z } from "zod";
import { NotificationEventType, UserPreference } from "@shared/types"; import { NotificationEventType, UserPreference, UserRole } from "@shared/types";
import User from "@server/models/User";
import BaseSchema from "../BaseSchema"; import BaseSchema from "../BaseSchema";
const BaseIdSchema = z.object({
id: z.string().uuid(),
});
export const UsersListSchema = z.object({
body: z.object({
/** Groups sorting direction */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
/** Groups sorting column */
sort: z
.string()
.refine((val) => Object.keys(User.getAttributes()).includes(val), {
message: "Invalid sort parameter",
})
.default("createdAt"),
ids: z.array(z.string().uuid()).optional(),
query: z.string().optional(),
filter: z
.enum([
"invited",
"viewers",
"admins",
"members",
"active",
"all",
"suspended",
])
.optional(),
}),
});
export type UsersListReq = z.infer<typeof UsersListSchema>;
export const UsersNotificationsSubscribeSchema = z.object({ export const UsersNotificationsSubscribeSchema = z.object({
body: z.object({ body: z.object({
eventType: z.nativeEnum(NotificationEventType), eventType: z.nativeEnum(NotificationEventType),
@@ -42,3 +83,58 @@ export const UsersDeleteSchema = BaseSchema.extend({
}); });
export type UsersDeleteSchemaReq = z.infer<typeof UsersDeleteSchema>; export type UsersDeleteSchemaReq = z.infer<typeof UsersDeleteSchema>;
export const UsersInfoSchema = BaseSchema.extend({
body: z.object({
id: z.string().uuid().optional(),
}),
});
export type UsersInfoReq = z.infer<typeof UsersInfoSchema>;
export const UsersActivateSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type UsersActivateReq = z.infer<typeof UsersActivateSchema>;
export const UsersPromoteSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type UsersPromoteReq = z.infer<typeof UsersPromoteSchema>;
export const UsersDemoteSchema = BaseSchema.extend({
body: z.object({
id: z.string().uuid(),
to: z.nativeEnum(UserRole).default(UserRole.Member),
}),
});
export type UsersDemoteReq = z.infer<typeof UsersDemoteSchema>;
export const UsersSuspendSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type UsersSuspendReq = z.infer<typeof UsersSuspendSchema>;
export const UsersResendInviteSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type UsersResendInviteReq = z.infer<typeof UsersResendInviteSchema>;
export const UsersInviteSchema = z.object({
body: z.object({
invites: z.array(
z.object({
email: z.string().email(),
name: z.string(),
role: z.nativeEnum(UserRole),
})
),
}),
});
export type UsersInviteReq = z.infer<typeof UsersInviteSchema>;

View File

@@ -307,27 +307,6 @@ describe("#users.invite", () => {
expect(body.data.users[0].isAdmin).toBeFalsy(); expect(body.data.users[0].isAdmin).toBeFalsy();
}); });
it("should invite user as a member if role is any arbitary value", async () => {
const admin = await buildAdmin();
const res = await server.post("/api/users.invite", {
body: {
token: admin.getJwtToken(),
invites: [
{
email: "test@example.com",
name: "Test",
role: "arbitary",
},
],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.sent.length).toEqual(1);
expect(body.data.users[0].isViewer).toBeFalsy();
expect(body.data.users[0].isAdmin).toBeFalsy();
});
it("should require authentication", async () => { it("should require authentication", async () => {
const res = await server.post("/api/users.invite"); const res = await server.post("/api/users.invite");
expect(res.status).toEqual(401); expect(res.status).toEqual(401);

View File

@@ -17,155 +17,141 @@ import { rateLimiter } from "@server/middlewares/rateLimiter";
import { transaction } from "@server/middlewares/transaction"; import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate"; import validate from "@server/middlewares/validate";
import { Event, User, Team } from "@server/models"; import { Event, User, Team } from "@server/models";
import { UserFlag, UserRole } from "@server/models/User"; import { UserFlag } from "@server/models/User";
import { can, authorize } from "@server/policies"; import { can, authorize } from "@server/policies";
import { presentUser, presentPolicies } from "@server/presenters"; import { presentUser, presentPolicies } from "@server/presenters";
import { APIContext } from "@server/types"; import { APIContext } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { safeEqual } from "@server/utils/crypto"; import { safeEqual } from "@server/utils/crypto";
import {
assertIn,
assertSort,
assertPresent,
assertArray,
} from "@server/validation";
import pagination from "../middlewares/pagination"; import pagination from "../middlewares/pagination";
import * as T from "./schema"; import * as T from "./schema";
const router = new Router(); const router = new Router();
const emailEnabled = !!(env.SMTP_HOST || env.ENVIRONMENT === "development"); const emailEnabled = !!(env.SMTP_HOST || env.ENVIRONMENT === "development");
router.post("users.list", auth(), pagination(), async (ctx: APIContext) => { router.post(
let { direction } = ctx.request.body; "users.list",
const { sort = "createdAt", query, filter, ids } = ctx.request.body; auth(),
if (direction !== "ASC") { pagination(),
direction = "DESC"; validate(T.UsersListSchema),
} async (ctx: APIContext<T.UsersListReq>) => {
assertSort(sort, User); const { sort, direction, query, filter, ids } = ctx.input.body;
if (filter) { const actor = ctx.state.auth.user;
assertIn( let where: WhereOptions<User> = {
filter, teamId: actor.teamId,
["invited", "viewers", "admins", "members", "active", "all", "suspended"],
"Invalid filter"
);
}
const actor = ctx.state.auth.user;
let where: WhereOptions<User> = {
teamId: actor.teamId,
};
// Filter out suspended users if we're not an admin
if (!actor.isAdmin) {
where = {
...where,
suspendedAt: {
[Op.eq]: null,
},
}; };
}
switch (filter) { // Filter out suspended users if we're not an admin
case "invited": { if (!actor.isAdmin) {
where = { ...where, lastActiveAt: null }; where = {
break; ...where,
suspendedAt: {
[Op.eq]: null,
},
};
} }
case "viewers": { switch (filter) {
where = { ...where, isViewer: true }; case "invited": {
break; where = { ...where, lastActiveAt: null };
} break;
}
case "admins": { case "viewers": {
where = { ...where, isAdmin: true }; where = { ...where, isViewer: true };
break; break;
} }
case "members": { case "admins": {
where = { ...where, isAdmin: false, isViewer: false }; where = { ...where, isAdmin: true };
break; break;
} }
case "suspended": { case "members": {
if (actor.isAdmin) { where = { ...where, isAdmin: false, isViewer: false };
break;
}
case "suspended": {
if (actor.isAdmin) {
where = {
...where,
suspendedAt: {
[Op.ne]: null,
},
};
}
break;
}
case "active": {
where = {
...where,
lastActiveAt: {
[Op.ne]: null,
},
suspendedAt: {
[Op.is]: null,
},
};
break;
}
case "all": {
break;
}
default: {
where = { where = {
...where, ...where,
suspendedAt: { suspendedAt: {
[Op.ne]: null, [Op.is]: null,
}, },
}; };
break;
} }
break;
} }
case "active": { if (query) {
where = { where = {
...where, ...where,
lastActiveAt: { name: {
[Op.ne]: null, [Op.iLike]: `%${query}%`,
},
suspendedAt: {
[Op.is]: null,
}, },
}; };
break;
} }
case "all": { if (ids) {
break;
}
default: {
where = { where = {
...where, ...where,
suspendedAt: { id: ids,
[Op.is]: null,
},
}; };
break;
} }
}
if (query) { const [users, total] = await Promise.all([
where = { User.findAll({
...where, where,
name: { order: [[sort, direction]],
[Op.iLike]: `%${query}%`, offset: ctx.state.pagination.offset,
}, limit: ctx.state.pagination.limit,
}),
User.count({
where,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: users.map((user) =>
presentUser(user, {
includeDetails: can(actor, "readDetails", user),
})
),
policies: presentPolicies(actor, users),
}; };
} }
);
if (ids) {
assertArray(ids, "ids must be an array of UUIDs");
where = {
...where,
id: ids,
};
}
const [users, total] = await Promise.all([
User.findAll({
where,
order: [[sort, direction]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
User.count({
where,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: users.map((user) =>
presentUser(user, {
includeDetails: can(actor, "readDetails", user),
})
),
policies: presentPolicies(actor, users),
};
});
router.post("users.count", auth(), async (ctx: APIContext) => { router.post("users.count", auth(), async (ctx: APIContext) => {
const { user } = ctx.state.auth; const { user } = ctx.state.auth;
@@ -178,20 +164,25 @@ router.post("users.count", auth(), async (ctx: APIContext) => {
}; };
}); });
router.post("users.info", auth(), async (ctx: APIContext) => { router.post(
const { id } = ctx.request.body; "users.info",
const actor = ctx.state.auth.user; auth(),
const user = id ? await User.findByPk(id) : actor; validate(T.UsersInfoSchema),
authorize(actor, "read", user); async (ctx: APIContext<T.UsersInfoReq>) => {
const includeDetails = can(actor, "readDetails", user); const { id } = ctx.input.body;
const actor = ctx.state.auth.user;
const user = id ? await User.findByPk(id) : actor;
authorize(actor, "read", user);
const includeDetails = can(actor, "readDetails", user);
ctx.body = { ctx.body = {
data: presentUser(user, { data: presentUser(user, {
includeDetails, includeDetails,
}), }),
policies: presentPolicies(actor, [user]), policies: presentPolicies(actor, [user]),
}; };
}); }
);
router.post( router.post(
"users.update", "users.update",
@@ -245,119 +236,133 @@ router.post(
); );
// Admin specific // Admin specific
router.post("users.promote", auth(), async (ctx: APIContext) => { router.post(
const userId = ctx.request.body.id; "users.promote",
const actor = ctx.state.auth.user; auth(),
const teamId = actor.teamId; validate(T.UsersPromoteSchema),
assertPresent(userId, "id is required"); async (ctx: APIContext<T.UsersPromoteReq>) => {
const user = await User.findByPk(userId); const userId = ctx.input.body.id;
authorize(actor, "promote", user); const actor = ctx.state.auth.user;
const teamId = actor.teamId;
const user = await User.findByPk(userId);
authorize(actor, "promote", user);
await user.promote(); await user.promote();
await Event.create({ await Event.create({
name: "users.promote", name: "users.promote",
actorId: actor.id, actorId: actor.id,
userId, userId,
teamId, teamId,
data: { data: {
name: user.name, name: user.name,
}, },
ip: ctx.request.ip, ip: ctx.request.ip,
}); });
const includeDetails = can(actor, "readDetails", user); const includeDetails = can(actor, "readDetails", user);
ctx.body = { ctx.body = {
data: presentUser(user, { data: presentUser(user, {
includeDetails, includeDetails,
}), }),
policies: presentPolicies(actor, [user]), policies: presentPolicies(actor, [user]),
}; };
}); }
);
router.post("users.demote", auth(), async (ctx: APIContext) => { router.post(
const userId = ctx.request.body.id; "users.demote",
let { to } = ctx.request.body; auth(),
const actor = ctx.state.auth.user; validate(T.UsersDemoteSchema),
assertPresent(userId, "id is required"); async (ctx: APIContext<T.UsersDemoteReq>) => {
const userId = ctx.input.body.id;
const to = ctx.input.body.to;
const actor = ctx.state.auth.user;
to = (to === "viewer" ? "viewer" : "member") as UserRole; const user = await User.findByPk(userId, {
rejectOnEmpty: true,
});
authorize(actor, "demote", user);
const user = await User.findByPk(userId, { await userDemoter({
rejectOnEmpty: true, to,
}); user,
authorize(actor, "demote", user); actorId: actor.id,
ip: ctx.request.ip,
});
const includeDetails = can(actor, "readDetails", user);
await userDemoter({ ctx.body = {
to, data: presentUser(user, {
user, includeDetails,
actorId: actor.id, }),
ip: ctx.request.ip, policies: presentPolicies(actor, [user]),
}); };
const includeDetails = can(actor, "readDetails", user); }
);
ctx.body = { router.post(
data: presentUser(user, { "users.suspend",
includeDetails, auth(),
}), validate(T.UsersSuspendSchema),
policies: presentPolicies(actor, [user]), async (ctx: APIContext<T.UsersSuspendReq>) => {
}; const userId = ctx.input.body.id;
}); const actor = ctx.state.auth.user;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
});
authorize(actor, "suspend", user);
router.post("users.suspend", auth(), async (ctx: APIContext) => { await userSuspender({
const userId = ctx.request.body.id; user,
const actor = ctx.state.auth.user; actorId: actor.id,
assertPresent(userId, "id is required"); ip: ctx.request.ip,
const user = await User.findByPk(userId, { });
rejectOnEmpty: true, const includeDetails = can(actor, "readDetails", user);
});
authorize(actor, "suspend", user);
await userSuspender({ ctx.body = {
user, data: presentUser(user, {
actorId: actor.id, includeDetails,
ip: ctx.request.ip, }),
}); policies: presentPolicies(actor, [user]),
const includeDetails = can(actor, "readDetails", user); };
}
);
ctx.body = { router.post(
data: presentUser(user, { "users.activate",
includeDetails, auth(),
}), validate(T.UsersActivateSchema),
policies: presentPolicies(actor, [user]), async (ctx: APIContext<T.UsersActivateReq>) => {
}; const userId = ctx.input.body.id;
}); const actor = ctx.state.auth.user;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
});
authorize(actor, "activate", user);
router.post("users.activate", auth(), async (ctx: APIContext) => { await userUnsuspender({
const userId = ctx.request.body.id; user,
const actor = ctx.state.auth.user; actorId: actor.id,
assertPresent(userId, "id is required"); ip: ctx.request.ip,
const user = await User.findByPk(userId, { });
rejectOnEmpty: true, const includeDetails = can(actor, "readDetails", user);
});
authorize(actor, "activate", user);
await userUnsuspender({ ctx.body = {
user, data: presentUser(user, {
actorId: actor.id, includeDetails,
ip: ctx.request.ip, }),
}); policies: presentPolicies(actor, [user]),
const includeDetails = can(actor, "readDetails", user); };
}
ctx.body = { );
data: presentUser(user, {
includeDetails,
}),
policies: presentPolicies(actor, [user]),
};
});
router.post( router.post(
"users.invite", "users.invite",
rateLimiter(RateLimiterStrategy.TenPerHour), rateLimiter(RateLimiterStrategy.TenPerHour),
auth(), auth(),
async (ctx: APIContext) => { validate(T.UsersInviteSchema),
const { invites } = ctx.request.body; async (ctx: APIContext<T.UsersInviteReq>) => {
assertArray(invites, "invites must be an array"); const { invites } = ctx.input.body;
const { user } = ctx.state.auth; const { user } = ctx.state.auth;
const team = await Team.findByPk(user.teamId); const team = await Team.findByPk(user.teamId);
authorize(user, "inviteUser", team); authorize(user, "inviteUser", team);
@@ -380,9 +385,10 @@ router.post(
router.post( router.post(
"users.resendInvite", "users.resendInvite",
auth(), auth(),
validate(T.UsersResendInviteSchema),
transaction(), transaction(),
async (ctx: APIContext) => { async (ctx: APIContext<T.UsersResendInviteReq>) => {
const { id } = ctx.request.body; const { id } = ctx.input.body;
const { auth, transaction } = ctx.state; const { auth, transaction } = ctx.state;
const actor = auth.user; const actor = auth.user;
@@ -452,7 +458,7 @@ router.post(
transaction(), transaction(),
async (ctx: APIContext<T.UsersDeleteSchemaReq>) => { async (ctx: APIContext<T.UsersDeleteSchemaReq>) => {
const { transaction } = ctx.state; const { transaction } = ctx.state;
const { id, code } = ctx.request.body; const { id, code } = ctx.input.body;
const actor = ctx.state.auth.user; const actor = ctx.state.auth.user;
let user: User; let user: User;

View File

@@ -1,4 +1,8 @@
export type Role = "admin" | "viewer" | "member"; export enum UserRole {
Admin = "admin",
Member = "member",
Viewer = "viewer",
}
export type DateFilter = "day" | "week" | "month" | "year"; export type DateFilter = "day" | "week" | "month" | "year";