This commit is contained in:
Tom Moor committed 2025-03-16 14:45:16 -04:00
1 parent 6869d4cb02
commit c71f1382a2
28 files changed
+610 -256

No files matched your search

+6 -18
View File
@@ -155,12 +155,7 @@ export const createDocumentFromTemplate = createAction({
? stores.documents.get(activeDocumentId)
: undefined;
if (
!currentTeamId ||
!document?.isTemplate ||
!!document?.isDraft ||
!!document?.isDeleted
) {
if (!currentTeamId || !!document?.isDraft || !!document?.isDeleted) {
return false;
}
@@ -766,7 +761,7 @@ export const createTemplateFromDocument = createAction({
const document = activeDocumentId
? stores.documents.get(activeDocumentId)
: undefined;
if (document?.isTemplate || !document?.isActive) {
if (!document?.isActive) {
return false;
}
return !!(
@@ -829,7 +824,7 @@ export const moveTemplateToWorkspace = createAction({
return false;
}
const document = stores.documents.get(activeDocumentId);
if (!document || !document.template || document.isWorkspaceTemplate) {
if (!document) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
@@ -895,8 +890,7 @@ export const moveDocument = createAction({
return false;
}
const document = stores.documents.get(activeDocumentId);
// Don't show the button if this is a non-workspace template.
if (!document || (document.template && !document.isWorkspaceTemplate)) {
if (!document) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
@@ -914,8 +908,7 @@ export const moveTemplate = createAction({
return false;
}
const document = stores.documents.get(activeDocumentId);
// Don't show the menu if this is not a template (or) a workspace template.
if (!document || !document.template || document.isWorkspaceTemplate) {
if (!document) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
@@ -1106,12 +1099,7 @@ export const openDocumentInsights = createAction({
? stores.documents.get(activeDocumentId)
: undefined;
return (
!!activeDocumentId &&
can.listViews &&
!document?.isTemplate &&
!document?.isDeleted
);
return !!activeDocumentId && can.listViews && !document?.isDeleted;
},
perform: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
@@ -12,15 +12,15 @@ import history from "~/utils/history";
import { newDocumentPath } from "~/utils/routeHelpers";
const useTemplatesAction = () => {
const { documents } = useStores();
const { templates } = useStores();
React.useEffect(() => {
void documents.fetchAllTemplates();
}, [documents]);
void templates.fetchAll();
}, [templates]);
const actions = React.useMemo(
() =>
documents.templatesAlphabetical.map((template) =>
templates.orderedData.map((template) =>
createAction({
name: template.titleWithDefault,
analyticsName: "New document",
@@ -58,7 +58,7 @@ const useTemplatesAction = () => {
),
})
),
[documents.templatesAlphabetical]
[templates.orderedData]
);
const newFromTemplate = React.useMemo(
+1 -1
View File
@@ -140,7 +140,7 @@ const useSettingsConfig = () => {
name: t("Templates"),
path: settingsPath("templates"),
component: Templates,
enabled: can.readTemplate,
enabled: can.createDocument,
group: t("Workspace"),
icon: ShapesIcon,
},
+3 -6
View File
@@ -231,9 +231,7 @@ const MenuContent: React.FC<MenuContentProps> = observer(function MenuContent_({
{
type: "button",
title: t("Restore"),
visible:
!!(document.isWorkspaceTemplate || collection?.isActive) &&
!!(can.restore || can.unarchive),
visible: !!collection?.isActive && !!(can.restore || can.unarchive),
onClick: (ev) => handleRestore(ev),
icon: <RestoreIcon />,
},
@@ -241,7 +239,7 @@ const MenuContent: React.FC<MenuContentProps> = observer(function MenuContent_({
type: "submenu",
title: t("Restore"),
visible:
!(document.isWorkspaceTemplate || collection?.isActive) &&
!collection?.isActive &&
!!(can.restore || can.unarchive) &&
restoreItems.length !== 0,
style: {
@@ -289,8 +287,7 @@ const MenuContent: React.FC<MenuContentProps> = observer(function MenuContent_({
type: "route",
title: t("Edit"),
to: documentEditPath(document),
visible:
!!can.update && user.separateEditMode && !document.template,
visible: !!can.update && user.separateEditMode,
icon: <EditIcon />,
},
{
+4 -24
View File
@@ -24,7 +24,6 @@ import DocumentsStore from "~/stores/DocumentsStore";
import User from "~/models/User";
import type { Properties } from "~/types";
import { client } from "~/utils/ApiClient";
import { settingsPath } from "~/utils/routeHelpers";
import Collection from "./Collection";
import Notification from "./Notification";
import Pin from "./Pin";
@@ -146,12 +145,6 @@ export default class Document extends ArchivableModel implements Searchable {
@observable
color?: string | null;
/**
* Whether this is a template.
*/
@observable
template: boolean;
/**
* Whether the document layout is displayed full page width.
*/
@@ -258,20 +251,17 @@ export default class Document extends ArchivableModel implements Searchable {
@computed
get path(): string {
const prefix =
this.template && !this.isDeleted ? settingsPath("templates") : "/doc";
if (!this.title) {
return `${prefix}/untitled-${this.urlId}`;
return `/doc/untitled-${this.urlId}`;
}
const slugifiedTitle = slugify(this.title);
return `${prefix}/${slugifiedTitle}-${this.urlId}`;
return `/doc/${slugifiedTitle}-${this.urlId}`;
}
@computed
get noun(): string {
return this.template ? t("template") : t("document");
return t("document");
}
@computed
@@ -353,11 +343,6 @@ export default class Document extends ArchivableModel implements Searchable {
return !!this.deletedAt;
}
@computed
get isTemplate(): boolean {
return !!this.template;
}
@computed
get isDraft(): boolean {
return !this.publishedAt;
@@ -423,11 +408,6 @@ export default class Document extends ArchivableModel implements Searchable {
return path.map((item) => item.asNavigationNode);
}
@computed
get isWorkspaceTemplate() {
return this.template && !this.collectionId;
}
get titleWithDefault(): string {
return this.title || i18n.t("Untitled");
}
@@ -620,7 +600,7 @@ export default class Document extends ArchivableModel implements Searchable {
@computed
get isActive(): boolean {
return !this.isDeleted && !this.isTemplate && !this.isArchived;
return !this.isDeleted && !this.isArchived;
}
@computed
+145
View File
@@ -0,0 +1,145 @@
import type { ProsemirrorData } from "@shared/types";
import { isRTL } from "@shared/utils/rtl";
import slugify from "@shared/utils/slugify";
import { addDays } from "date-fns";
import i18n from "i18next";
import { computed, observable } from "mobx";
import TemplatesStore from "~/stores/TemplatesStore";
import User from "~/models/User";
import Collection from "./Collection";
import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
import { Searchable } from "./interfaces/Searchable";
export default class Template extends ParanoidModel implements Searchable {
static modelName = "Template";
store: TemplatesStore;
@observable.shallow
data: ProsemirrorData;
@computed
get searchContent(): string {
return this.title;
}
/**
* The id of the collection that this document belongs to, if any.
*/
@Field
@observable
collectionId?: string | null;
/**
* The collection that this document belongs to.
*/
@Relation(() => Collection, { onDelete: "cascade" })
collection?: Collection;
/**
* The title of the document.
*/
@Field
@observable
title: string;
/**
* An icon (or) emoji to use as the document icon.
*/
@Field
@observable
icon?: string | null;
/**
* The color to use for the document icon.
*/
@Field
@observable
color?: string | null;
/**
* Whether the document layout is displayed full page width.
*/
@Field
@observable
fullWidth: boolean;
@Relation(() => User)
createdBy: User | undefined;
@Relation(() => User)
@observable
updatedBy: User | undefined;
@observable
publishedAt: string | undefined;
@observable
urlId: string;
/**
* Returns the direction of the template text, either "rtl" or "ltr"
*/
@computed
get dir(): "rtl" | "ltr" {
return this.rtl ? "rtl" : "ltr";
}
/**
* Returns true if the template text is right-to-left
*/
@computed
get rtl() {
return isRTL(this.title);
}
@computed
get path(): string {
if (!this.title) {
return `/settings/templates/untitled-${this.urlId}`;
}
const slugifiedTitle = slugify(this.title);
return `/settings/templates/${slugifiedTitle}-${this.urlId}`;
}
@computed
get isDeleted(): boolean {
return !!this.deletedAt;
}
@computed
get isDraft(): boolean {
return !this.publishedAt;
}
@computed
get hasEmptyTitle(): boolean {
return this.title === "";
}
@computed
get isWorkspaceTemplate(): boolean {
return !this.collectionId;
}
@computed
get permanentlyDeletedAt(): string | undefined {
if (!this.deletedAt) {
return undefined;
}
return addDays(new Date(this.deletedAt), 30).toString();
}
get titleWithDefault(): string {
return this.title || i18n.t("Untitled");
}
@computed
get isActive(): boolean {
return !this.isDeleted;
}
}
+1 -3
View File
@@ -368,9 +368,7 @@ function DocumentHeader({
hideOnActionDisabled
hideIcon
>
{document.collectionId || document.isWorkspaceTemplate
? t("Publish")
: `${t("Publish")}…`}
{document.collectionId ? t("Publish") : `${t("Publish")}…`}
</Button>
</Action>
)}
+7 -8
View File
@@ -17,16 +17,11 @@ import NewTemplateMenu from "~/menus/NewTemplateMenu";
import { settingsPath } from "~/utils/routeHelpers";
function Templates() {
const { documents } = useStores();
const { templates } = useStores();
const { t } = useTranslation();
const param = useQuery();
const { fetchTemplates, templates, templatesAlphabetical } = documents;
const sort = param.get("sort") || "recent";
React.useEffect(() => {
void documents.fetchDrafts();
}, [documents]);
return (
<Scene
icon={<ShapesIcon />}
@@ -65,8 +60,12 @@ function Templates() {
</Tabs>
}
empty={<Empty>{t("There are no templates just yet.")}</Empty>}
fetch={fetchTemplates}
documents={sort === "alphabetical" ? templatesAlphabetical : templates}
fetch={templates.fetchAll}
documents={
sort === "alphabetical"
? templates.alphabetical
: templates.orderedData
}
showCollection
showDraft
/>
-31
View File
@@ -99,17 +99,6 @@ export default class DocumentsStore extends Store<Document> {
return orderBy(this.all, "updatedAt", "desc");
}
get templates(): Document[] {
return orderBy(
filter(
this.orderedData,
(d) => !d.archivedAt && !d.deletedAt && d.template
),
"updatedAt",
"desc"
);
}
createdByUser(userId: string): Document[] {
return orderBy(
filter(this.all, (d) => d.createdBy?.id === userId),
@@ -152,21 +141,6 @@ export default class DocumentsStore extends Store<Document> {
);
}
templatesInCollection(collectionId: string): Document[] {
return orderBy(
filter(
this.orderedData,
(d) =>
!d.archivedAt &&
!d.deletedAt &&
d.template === true &&
d.collectionId === collectionId
),
"updatedAt",
"desc"
);
}
publishedInCollection(collectionId: string): Document[] {
return filter(
this.all,
@@ -231,11 +205,6 @@ export default class DocumentsStore extends Store<Document> {
);
}
@computed
get templatesAlphabetical(): Document[] {
return naturalSort(this.templates, "title");
}
@computed
get totalDrafts(): number {
return this.drafts().length;
+3
View File
@@ -24,6 +24,7 @@ import SearchesStore from "./SearchesStore";
import SharesStore from "./SharesStore";
import StarsStore from "./StarsStore";
import SubscriptionsStore from "./SubscriptionsStore";
import TemplatesStore from "./TemplatesStore";
import UiStore from "./UiStore";
import UserMembershipsStore from "./UserMembershipsStore";
import UsersStore from "./UsersStore";
@@ -55,6 +56,7 @@ export default class RootStore {
ui: UiStore;
stars: StarsStore;
subscriptions: SubscriptionsStore;
templates: TemplatesStore;
users: UsersStore;
views: ViewsStore;
fileOperations: FileOperationsStore;
@@ -82,6 +84,7 @@ export default class RootStore {
this.registerStore(SharesStore);
this.registerStore(StarsStore);
this.registerStore(SubscriptionsStore);
this.registerStore(TemplatesStore);
this.registerStore(UsersStore);
this.registerStore(ViewsStore);
this.registerStore(FileOperationsStore);
+16
View File
@@ -0,0 +1,16 @@
import naturalSort from "@shared/utils/naturalSort";
import { computed } from "mobx";
import Template from "~/models/Template";
import RootStore from "./RootStore";
import Store from "./base/Store";
export default class TemplatesStore extends Store<Template> {
constructor(rootStore: RootStore) {
super(rootStore, Template);
}
@computed
get alphabetical(): Template[] {
return naturalSort(Array.from(this.data.values()), "title");
}
}
+1 -7
View File
@@ -99,6 +99,7 @@ type AdditionalFindOptions = {
[Op.is]: null,
},
},
template: false,
},
attributes: {
exclude: ["state"],
@@ -812,13 +813,6 @@ class Document extends ArchivableModel<
return !!(this.importId && this.sourceMetadata?.trial);
}
/**
* Returns whether this document is a template created at the workspace level.
*/
get isWorkspaceTemplate() {
return this.template && !this.collectionId;
}
/**
* Revert the state of the document to match the passed revision.
*
+184
View File
@@ -0,0 +1,184 @@
import { ProsemirrorData } from "@shared/types";
import { DocumentValidation } from "@shared/validations";
import { InferAttributes, InferCreationAttributes, Op } from "sequelize";
import {
Column,
DataType,
BelongsTo,
ForeignKey,
IsDate,
Table,
Length as SimpleLength,
DefaultScope,
Default,
HasMany,
Unique,
} from "sequelize-typescript";
import slugify from "slugify";
import Collection from "./Collection";
import Revision from "./Revision";
import Team from "./Team";
import User from "./User";
import IdModel from "./base/IdModel";
import Fix from "./decorators/Fix";
import IsHexColor from "./validators/IsHexColor";
import Length from "./validators/Length";
@DefaultScope(() => ({
include: [
{
model: User,
as: "createdBy",
paranoid: false,
},
{
model: User,
as: "updatedBy",
paranoid: false,
},
],
where: {
publishedAt: {
[Op.ne]: null,
},
template: true,
},
attributes: {
exclude: ["state"],
},
}))
@Table({ tableName: "documents", modelName: "template" })
@Fix
class Template extends IdModel<
InferAttributes<Template>,
Partial<InferCreationAttributes<Template>>
> {
@SimpleLength({
min: 10,
max: 10,
msg: `urlId must be 10 characters`,
})
@Unique
@Column
urlId: string;
@Length({
max: DocumentValidation.maxTitleLength,
msg: `Template title must be ${DocumentValidation.maxTitleLength} characters or less`,
})
@Column
title: string;
@Default(false)
@Column
fullWidth: boolean;
/** The version of the editor last used to edit this document. */
@SimpleLength({
max: 255,
msg: `editorVersion must be 255 characters or less`,
})
@Column
editorVersion: string;
/** An icon to use as the template icon. */
@Length({
max: 50,
msg: `icon must be 50 characters or less`,
})
@Column
icon: string | null;
/** The color of the icon. */
@IsHexColor
@Column
color: string | null;
/**
* The content of the template as JSON, this is a snapshot at the last time the state was saved.
*/
@Column(DataType.JSONB)
content: ProsemirrorData | null;
/** Whether the document is published, and if so when. */
@IsDate
@Column
publishedAt: Date | null;
// associations
@BelongsTo(() => User, "lastModifiedById")
updatedBy: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
lastModifiedById: string;
@BelongsTo(() => User, "createdById")
createdBy: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
createdById: string;
@BelongsTo(() => Team, "teamId")
team: Team;
@ForeignKey(() => Team)
@Column(DataType.UUID)
teamId: string;
@BelongsTo(() => Collection, "collectionId")
collection: Collection | null;
@ForeignKey(() => Collection)
@Column(DataType.UUID)
collectionId?: string | null;
@HasMany(() => Revision, "documentId")
revisions: Revision[];
@Default(true)
@Column
template: boolean;
// getters
/** The frontend path to this template. */
get path() {
if (!this.title) {
return `/settings/templates/untitled-${this.urlId}`;
}
const slugifiedTitle = slugify(this.title);
return `/settings/templates/${slugifiedTitle}-${this.urlId}`;
}
/**
* Returns whether this is a workspace template.
*
* @returns boolean
*/
get isWorkspaceTemplate() {
return !this.collectionId;
}
/**
* Convenience method that returns whether this template is a draft.
*
* @returns boolean
*/
get isDraft(): boolean {
return !this.publishedAt;
}
/**
* Convenience method that returns whether this template is deleted.
*
* @returns boolean
*/
get isDeleted(): boolean {
return !this.deletedAt;
}
}
export default Template;
+4 -4
View File
@@ -11,7 +11,7 @@ import { determineIconType } from "@shared/utils/icon";
import { parser, serializer, schema } from "@server/editor";
import { addTags } from "@server/logging/tracer";
import { trace } from "@server/logging/tracing";
import { Collection, Document, Revision } from "@server/models";
import { Collection, Document, Revision, Template } from "@server/models";
import diff from "@server/utils/diff";
import { MentionAttrs, ProsemirrorHelper } from "./ProsemirrorHelper";
import { TextHelper } from "./TextHelper";
@@ -72,7 +72,7 @@ export class DocumentHelper {
* @returns The document content as a plain JSON object
*/
static async toJSON(
document: Document | Revision | Collection,
document: Document | Template | Revision | Collection,
options?: {
/** The team context */
teamId?: string;
@@ -84,7 +84,7 @@ export class DocumentHelper {
internalUrlBase?: string;
}
): Promise<ProsemirrorData> {
let doc: Node | null;
let doc: Node | null | undefined;
let data;
if ("content" in document && document.content) {
@@ -103,7 +103,7 @@ export class DocumentHelper {
doc = Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default"));
} else if (document instanceof Collection) {
doc = parser.parse(document.description ?? "");
} else {
} else if (document instanceof Document) {
doc = parser.parse(document.text);
}
+2
View File
@@ -46,6 +46,8 @@ export { default as Team } from "./Team";
export { default as TeamDomain } from "./TeamDomain";
export { default as Template } from "./Template";
export { default as User } from "./User";
export { default as UserAuthentication } from "./UserAuthentication";
+22 -77
View File
@@ -15,23 +15,23 @@ allow(User, "createDocument", Team, (actor, document) =>
)
);
allow(User, "read", Document, (actor, document) =>
and(
isTeamModel(actor, document),
or(
includesMembership(document, [
DocumentPermission.Read,
DocumentPermission.ReadWrite,
DocumentPermission.Admin,
]),
and(!!document?.isDraft, actor.id === document?.createdById),
and(
!!document?.isWorkspaceTemplate,
can(actor, "readTemplate", actor.team)
),
can(actor, "readDocument", document?.collection)
allow(
User,
["read", "star", "unstar", "subscribe", "unsubscribe"],
Document,
(actor, document) =>
and(
isTeamModel(actor, document),
or(
includesMembership(document, [
DocumentPermission.Read,
DocumentPermission.ReadWrite,
DocumentPermission.Admin,
]),
and(!!document?.isDraft, actor.id === document?.createdById),
can(actor, "readDocument", document?.collection)
)
)
)
);
allow(User, ["listRevisions", "listViews"], Document, (actor, document) =>
@@ -59,29 +59,15 @@ allow(User, "comment", Document, (actor, document) =>
and(can(actor, "update", document), actor.isGuest)
),
isTeamMutable(actor),
!!document?.isActive,
!document?.template
!!document?.isActive
)
);
allow(
User,
["star", "unstar", "subscribe", "unsubscribe"],
Document,
(actor, document) =>
and(
//
can(actor, "read", document),
!document?.template
)
);
allow(User, "share", Document, (actor, document) =>
and(
can(actor, "read", document),
isTeamMutable(actor),
!!document?.isActive,
!document?.template,
or(!document?.collection, can(actor, "share", document?.collection))
)
);
@@ -98,14 +84,7 @@ allow(User, "update", Document, (actor, document) =>
]),
or(
can(actor, "updateDocument", document?.collection),
and(!!document?.isDraft && actor.id === document?.createdById),
and(
!!document?.isWorkspaceTemplate,
or(
actor.id === document?.createdById,
can(actor, "updateTemplate", actor.team)
)
)
and(!!document?.isDraft && actor.id === document?.createdById)
)
)
)
@@ -121,7 +100,6 @@ allow(User, "publish", Document, (actor, document) =>
allow(User, "manageUsers", Document, (actor, document) =>
and(
!document?.template,
can(actor, "update", document),
or(
includesMembership(document, [DocumentPermission.Admin]),
@@ -137,14 +115,7 @@ allow(User, "duplicate", Document, (actor, document) =>
or(
includesMembership(document, [DocumentPermission.Admin]),
can(actor, "updateDocument", document?.collection),
!!document?.isDraft && actor.id === document?.createdById,
and(
!!document?.isWorkspaceTemplate,
or(
actor.id === document?.createdById,
can(actor, "updateTemplate", actor.team)
)
)
!!document?.isDraft && actor.id === document?.createdById
)
)
);
@@ -154,20 +125,13 @@ allow(User, "move", Document, (actor, document) =>
can(actor, "update", document),
or(
can(actor, "updateDocument", document?.collection),
and(!!document?.isDraft && actor.id === document?.createdById),
and(
!!document?.isWorkspaceTemplate,
or(
actor.id === document?.createdById,
can(actor, "updateTemplate", actor.team)
)
)
!!document?.isDraft && actor.id === document?.createdById
)
)
);
allow(User, "createChildDocument", Document, (actor, document) =>
and(can(actor, "update", document), !document?.isDraft, !document?.template)
and(can(actor, "update", document), !document?.isDraft)
);
allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) =>
@@ -175,7 +139,6 @@ allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) =>
can(actor, "update", document),
can(actor, "update", document?.collection),
!document?.isDraft,
!document?.template,
!actor.isGuest
)
);
@@ -186,7 +149,6 @@ allow(User, "pinToHome", Document, (actor, document) =>
isTeamAdmin(actor, document),
isTeamMutable(actor),
!document?.isDraft,
!document?.template,
!!document?.isActive
)
);
@@ -196,11 +158,7 @@ allow(User, "delete", Document, (actor, document) =>
isTeamModel(actor, document),
isTeamMutable(actor),
!document?.isDeleted,
or(
can(actor, "unarchive", document),
can(actor, "update", document),
and(!document?.isWorkspaceTemplate, !document?.collection)
)
or(can(actor, "unarchive", document), can(actor, "update", document))
)
);
@@ -216,10 +174,6 @@ allow(User, ["restore", "permanentDelete"], Document, (actor, document) =>
]),
can(actor, "updateDocument", document?.collection),
and(!!document?.isDraft && actor.id === document?.createdById),
and(
!!document?.isWorkspaceTemplate,
can(actor, "updateTemplate", actor.team)
),
!document?.collection
)
)
@@ -227,7 +181,6 @@ allow(User, ["restore", "permanentDelete"], Document, (actor, document) =>
allow(User, "archive", Document, (actor, document) =>
and(
!document?.template,
!document?.isDraft,
!!document?.isActive,
can(actor, "update", document),
@@ -240,7 +193,6 @@ allow(User, "archive", Document, (actor, document) =>
allow(User, "unarchive", Document, (actor, document) =>
and(
!document?.template,
!document?.isDraft,
!document?.isDeleted,
!!document?.archivedAt,
@@ -274,13 +226,6 @@ allow(User, "unpublish", Document, (user, document) => {
return false;
}
if (
document.isWorkspaceTemplate &&
(user.id === document.createdById || can(user, "updateTemplate", user.team))
) {
return true;
}
invariant(
document.collection,
"collection is missing, did you forget to include in the query scope?"
+1 -1
View File
@@ -69,7 +69,7 @@ describe("policies/team", () => {
});
const abilities = serialize(user, team);
expect(abilities.readTemplate).toEqual(permission);
expect(abilities.createDocument).toEqual(permission);
});
}
});
+1 -31
View File
@@ -1,13 +1,6 @@
import { Team, User } from "@server/models";
import { allow } from "./cancan";
import {
and,
isCloudHosted,
isTeamAdmin,
isTeamModel,
isTeamMutable,
or,
} from "./utils";
import { and, isCloudHosted, isTeamAdmin, isTeamModel, or } from "./utils";
allow(User, "read", Team, isTeamModel);
@@ -39,26 +32,3 @@ allow(User, ["delete", "audit"], Team, (actor, team) =>
isTeamAdmin(actor, team)
)
);
allow(User, "createTemplate", Team, (actor, team) =>
and(
//
!actor.isGuest,
!actor.isViewer,
isTeamModel(actor, team),
isTeamMutable(actor)
)
);
allow(User, "readTemplate", Team, (actor, team) =>
and(!actor.isViewer, isTeamModel(actor, team))
);
allow(User, "updateTemplate", Team, (actor, team) =>
and(
//
actor.isAdmin,
isTeamModel(actor, team),
isTeamMutable(actor)
)
);
+67
View File
@@ -0,0 +1,67 @@
import { Template, User, Team } from "@server/models";
import { allow, can } from "./cancan";
import { and, isTeamModel, isTeamMutable, or } from "./utils";
allow(User, ["createTemplate", "updateTemplate"], Team, (actor, team) =>
and(
//
actor.isAdmin,
isTeamModel(actor, team),
isTeamMutable(actor)
)
);
allow(User, "read", Template, (actor, template) =>
and(
isTeamModel(actor, template),
or(
and(!!template?.isWorkspaceTemplate, can(actor, "read", actor.team)),
can(actor, "readDocument", template?.collection)
)
)
);
allow(User, "listRevisions", Template, (actor, template) =>
or(
and(can(actor, "read", template), !actor.isGuest),
and(can(actor, "update", template), actor.isGuest)
)
);
allow(User, ["update", "duplicate"], Template, (actor, template) =>
and(
can(actor, "read", template),
isTeamMutable(actor),
or(
and(
!!template?.isWorkspaceTemplate,
can(actor, "updateTemplate", actor.team)
),
can(actor, "update", template?.collection)
)
)
);
allow(User, "publish", Template, (actor, template) =>
and(
//
can(actor, "update", template),
!!template?.isDraft
)
);
allow(User, "unpublish", Template, (actor, template) =>
and(
//
can(actor, "update", template),
!template?.isDraft
)
);
allow(User, "delete", Template, (actor, template) =>
and(
//
can(actor, "update", template),
!template?.isDeleted
)
);
+2
View File
@@ -23,6 +23,7 @@ import presentShare from "./share";
import presentStar from "./star";
import presentSubscription from "./subscription";
import presentTeam from "./team";
import presentTemplate from "./template";
import presentUser from "./user";
import presentView from "./view";
@@ -52,6 +53,7 @@ export {
presentStar,
presentSubscription,
presentTeam,
presentTemplate,
presentUser,
presentView,
};
+32
View File
@@ -0,0 +1,32 @@
import { traceFunction } from "@server/logging/tracing";
import { Template } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { APIContext } from "@server/types";
import presentUser from "./user";
async function presentTemplate(
ctx: APIContext | undefined,
template: Template
) {
return {
id: template.id,
url: template.path,
urlId: template.urlId,
title: template.title,
data: await DocumentHelper.toJSON(template),
icon: template.icon,
color: template.color,
createdAt: template.createdAt,
createdBy: presentUser(template.createdBy),
updatedAt: template.updatedAt,
updatedBy: presentUser(template.updatedBy),
publishedAt: template.publishedAt,
deletedAt: template.deletedAt,
fullWidth: template.fullWidth,
collectionId: undefined,
};
}
export default traceFunction({
spanName: "presenters",
})(presentTemplate);
+5 -36
View File
@@ -54,7 +54,7 @@ import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import SearchHelper from "@server/models/helpers/SearchHelper";
import { TextHelper } from "@server/models/helpers/TextHelper";
import { authorize, can, cannot } from "@server/policies";
import { authorize, cannot } from "@server/policies";
import {
presentDocument,
presentPolicies,
@@ -88,7 +88,6 @@ router.post(
const {
sort,
direction,
template,
collectionId,
backlinkDocumentId,
parentDocumentId,
@@ -116,12 +115,6 @@ router.post(
where[Op.and].push({ archivedAt: { [Op.eq]: null } });
}
if (template) {
where[Op.and].push({
template: true,
});
}
// if a specific user is passed then add to filters. If the user doesn't
// exist in the team then nothing will be returned, so no need to check auth
if (createdById) {
@@ -149,12 +142,7 @@ router.post(
} else if (!backlinkDocumentId) {
const collectionIds = await user.collectionIds();
where[Op.and].push({
collectionId:
template && can(user, "readTemplate", user.team)
? {
[Op.or]: [{ [Op.in]: collectionIds }, { [Op.is]: null }],
}
: collectionIds,
collectionId: collectionIds,
});
}
@@ -830,8 +818,7 @@ router.post(
}).findByPk(destCollectionId)
: undefined;
// In case of workspace templates, both source and destination collections are undefined.
if (!document.isWorkspaceTemplate && !destCollection?.isActive) {
if (!destCollection?.isActive) {
throw ValidationError(
"Unable to restore, the collection may have been deleted or archived"
);
@@ -846,19 +833,7 @@ router.post(
});
}
if (document.deletedAt && document.isWorkspaceTemplate) {
authorize(user, "restore", document);
await document.restore({ transaction });
await Event.createFromContext(ctx, {
name: "documents.restore",
documentId: document.id,
collectionId: document.collectionId,
data: {
title: document.title,
},
});
} else if (document.deletedAt) {
if (document.deletedAt) {
authorize(user, "restore", document);
authorize(user, "updateDocument", destCollection);
@@ -1198,7 +1173,7 @@ router.post(
authorize(user, "publish", document);
}
if (!document.collectionId && !document.isWorkspaceTemplate) {
if (!document.collectionId) {
assertPresent(
collectionId,
"collectionId is required to publish a draft without collection"
@@ -1217,8 +1192,6 @@ router.post(
}
);
authorize(user, "createChildDocument", parentDocument, { collection });
} else if (document.isWorkspaceTemplate) {
authorize(user, "createTemplate", user.team);
} else {
authorize(user, "createDocument", collection);
}
@@ -1266,8 +1239,6 @@ router.post(
if (collection) {
authorize(user, "updateDocument", collection);
} else if (document.isWorkspaceTemplate) {
authorize(user, "createTemplate", user.team);
}
if (parentDocumentId) {
@@ -1325,8 +1296,6 @@ router.post(
method: ["withMembership", user.id],
}).findByPk(collectionId, { transaction });
authorize(user, "updateDocument", collection);
} else if (document.template) {
authorize(user, "updateTemplate", user.team);
} else if (!parentDocumentId) {
throw InvalidRequestError("collectionId is required to move a document");
}
-3
View File
@@ -87,9 +87,6 @@ export const DocumentsListSchema = BaseSchema.extend({
/** Id of the parent document to which the document belongs */
parentDocumentId: z.string().uuid().nullish(),
/** Boolean which denotes whether the document is a template */
template: z.boolean().optional(),
/** Document statuses to include in results */
statusFilter: z.nativeEnum(StatusFilter).array().optional(),
}),
+2
View File
@@ -36,6 +36,7 @@ import stars from "./stars";
import subscriptions from "./subscriptions";
import suggestions from "./suggestions";
import teams from "./teams";
import templates from "./templates";
import urls from "./urls";
import userMemberships from "./userMemberships";
import users from "./users";
@@ -87,6 +88,7 @@ router.use("/", stars.routes());
router.use("/", subscriptions.routes());
router.use("/", suggestions.routes());
router.use("/", teams.routes());
router.use("/", templates.routes());
router.use("/", integrations.routes());
router.use("/", notifications.routes());
router.use("/", attachments.routes());
+1
View File
@@ -0,0 +1 @@
export { default } from "./templates";
+27
View File
@@ -0,0 +1,27 @@
import { BaseSchema } from "@server/routes/api/schema";
import { z } from "zod";
const TemplatesSortParamsSchema = z.object({
/** Specifies the attributes by which templates will be sorted in the list */
sort: z
.string()
.refine((val) =>
["createdAt", "updatedAt", "publishedAt", "title"].includes(val)
)
.default("updatedAt"),
/** Specifies the sort order with respect to sort field */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
});
export const TemplatesListSchema = BaseSchema.extend({
body: TemplatesSortParamsSchema.extend({
/** Id of the collection to which the template belongs */
collectionId: z.string().uuid().optional(),
}),
});
export type TemplatesListReq = z.infer<typeof TemplatesListSchema>;
+67
View File
@@ -0,0 +1,67 @@
import auth from "@server/middlewares/authentication";
import validate from "@server/middlewares/validate";
import { Collection, Template } from "@server/models";
import { authorize } from "@server/policies";
import { presentPolicies, presentTemplate } from "@server/presenters";
import { APIContext } from "@server/types";
import Router from "koa-router";
import { Op, WhereOptions } from "sequelize";
import pagination from "../middlewares/pagination";
import * as T from "./schema";
const router = new Router();
router.post(
"templates.list",
auth(),
pagination(),
validate(T.TemplatesListSchema),
async (ctx: APIContext<T.TemplatesListReq>) => {
const { sort, direction, collectionId } = ctx.input.body;
const { user } = ctx.state.auth;
const where: WhereOptions<Template> & {
[Op.and]: WhereOptions<Template>[];
} = {
teamId: user.teamId,
[Op.and]: [
{
deletedAt: {
[Op.eq]: null,
},
},
],
};
// if a specific collection is passed then we need to check auth to view it
if (collectionId) {
where[Op.and].push({ collectionId: [collectionId] });
const collection = await Collection.scope({
method: ["withMembership", user.id],
}).findByPk(collectionId);
authorize(user, "read", collection);
}
const [templates, total] = await Promise.all([
Template.findAll({
where,
order: [[sort, direction]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
Template.count({ where }),
]);
const data = await Promise.all(
templates.map((template) => presentTemplate(ctx, template))
);
const policies = presentPolicies(user, templates);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data,
policies,
};
}
);
export default router;
+1 -1
View File
@@ -49,7 +49,7 @@ export function createDatabaseInstance(
});
} catch (error) {
Logger.fatal(
"Could not connect to database",
env.isDevelopment ? error.message : "Could not connect to database",
databaseUrl
? new Error(
`Failed to parse: "${databaseUrl}". Ensure special characters in database URL are encoded`