mirror of
https://github.com/docmost/docmost.git
synced 2026-05-13 11:44:07 +08:00
Compare commits
1 Commits
main
...
permission-cache
| Author | SHA1 | Date | |
|---|---|---|---|
| ff094c00a7 |
@@ -1,3 +1,11 @@
|
|||||||
export const CacheKey = {
|
export const CacheKey = {
|
||||||
LICENSE_VALID: (workspaceId: string) => `license:valid:${workspaceId}`,
|
LICENSE_VALID: (workspaceId: string) => `license:valid:${workspaceId}`,
|
||||||
|
SPACE_ROLES: (userId: string, spaceId: string) =>
|
||||||
|
`perm:space-roles:${userId}:${spaceId}`,
|
||||||
|
PAGE_CAN_EDIT: (userId: string, pageId: string) =>
|
||||||
|
`perm:can-edit:${userId}:${pageId}`,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Permission caches dedupe repeated checks within and across short request bursts.
|
||||||
|
// 5s keeps staleness on revocations bounded.
|
||||||
|
export const PERMISSION_CACHE_TTL_MS = 5_000;
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Cache } from 'cache-manager';
|
||||||
|
|
||||||
|
export async function withCache<T>(
|
||||||
|
cacheManager: Cache,
|
||||||
|
key: string,
|
||||||
|
ttlMs: number,
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
try {
|
||||||
|
const cached = await cacheManager.get<{ v: T }>(key);
|
||||||
|
if (cached !== undefined && cached !== null) {
|
||||||
|
return cached.v;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[withCache] get failed for "${key}", falling back to source`, err);
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = await fn();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await cacheManager.set(key, { v: value }, ttlMs);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[withCache] set failed for "${key}"`, err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Inject, Injectable } from '@nestjs/common';
|
||||||
|
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||||
|
import { Cache } from 'cache-manager';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
import { dbOrTx } from '@docmost/db/utils';
|
||||||
@@ -17,6 +19,11 @@ import {
|
|||||||
executeWithCursorPagination,
|
executeWithCursorPagination,
|
||||||
} from '@docmost/db/pagination/cursor-pagination';
|
} from '@docmost/db/pagination/cursor-pagination';
|
||||||
import { PagePermissionMember } from './types/page-permission.types';
|
import { PagePermissionMember } from './types/page-permission.types';
|
||||||
|
import { withCache } from '../../../common/helpers/with-cache';
|
||||||
|
import {
|
||||||
|
CacheKey,
|
||||||
|
PERMISSION_CACHE_TTL_MS,
|
||||||
|
} from '../../../common/helpers/cache-keys';
|
||||||
|
|
||||||
export { PagePermissionMember } from './types/page-permission.types';
|
export { PagePermissionMember } from './types/page-permission.types';
|
||||||
|
|
||||||
@@ -25,6 +32,7 @@ export class PagePermissionRepo {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly groupRepo: GroupRepo,
|
private readonly groupRepo: GroupRepo,
|
||||||
|
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findPageAccessByPageId(
|
async findPageAccessByPageId(
|
||||||
@@ -361,40 +369,8 @@ export class PagePermissionRepo {
|
|||||||
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
||||||
*/
|
*/
|
||||||
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
||||||
const deniedAncestor = await this.db
|
const { canAccess } = await this.canUserEditPage(userId, pageId);
|
||||||
.withRecursive('ancestors', (qb) =>
|
return canAccess;
|
||||||
qb
|
|
||||||
.selectFrom('pages')
|
|
||||||
.select(['pages.id as ancestorId', 'pages.parentPageId'])
|
|
||||||
.where('pages.id', '=', pageId)
|
|
||||||
.unionAll((eb) =>
|
|
||||||
eb
|
|
||||||
.selectFrom('pages')
|
|
||||||
.innerJoin('ancestors', 'ancestors.parentPageId', 'pages.id')
|
|
||||||
.select(['pages.id as ancestorId', 'pages.parentPageId']),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.selectFrom('ancestors')
|
|
||||||
.innerJoin('pageAccess', 'pageAccess.pageId', 'ancestors.ancestorId')
|
|
||||||
.leftJoin('pagePermissions', (join) =>
|
|
||||||
join
|
|
||||||
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
|
||||||
.on((eb) =>
|
|
||||||
eb.or([
|
|
||||||
eb('pagePermissions.userId', '=', userId),
|
|
||||||
eb(
|
|
||||||
'pagePermissions.groupId',
|
|
||||||
'in',
|
|
||||||
this.userGroupIdsSubquery(eb, userId),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.select('pageAccess.pageId')
|
|
||||||
.where('pagePermissions.id', 'is', null)
|
|
||||||
.executeTakeFirst();
|
|
||||||
|
|
||||||
return !deniedAncestor;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -412,43 +388,50 @@ export class PagePermissionRepo {
|
|||||||
canAccess: boolean;
|
canAccess: boolean;
|
||||||
canEdit: boolean;
|
canEdit: boolean;
|
||||||
}> {
|
}> {
|
||||||
const result = await sql<{
|
return withCache(
|
||||||
canAccess: boolean | null;
|
this.cacheManager,
|
||||||
canEdit: boolean | null;
|
CacheKey.PAGE_CAN_EDIT(userId, pageId),
|
||||||
}>`
|
PERMISSION_CACHE_TTL_MS,
|
||||||
WITH RECURSIVE ancestors AS (
|
async () => {
|
||||||
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
const result = await sql<{
|
||||||
FROM pages
|
canAccess: boolean | null;
|
||||||
WHERE id = ${pageId}::uuid
|
canEdit: boolean | null;
|
||||||
UNION ALL
|
}>`
|
||||||
SELECT p.id, p.parent_page_id, a.depth + 1
|
WITH RECURSIVE ancestors AS (
|
||||||
FROM pages p
|
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
||||||
JOIN ancestors a ON a.parent_page_id = p.id
|
FROM pages
|
||||||
)
|
WHERE id = ${pageId}::uuid
|
||||||
SELECT
|
UNION ALL
|
||||||
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
SELECT p.id, p.parent_page_id, a.depth + 1
|
||||||
-- nearest restricted ancestor's highest role wins (DESC: 'writer' > 'reader', NULLS LAST: no-permission after real roles)
|
FROM pages p
|
||||||
(array_agg(pp.role ORDER BY a.depth ASC, pp.role DESC NULLS LAST))[1] = 'writer' AS "canEdit"
|
JOIN ancestors a ON a.parent_page_id = p.id
|
||||||
FROM ancestors a
|
|
||||||
JOIN page_access pa ON pa.page_id = a.ancestor_id
|
|
||||||
LEFT JOIN page_permissions pp ON pp.page_access_id = pa.id
|
|
||||||
AND (
|
|
||||||
pp.user_id = ${userId}::uuid
|
|
||||||
OR pp.group_id IN (
|
|
||||||
SELECT gu.group_id FROM group_users gu WHERE gu.user_id = ${userId}::uuid
|
|
||||||
)
|
)
|
||||||
)
|
SELECT
|
||||||
`.execute(this.db);
|
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
||||||
|
-- nearest restricted ancestor's highest role wins (DESC: 'writer' > 'reader', NULLS LAST: no-permission after real roles)
|
||||||
|
(array_agg(pp.role ORDER BY a.depth ASC, pp.role DESC NULLS LAST))[1] = 'writer' AS "canEdit"
|
||||||
|
FROM ancestors a
|
||||||
|
JOIN page_access pa ON pa.page_id = a.ancestor_id
|
||||||
|
LEFT JOIN page_permissions pp ON pp.page_access_id = pa.id
|
||||||
|
AND (
|
||||||
|
pp.user_id = ${userId}::uuid
|
||||||
|
OR pp.group_id IN (
|
||||||
|
SELECT gu.group_id FROM group_users gu WHERE gu.user_id = ${userId}::uuid
|
||||||
|
)
|
||||||
|
)
|
||||||
|
`.execute(this.db);
|
||||||
|
|
||||||
const row = result.rows[0];
|
const row = result.rows[0];
|
||||||
if (!row || row.canAccess === null) {
|
if (!row || row.canAccess === null) {
|
||||||
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
hasAnyRestriction: true,
|
hasAnyRestriction: true,
|
||||||
canAccess: row.canAccess,
|
canAccess: row.canAccess,
|
||||||
canEdit: row.canAccess && (row.canEdit ?? false),
|
canEdit: row.canAccess && (row.canEdit ?? false),
|
||||||
};
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
||||||
|
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||||
|
import { Cache } from 'cache-manager';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
import { dbOrTx } from '@docmost/db/utils';
|
||||||
@@ -13,6 +15,11 @@ import { MemberInfo, UserSpaceRole } from './types';
|
|||||||
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
||||||
import { GroupRepo } from '@docmost/db/repos/group/group.repo';
|
import { GroupRepo } from '@docmost/db/repos/group/group.repo';
|
||||||
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
||||||
|
import { withCache } from '../../../common/helpers/with-cache';
|
||||||
|
import {
|
||||||
|
CacheKey,
|
||||||
|
PERMISSION_CACHE_TTL_MS,
|
||||||
|
} from '../../../common/helpers/cache-keys';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SpaceMemberRepo {
|
export class SpaceMemberRepo {
|
||||||
@@ -20,6 +27,7 @@ export class SpaceMemberRepo {
|
|||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly groupRepo: GroupRepo,
|
private readonly groupRepo: GroupRepo,
|
||||||
private readonly spaceRepo: SpaceRepo,
|
private readonly spaceRepo: SpaceRepo,
|
||||||
|
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async insertSpaceMember(
|
async insertSpaceMember(
|
||||||
@@ -214,25 +222,36 @@ export class SpaceMemberRepo {
|
|||||||
userId: string,
|
userId: string,
|
||||||
spaceId: string,
|
spaceId: string,
|
||||||
): Promise<UserSpaceRole[]> {
|
): Promise<UserSpaceRole[]> {
|
||||||
const roles = await this.db
|
return withCache(
|
||||||
.selectFrom('spaceMembers')
|
this.cacheManager,
|
||||||
.select(['userId', 'role'])
|
CacheKey.SPACE_ROLES(userId, spaceId),
|
||||||
.where('userId', '=', userId)
|
PERMISSION_CACHE_TTL_MS,
|
||||||
.where('spaceId', '=', spaceId)
|
async () => {
|
||||||
.unionAll(
|
const roles = await this.db
|
||||||
this.db
|
|
||||||
.selectFrom('spaceMembers')
|
.selectFrom('spaceMembers')
|
||||||
.innerJoin('groupUsers', 'groupUsers.groupId', 'spaceMembers.groupId')
|
.select(['userId', 'role'])
|
||||||
.select(['groupUsers.userId', 'spaceMembers.role'])
|
.where('userId', '=', userId)
|
||||||
.where('groupUsers.userId', '=', userId)
|
.where('spaceId', '=', spaceId)
|
||||||
.where('spaceMembers.spaceId', '=', spaceId),
|
.unionAll(
|
||||||
)
|
this.db
|
||||||
.execute();
|
.selectFrom('spaceMembers')
|
||||||
|
.innerJoin(
|
||||||
|
'groupUsers',
|
||||||
|
'groupUsers.groupId',
|
||||||
|
'spaceMembers.groupId',
|
||||||
|
)
|
||||||
|
.select(['groupUsers.userId', 'spaceMembers.role'])
|
||||||
|
.where('groupUsers.userId', '=', userId)
|
||||||
|
.where('spaceMembers.spaceId', '=', spaceId),
|
||||||
|
)
|
||||||
|
.execute();
|
||||||
|
|
||||||
if (!roles || roles.length === 0) {
|
if (!roles || roles.length === 0) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
return roles;
|
return roles;
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserIdsWithSpaceAccess(
|
async getUserIdsWithSpaceAccess(
|
||||||
|
|||||||
Reference in New Issue
Block a user