mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 14:57:37 +00:00
refactor(authz): move to domain-based authz and flatten routes
This commit is contained in:
@@ -96,7 +96,7 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /teams/:teamId/agents/:agentId', () => {
|
||||
describe('PUT /agents/:agentId', () => {
|
||||
it('updates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
@@ -111,7 +111,7 @@ describe('Agent API', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -131,9 +131,9 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/agents/:agentId', () => {
|
||||
describe('DELETE /agents/:agentId', () => {
|
||||
it('deletes an agent', async () => {
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
@@ -142,7 +142,7 @@ describe('Agent API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agent-sessions/:sessionId/entries', () => {
|
||||
describe('GET /agent-sessions/:sessionId/entries', () => {
|
||||
it('returns entries of agent session if user is admin', async () => {
|
||||
const mockEntries = [
|
||||
{
|
||||
@@ -154,7 +154,7 @@ describe('Agent API', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agent-sessions/session1/entries', {
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
@@ -164,16 +164,17 @@ describe('Agent API', () => {
|
||||
expect(data[0].id).toBe('entry1')
|
||||
expect(data[0].entry.step).toBe(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
teamId: 'team1',
|
||||
user: undefined,
|
||||
permission: 'Admin',
|
||||
type: 'agentSession',
|
||||
id: 'session1',
|
||||
})
|
||||
})
|
||||
|
||||
it('denies access if user is not admin', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/agent-sessions/session1/entries', {
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
|
||||
+45
-47
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
@@ -19,9 +19,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
@@ -55,9 +56,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
@@ -88,57 +90,53 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/agents/:agentId',
|
||||
zValidator('json', updateAgentRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.put('/agents/:agentId', zValidator('json', updateAgentRequestSchema), async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/agents/:agentId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.delete('/agents/:agentId', async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
await agentService.deleteAgent({
|
||||
@@ -147,15 +145,15 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/agent-sessions/:sessionId/entries', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
.get('/agent-sessions/:sessionId/entries', async (c) => {
|
||||
const sessionId = c.req.param('sessionId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.AgentSession,
|
||||
id: sessionId,
|
||||
})
|
||||
|
||||
const entries = await agentService.getSessionEntries({ sessionId })
|
||||
|
||||
+11
-11
@@ -4,6 +4,7 @@ import attachmentRoute from './attachment'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { AssetType } from '@/generated/prisma/client'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
@@ -15,16 +16,8 @@ vi.mock('@/api/middleware/auth', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
vi.mock('@/services/authz/authz')
|
||||
vi.mock('@/services/asset/asset')
|
||||
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -37,12 +30,13 @@ describe('Attachment API', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/attachments', async () => {
|
||||
// We only need the id for this test
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(assetService, 'createAsset').mockResolvedValue({ id: 'asset1' } as any)
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
|
||||
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
@@ -58,6 +52,12 @@ describe('Attachment API', () => {
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('asset1')
|
||||
expect(json.uploadUrl).toBe('http://mock-s3-url')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
})
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'test.txt',
|
||||
|
||||
@@ -5,7 +5,7 @@ import { assetService } from '@/services/asset/asset'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { AssetType } from '@/generated/prisma/client'
|
||||
import { ulid } from 'ulid'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
@@ -19,9 +19,10 @@ const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
|
||||
+83
-62
@@ -1,26 +1,46 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { collectionService } from '@/services/collection/collection'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import app from './collection'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { Hono, Context, Next } from 'hono'
|
||||
import collectionRoute from './collection'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
authMiddleware: vi.fn(async (c, next) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user-1', name: 'Test User' } as any)
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Collection: 'collection',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Collection API', () => {
|
||||
const teamId = 'team-1'
|
||||
const projectId = 'project-1'
|
||||
const collectionId = 'col-1'
|
||||
const authMiddleware = async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
}
|
||||
const app = new Hono().use('*', authMiddleware).route('/', collectionRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/projects/:projectId/collections', async () => {
|
||||
it('POST /projects/:projectId/collections', async () => {
|
||||
const mockCreate = vi.spyOn(collectionService, 'createCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'New Collection',
|
||||
@@ -34,33 +54,29 @@ describe('Collection API', () => {
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(
|
||||
`/teams/${teamId}/projects/${projectId}/collections`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
user: { id: 'user-1' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
)
|
||||
const res = await app.request(`/projects/${projectId}/collections`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockCreate).toHaveBeenCalledWith(projectId, expect.any(Object))
|
||||
expect(mockAuthz).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects/:projectId/collections', async () => {
|
||||
it('GET /projects/:projectId/collections', async () => {
|
||||
const mockList = vi.spyOn(collectionService, 'listCollections').mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
@@ -79,18 +95,21 @@ describe('Collection API', () => {
|
||||
pageInfo: { total: 1 },
|
||||
})
|
||||
|
||||
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(`/teams/${teamId}/projects/${projectId}/collections`)
|
||||
const res = await app.request(`/projects/${projectId}/collections`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalled()
|
||||
expect(mockAuthz).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects/:projectId/collections/:collectionId', async () => {
|
||||
it('GET /collections/:collectionId', async () => {
|
||||
const mockGet = vi.spyOn(collectionService, 'getCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Col 1',
|
||||
@@ -104,18 +123,19 @@ describe('Collection API', () => {
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(
|
||||
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`,
|
||||
)
|
||||
const res = await app.request(`/collections/${collectionId}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockGet).toHaveBeenCalledWith(collectionId)
|
||||
expect(mockAuthz).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/projects/:projectId/collections/:collectionId', async () => {
|
||||
it('PATCH /collections/:collectionId', async () => {
|
||||
const mockUpdate = vi.spyOn(collectionService, 'updateCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Updated Name',
|
||||
@@ -129,36 +149,37 @@ describe('Collection API', () => {
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(
|
||||
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated Name' }),
|
||||
},
|
||||
)
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated Name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(collectionId, { name: 'Updated Name' })
|
||||
expect(mockAuthz).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/projects/:projectId/collections/:collectionId', async () => {
|
||||
it('DELETE /collections/:collectionId', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mockDelete = vi.spyOn(collectionService, 'deleteCollection').mockResolvedValue({} as any)
|
||||
const mockAuthz = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request(
|
||||
`/teams/${teamId}/projects/${projectId}/collections/${collectionId}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
},
|
||||
)
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockDelete).toHaveBeenCalledWith(collectionId)
|
||||
expect(mockAuthz).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+21
-21
@@ -1,7 +1,7 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { collectionService } from '@/services/collection/collection'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import {
|
||||
createCollectionRequestSchema,
|
||||
updateCollectionRequestSchema,
|
||||
@@ -26,18 +26,18 @@ function toCollectionInfo(c: Prisma.CollectionGetPayload<Record<string, never>>)
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/teams/:teamId/projects/:projectId/collections',
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('json', createCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId, projectId } = c.req.param()
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.createCollection(projectId, req)
|
||||
@@ -45,18 +45,18 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/projects/:projectId/collections',
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('query', listCollectionsRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId, projectId } = c.req.param()
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collections = await collectionService.listCollections(projectId, req)
|
||||
@@ -67,15 +67,15 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
})
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/projects/:projectId/collections/:collectionId', async (c) => {
|
||||
const { teamId, projectId, collectionId } = c.req.param()
|
||||
.get('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.getCollection(collectionId)
|
||||
@@ -86,33 +86,33 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(toCollectionInfo(collection))
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/projects/:projectId/collections/:collectionId',
|
||||
'/collections/:collectionId',
|
||||
zValidator('json', updateCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { teamId, projectId, collectionId } = c.req.param()
|
||||
const { collectionId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.updateCollection(collectionId, req)
|
||||
return c.json(toCollectionInfo(collection))
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/projects/:projectId/collections/:collectionId', async (c) => {
|
||||
const { teamId, projectId, collectionId } = c.req.param()
|
||||
.delete('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
await collectionService.deleteCollection(collectionId)
|
||||
|
||||
+64
-39
@@ -1,27 +1,30 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
@@ -32,6 +35,7 @@ describe('file api', () => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({ teamId: 'test-team' })
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
@@ -41,13 +45,14 @@ describe('file api', () => {
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId', async () => {
|
||||
it('GET /files/:fileId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
@@ -61,20 +66,21 @@ describe('file api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id')
|
||||
const res = await app.request('/files/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-file')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/files/:fileId', async () => {
|
||||
it('PUT /files/:fileId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
@@ -88,7 +94,7 @@ describe('file api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id', {
|
||||
const res = await app.request('/files/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
@@ -99,17 +105,18 @@ describe('file api', () => {
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/files', async () => {
|
||||
it('DELETE /files', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
const res = await app.request('/files', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
@@ -118,18 +125,19 @@ describe('file api', () => {
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/restore', async () => {
|
||||
it('POST /files/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/restore', {
|
||||
const res = await app.request('/files/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
@@ -138,14 +146,15 @@ describe('file api', () => {
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/:fileId/comments', async () => {
|
||||
it('POST /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'test-id',
|
||||
@@ -160,8 +169,14 @@ describe('file api', () => {
|
||||
sessionId: null,
|
||||
})
|
||||
|
||||
// Mock assetService.getAsset to return teamId for notification
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
project: { teamId: 'test-team' },
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments', {
|
||||
const res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
|
||||
@@ -172,9 +187,10 @@ describe('file api', () => {
|
||||
expect(json.message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
@@ -186,7 +202,7 @@ describe('file api', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId/comments', async () => {
|
||||
it('GET /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.listComments).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
@@ -207,7 +223,7 @@ describe('file api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments')
|
||||
const res = await app.request('/files/test-id/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
@@ -215,9 +231,10 @@ describe('file api', () => {
|
||||
expect(json.data[0].message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
@@ -239,18 +256,24 @@ describe('file api', () => {
|
||||
expect(json.key).toMatch(/^files\//)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
teamId: 'test-team',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 'test-team',
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
it('PATCH /files/:fileId/metadata', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
|
||||
// Mock assetService.getAsset to return teamId for notification
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
project: { teamId: 'test-team' },
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/metadata', {
|
||||
const res = await app.request('/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
|
||||
@@ -259,9 +282,10 @@ describe('file api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
@@ -272,7 +296,7 @@ describe('file api', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/order', async () => {
|
||||
it('PATCH /files/:fileId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
@@ -286,7 +310,7 @@ describe('file api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/order', {
|
||||
const res = await app.request('/files/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
@@ -295,9 +319,10 @@ describe('file api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
|
||||
+51
-37
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
@@ -22,21 +22,22 @@ import type { Prisma } from '@/generated/prisma/client'
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/files/:fileId', async (c) => {
|
||||
.get('/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/order',
|
||||
'/files/:fileId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
@@ -44,24 +45,26 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(fileId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put('/teams/:teamId/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
.put('/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
@@ -71,15 +74,16 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.delete('/teams/:teamId/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
.delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -87,48 +91,51 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
'/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
|
||||
const hasStatus = req.some((m) => m.key === 'status')
|
||||
if (hasStatus) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
if (context?.teamId) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json('')
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
'/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
@@ -143,19 +150,23 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
|
||||
if (context?.teamId) {
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(comment, 201)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
'/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
@@ -163,31 +174,32 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/comments/:commentId', async (c) => {
|
||||
.get('/comments/:commentId', async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
|
||||
const comment = await assetService.getComment(commentId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: comment.assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Comment,
|
||||
id: commentId,
|
||||
})
|
||||
|
||||
const comment = await assetService.getComment(commentId)
|
||||
return c.json(comment)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/files/restore',
|
||||
'/files/restore',
|
||||
zValidator('json', restoreFilesRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
@@ -195,9 +207,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -211,9 +224,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const { file } = c.req.valid('form')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
|
||||
+45
-34
@@ -3,18 +3,21 @@ import { Hono } from 'hono'
|
||||
import folderRoute from './folder'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { searchService } from '@/services/search/search'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
@@ -42,7 +45,7 @@ describe('folder api', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId', async () => {
|
||||
it('GET /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
@@ -56,20 +59,21 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id')
|
||||
const res = await app.request('/folders/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/folders/:folderId', async () => {
|
||||
it('PUT /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
@@ -83,7 +87,7 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id', {
|
||||
const res = await app.request('/folders/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
@@ -94,13 +98,14 @@ describe('folder api', () => {
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders', async () => {
|
||||
it('POST /folders', async () => {
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({
|
||||
id: 'new-id',
|
||||
name: 'new-folder',
|
||||
@@ -114,7 +119,7 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
const res = await app.request('/folders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
|
||||
@@ -125,13 +130,14 @@ describe('folder api', () => {
|
||||
expect(json.name).toBe('new-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'parent-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId/children', async () => {
|
||||
it('GET /folders/:folderId/children', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
@@ -150,7 +156,7 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/children?assetType=folder')
|
||||
const res = await app.request('/folders/test-id/children?assetType=folder')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
@@ -158,17 +164,18 @@ describe('folder api', () => {
|
||||
expect(json.data[0].name).toBe('child-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/folders', async () => {
|
||||
it('DELETE /folders', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
const res = await app.request('/folders', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
@@ -177,18 +184,19 @@ describe('folder api', () => {
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/restore', async () => {
|
||||
it('POST /folders/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/restore', {
|
||||
const res = await app.request('/folders/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
@@ -197,14 +205,15 @@ describe('folder api', () => {
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/:folderId/search', async () => {
|
||||
it('POST /folders/:folderId/search', async () => {
|
||||
vi.mocked(searchService.search).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
@@ -223,7 +232,7 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/search', {
|
||||
const res = await app.request('/folders/test-id/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -237,13 +246,14 @@ describe('folder api', () => {
|
||||
expect(json.data[0].name).toBe('result-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/folders/:folderId/order', async () => {
|
||||
it('PATCH /folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
@@ -257,7 +267,7 @@ describe('folder api', () => {
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/order', {
|
||||
const res = await app.request('/folders/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
@@ -266,9 +276,10 @@ describe('folder api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
|
||||
+75
-83
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { searchService } from '@/services/search/search'
|
||||
import {
|
||||
@@ -16,14 +16,15 @@ import type { Prisma } from '@/generated/prisma/client'
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
.post('/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const newAsset = await assetService.createAsset({
|
||||
@@ -35,7 +36,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(newAsset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/folders/:folderId/order',
|
||||
'/folders/:folderId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
@@ -43,126 +44,117 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(folderId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/teams/:teamId/folders/:folderId',
|
||||
zValidator('json', updateFolderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.put('/folders/:folderId', zValidator('json', updateFolderRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/folders/:folderId', async (c) => {
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.get('/folders/:folderId', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const assetInfo = await assetService.getAsset({ assetId: folderId })
|
||||
return c.json(assetInfo)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/folders/:folderId/children',
|
||||
zValidator('query', listChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
.get('/folders/:folderId/children', zValidator('query', listChildrenRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
})
|
||||
.delete('/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/folders/restore',
|
||||
zValidator('json', restoreFoldersRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/folders/:folderId/search',
|
||||
zValidator('json', searchRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.post('/folders/restore', zValidator('json', restoreFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/folders/:folderId/search', zValidator('json', searchRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
+48
-50
@@ -1,41 +1,18 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import inviteRoute from './invite'
|
||||
import publicInviteRoute from './public-invite'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { inviteService } from '@/services/invite/invite'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
|
||||
vi.mock('@/services/invite/invite', () => ({
|
||||
inviteService: {
|
||||
createTeamInvite: vi.fn(),
|
||||
createProjectInvite: vi.fn(),
|
||||
getInvite: vi.fn(),
|
||||
consumeInvite: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
vi.mock('@/services/invite/invite')
|
||||
vi.mock('@/services/notification/notification')
|
||||
vi.mock('@/services/authz/authz')
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'u1', name: 'Test User' } as any)
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
@@ -43,15 +20,24 @@ vi.mock('@/api/middleware/auth', () => ({
|
||||
const getApp = () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicInviteRoute)
|
||||
.use('*', authMiddleware)
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', inviteRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('Invite API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /invite/:code', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
@@ -59,7 +45,7 @@ describe('Invite API', () => {
|
||||
inviter: { name: 'Inviter' },
|
||||
role: 'editor',
|
||||
used: false,
|
||||
} as never)
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/invite/code123')
|
||||
expect(res.status).toBe(200)
|
||||
@@ -75,9 +61,8 @@ describe('Invite API', () => {
|
||||
|
||||
it('POST /teams/:teamId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
@@ -85,7 +70,7 @@ describe('Invite API', () => {
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t1/invite', {
|
||||
method: 'POST',
|
||||
@@ -105,6 +90,12 @@ describe('Invite API', () => {
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
role: 'editor',
|
||||
@@ -114,9 +105,8 @@ describe('Invite API', () => {
|
||||
|
||||
it('POST /projects/:projectId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
@@ -125,7 +115,7 @@ describe('Invite API', () => {
|
||||
project: { id: 'p1', name: 'Project A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/p1/invite', {
|
||||
method: 'POST',
|
||||
@@ -147,6 +137,12 @@ describe('Invite API', () => {
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
role: 'reviewer',
|
||||
@@ -156,19 +152,21 @@ describe('Invite API', () => {
|
||||
|
||||
it('POST /join (Team)', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
const { notificationService } = await import('@/services/notification/notification')
|
||||
|
||||
vi.mocked(notificationService.create).mockResolvedValue(undefined as never)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.create).mockResolvedValue(undefined as any)
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as never)
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/join', {
|
||||
method: 'POST',
|
||||
|
||||
+5
-3
@@ -6,7 +6,7 @@ import {
|
||||
joinRequestSchema,
|
||||
InviteInfo,
|
||||
} from '@/dtos/invite'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { inviteService } from '@/services/invite/invite'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
@@ -40,9 +40,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
@@ -63,9 +64,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createProjectInvite({
|
||||
|
||||
+98
-47
@@ -1,36 +1,30 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import metadataRoute from './metadata'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { Prisma } from '@/generated/prisma/client.ts'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz')
|
||||
vi.mock('@/services/metadata/metadata')
|
||||
|
||||
describe('metadata api', () => {
|
||||
const app = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', metadataRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/fields', async () => {
|
||||
@@ -41,11 +35,11 @@ describe('metadata api', () => {
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
}
|
||||
|
||||
vi.spyOn(metadataService, 'listTeamFields').mockResolvedValue([mockField])
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.listTeamFields).mockResolvedValue([mockField as any]) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -54,6 +48,12 @@ describe('metadata api', () => {
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
expect(json[0].aiAutofill).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/fields', async () => {
|
||||
@@ -64,11 +64,11 @@ describe('metadata api', () => {
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
}
|
||||
|
||||
vi.spyOn(metadataService, 'createTeamField').mockResolvedValue(mockField)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.createTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -82,6 +82,12 @@ describe('metadata api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('newfield')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/fields', async () => {
|
||||
@@ -92,13 +98,12 @@ describe('metadata api', () => {
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
}
|
||||
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([
|
||||
{ field: mockField, visible: true },
|
||||
vi.mocked(metadataService.listProjectFields).mockResolvedValue([
|
||||
{ field: mockField, visible: true } as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -106,12 +111,19 @@ describe('metadata api', () => {
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].visible).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /projects/:projectId/fields/order', async () => {
|
||||
vi.spyOn(metadataService, 'updateProjectFieldsOrder').mockResolvedValue(undefined)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(metadataService.updateProjectFieldsOrder).mockResolvedValue(undefined as any)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -122,33 +134,72 @@ describe('metadata api', () => {
|
||||
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
|
||||
{ fieldId: 'field1', visible: true },
|
||||
])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/fields/:fieldId', async () => {
|
||||
vi.spyOn(metadataService, 'deleteTeamField').mockResolvedValue(undefined)
|
||||
it('DELETE /fields/:fieldId', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.getFieldByKey).mockResolvedValue({
|
||||
key: 'f1',
|
||||
teamId: 't1',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(metadataService.deleteTeamField).mockResolvedValue(undefined as any)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields/f1', {
|
||||
const res = await app.request('/fields/f1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockResolvedValue(undefined)
|
||||
it('PUT /fields/:fieldId', async () => {
|
||||
const mockField = {
|
||||
key: 'f1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
teamId: 't1',
|
||||
}
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/files/f1/metadata', {
|
||||
method: 'PATCH',
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.getFieldByKey).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.updateTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/fields/f1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'resolution_width', value: 1920 }]),
|
||||
body: JSON.stringify({
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith('f1', [
|
||||
{ key: 'resolution_width', value: 1920 },
|
||||
])
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+52
-83
@@ -1,13 +1,11 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { z } from 'zod'
|
||||
import { Hono } from 'hono'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import {
|
||||
createFieldRequestSchema,
|
||||
updateFieldRequestSchema,
|
||||
updateProjectFieldsOrderRequestSchema,
|
||||
updateAssetMetadataRequestSchema,
|
||||
FieldInfo,
|
||||
} from '@/dtos/metadata'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
@@ -37,9 +35,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createTeamField(teamId, req)
|
||||
@@ -50,45 +49,66 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listTeamFields(teamId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f)))
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
.put('/fields/:fieldId', zValidator('json', updateFieldRequestSchema), async (c) => {
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: fieldId,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateTeamField(teamId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/fields/:fieldId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
// We need teamId/projectId for metadataService. But we can get them from the field itself.
|
||||
// Or we can refactor metadataService to not require them if we already have the field.
|
||||
// For now, let's just fetch it once to get the context for the service call.
|
||||
const field = await metadataService.getFieldByKey(fieldId)
|
||||
if (!field) throw new Error('Field not found')
|
||||
|
||||
let updated
|
||||
if (field.projectId) {
|
||||
updated = await metadataService.updateProjectField(field.projectId, fieldId, req)
|
||||
} else if (field.teamId) {
|
||||
updated = await metadataService.updateTeamField(field.teamId, fieldId, req)
|
||||
} else {
|
||||
throw new Error('Field has no context')
|
||||
}
|
||||
|
||||
return c.json(toFieldInfo(updated))
|
||||
})
|
||||
.delete('/fields/:fieldId', async (c) => {
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: fieldId,
|
||||
})
|
||||
|
||||
await metadataService.deleteTeamField(teamId, fieldId)
|
||||
const field = await metadataService.getFieldByKey(fieldId)
|
||||
if (!field) throw new Error('Field not found')
|
||||
|
||||
if (field.projectId) {
|
||||
await metadataService.deleteProjectField(field.projectId, fieldId)
|
||||
} else if (field.teamId) {
|
||||
await metadataService.deleteTeamField(field.teamId, fieldId)
|
||||
} else {
|
||||
throw new Error('Field has no context')
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
@@ -97,9 +117,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createProjectField(projectId, req)
|
||||
@@ -110,9 +131,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listProjectFields(user.id, projectId)
|
||||
@@ -127,68 +149,15 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/projects/:projectId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateProjectField(projectId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/projects/:projectId/fields/:fieldId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.deleteProjectField(projectId, fieldId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId') // Actually maps to assetId
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -1,52 +1,38 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz')
|
||||
vi.mock('@/services/notification/notification')
|
||||
|
||||
describe('notification api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockList: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockMarkRead: any
|
||||
const app = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', notificationRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
mockList = vi.fn()
|
||||
mockMarkRead = vi.fn()
|
||||
vi.spyOn(notificationService, 'list').mockImplementation(mockList)
|
||||
vi.spyOn(notificationService, 'markRead').mockImplementation(mockMarkRead)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications', async () => {
|
||||
mockList.mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }],
|
||||
vi.mocked(notificationService.list).mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 1, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -55,17 +41,24 @@ describe('notification api', () => {
|
||||
expect(json.pageInfo.total).toBe(1)
|
||||
expect(json.pageInfo.cursor).toBe('abc')
|
||||
|
||||
expect(mockList).toHaveBeenCalledWith('t1', 'user1', {
|
||||
expect(notificationService.list).toHaveBeenCalledWith('t1', 'user1', {
|
||||
unreadOnly: true,
|
||||
after: undefined,
|
||||
pageSize: 10,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/read', async () => {
|
||||
mockMarkRead.mockResolvedValue(undefined)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.markRead).mockResolvedValue(undefined as any)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -73,6 +66,12 @@ describe('notification api', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockMarkRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
expect(notificationService.markRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
@@ -20,9 +20,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await notificationService.list(teamId, user.id, {
|
||||
@@ -50,9 +51,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await notificationService.markRead(teamId, user.id, req.notificationId)
|
||||
|
||||
+73
-74
@@ -1,69 +1,40 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import projectRoute from './project'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz')
|
||||
vi.mock('@/services/project/project')
|
||||
vi.mock('@/services/asset/asset')
|
||||
|
||||
describe('project api', () => {
|
||||
let mockListProjects: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProjectTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListProjectMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockReparentAssets: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const app = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', projectRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
mockListProjects = vi.fn()
|
||||
mockCreateProject = vi.fn()
|
||||
mockUpdateProject = vi.fn()
|
||||
mockGetProject = vi.fn()
|
||||
mockGetProjectTeam = vi.fn()
|
||||
mockListProjectMembers = vi.fn()
|
||||
mockReparentAssets = vi.fn()
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(projectService, 'listProjects').mockImplementation(mockListProjects)
|
||||
vi.spyOn(projectService, 'createProject').mockImplementation(mockCreateProject)
|
||||
vi.spyOn(projectService, 'updateProject').mockImplementation(mockUpdateProject)
|
||||
vi.spyOn(projectService, 'getProject').mockImplementation(mockGetProject)
|
||||
vi.spyOn(projectService, 'getProjectTeam').mockImplementation(mockGetProjectTeam)
|
||||
vi.spyOn(projectService, 'listProjectMembers').mockImplementation(mockListProjectMembers)
|
||||
vi.spyOn(assetService, 'reparentAssets').mockImplementation(mockReparentAssets)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects', async () => {
|
||||
mockListProjects.mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }],
|
||||
vi.mocked(projectService.listProjects).mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 100, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects?page_size=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -71,16 +42,21 @@ describe('project api', () => {
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(100)
|
||||
expect(json.data[0].id).toBe('foo')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/projects', async () => {
|
||||
mockCreateProject.mockResolvedValue({
|
||||
vi.mocked(projectService.createProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'foo.png',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -92,17 +68,22 @@ describe('project api', () => {
|
||||
expect(json.id).toBe('foo')
|
||||
expect(json.name).toBe('foo.png')
|
||||
expect(json.coverImage).toBe('http://s3/bucket/key')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: 't',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/projects/:projectId', async () => {
|
||||
mockUpdateProject.mockResolvedValue({
|
||||
it('PUT /projects/:projectId', async () => {
|
||||
vi.mocked(projectService.updateProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'updated',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects/foo', {
|
||||
const res = await app.request('/projects/foo', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'updated' }),
|
||||
@@ -111,39 +92,54 @@ describe('project api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('updated')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: 'foo',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId', async () => {
|
||||
mockGetProject.mockResolvedValue({
|
||||
vi.mocked(projectService.getProject).mockResolvedValue({
|
||||
id: 'p',
|
||||
name: 'foo.png',
|
||||
rootFolder: 'root_folder_id',
|
||||
})
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.rootFolder).toBe('root_folder_id')
|
||||
expect(json.id).toBe('p')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/team', async () => {
|
||||
mockGetProjectTeam.mockResolvedValue('teamId')
|
||||
vi.mocked(projectService.getProjectTeam).mockResolvedValue('teamId')
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/team')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.teamId).toBe('teamId')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/reparent', async () => {
|
||||
mockReparentAssets.mockResolvedValue(undefined)
|
||||
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/reparent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -154,22 +150,25 @@ describe('project api', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(1, {
|
||||
assetId: 'new_parent_id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'new_parent_id',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(2, {
|
||||
assetId: 'asset_1',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_1',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(3, {
|
||||
assetId: 'asset_2',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_2',
|
||||
})
|
||||
expect(mockReparentAssets).toHaveBeenCalledWith({
|
||||
expect(assetService.reparentAssets).toHaveBeenCalledWith({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
creatorId: 'user1',
|
||||
|
||||
+41
-32
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset'
|
||||
@@ -22,9 +22,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const newProject = await projectService.createProject(user, {
|
||||
@@ -34,28 +35,25 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(newProject)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/projects/:projectId',
|
||||
zValidator('json', updateProjectRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.put('/projects/:projectId', zValidator('json', updateProjectRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(updatedProject)
|
||||
},
|
||||
)
|
||||
return c.json(updatedProject)
|
||||
})
|
||||
.get(
|
||||
'/projects/:projectId/recently-deleted',
|
||||
zValidator('query', recentlyDeletedRequestSchema),
|
||||
@@ -65,9 +63,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
@@ -86,9 +85,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
@@ -112,9 +112,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const p = await projectService.getProject(projectId)
|
||||
@@ -125,9 +126,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await projectService.deleteProject(projectId)
|
||||
@@ -138,9 +140,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
@@ -152,9 +155,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
@@ -168,9 +172,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
@@ -186,17 +191,19 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Edit permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -214,17 +221,19 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Read permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+91
-55
@@ -1,53 +1,38 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import providerRoute from './provider'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('provider api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', providerRoute)
|
||||
vi.mock('@/services/authz/authz')
|
||||
vi.mock('@/services/provider/provider')
|
||||
|
||||
let mockListByTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockDelete: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
describe('provider api', () => {
|
||||
const app = new Hono()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', providerRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
mockListByTeam = vi.spyOn(providerService, 'listByTeam')
|
||||
mockCreate = vi.spyOn(providerService, 'create')
|
||||
mockUpdate = vi.spyOn(providerService, 'update')
|
||||
mockDelete = vi.spyOn(providerService, 'delete')
|
||||
|
||||
// Default to admin permission granted
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers returns providers', async () => {
|
||||
mockListByTeam.mockResolvedValue([{ id: 'p1', name: 'openai', config: {} }])
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.listByTeam).mockResolvedValue([
|
||||
{ id: 'p1', name: 'openai', config: {} },
|
||||
] as any)
|
||||
|
||||
const res = await app.request('/teams/t1/providers')
|
||||
|
||||
@@ -55,26 +40,37 @@ describe('provider api', () => {
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
permission: 'Admin',
|
||||
}),
|
||||
)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers/:id/models returns models', async () => {
|
||||
const mockListModelsByProvider = vi.spyOn(providerService, 'listModelsByProvider')
|
||||
it('GET /providers/:id/models returns models', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockListModelsByProvider.mockResolvedValue([{ modelId: 'm1', name: 'model1' } as any])
|
||||
vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.listModelsByProvider).mockResolvedValue([
|
||||
{ modelId: 'm1', name: 'model1' },
|
||||
] as any)
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1/models')
|
||||
const res = await app.request('/providers/p1/models')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].modelId).toBe('m1')
|
||||
expect(mockListModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(providerService.listModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers creates provider', async () => {
|
||||
@@ -96,7 +92,14 @@ describe('provider api', () => {
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.create).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as any)
|
||||
|
||||
const res = await app.request('/teams/t1/providers', {
|
||||
method: 'POST',
|
||||
@@ -107,10 +110,16 @@ describe('provider api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('openai')
|
||||
expect(mockCreate).toHaveBeenCalledWith('t1', 'openai', config, models)
|
||||
expect(providerService.create).toHaveBeenCalledWith('t1', 'openai', config, models)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/providers/:id updates provider', async () => {
|
||||
it('PUT /providers/:id updates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://new-url.com',
|
||||
api: 'openai-completions',
|
||||
@@ -129,9 +138,19 @@ describe('provider api', () => {
|
||||
},
|
||||
},
|
||||
]
|
||||
mockUpdate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.update).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as any)
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config, models }),
|
||||
@@ -140,19 +159,36 @@ describe('provider api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.config.baseUrl).toBe('https://new-url.com')
|
||||
expect(mockUpdate).toHaveBeenCalledWith('t1', 'p1', config, models)
|
||||
expect(providerService.update).toHaveBeenCalledWith('t1', 'p1', config, models)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/providers/:id deletes provider', async () => {
|
||||
mockDelete.mockResolvedValue({ id: 'p1' })
|
||||
it('DELETE /providers/:id deletes provider', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.getById).mockResolvedValue({ id: 'p1', teamId: 't1' } as any)
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(providerService.delete).mockResolvedValue({ id: 'p1' } as any)
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(providerService.delete).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
+35
-28
@@ -1,6 +1,6 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
@@ -13,27 +13,31 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const providers = await providerService.listByTeam(teamId)
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.get('/teams/:teamId/providers/:id/models', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
.get('/providers/:id/models', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const models = await providerService.listModelsByProvider(teamId, id)
|
||||
const provider = await providerService.getById(id)
|
||||
if (!provider) throw new Error('Provider not found')
|
||||
|
||||
const models = await providerService.listModelsByProvider(provider.teamId, id)
|
||||
return c.json(models)
|
||||
})
|
||||
|
||||
@@ -43,47 +47,50 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const { name, config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const provider = await providerService.create(teamId, name, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.put(
|
||||
'/teams/:teamId/providers/:id',
|
||||
zValidator('json', updateProviderRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
.put('/providers/:id', zValidator('json', updateProviderRequestSchema), async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const provider = await providerService.update(teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
},
|
||||
)
|
||||
const providerBefore = await providerService.getById(id)
|
||||
if (!providerBefore) throw new Error('Provider not found')
|
||||
|
||||
.delete('/teams/:teamId/providers/:id', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const provider = await providerService.update(providerBefore.teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.delete('/providers/:id', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
await providerService.delete(teamId, id)
|
||||
const providerBefore = await providerService.getById(id)
|
||||
if (!providerBefore) throw new Error('Provider not found')
|
||||
|
||||
await providerService.delete(providerBefore.teamId, id)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
|
||||
+53
-11
@@ -5,6 +5,7 @@ import publicShareRoute from './public-share'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -20,9 +21,14 @@ vi.mock('@/services/authz/authz', () => ({
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Share: 'share',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -34,6 +40,7 @@ describe('Share API', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
@@ -102,7 +109,7 @@ describe('Share API', () => {
|
||||
})
|
||||
|
||||
// Protected Routes
|
||||
describe('POST /teams/:teamId/projects/:projectId/shares', () => {
|
||||
describe('POST /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
@@ -116,7 +123,7 @@ describe('Share API', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'My Share' }),
|
||||
@@ -125,22 +132,36 @@ describe('Share API', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.id).toBe('share1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/projects/:projectId/shares', () => {
|
||||
describe('GET /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectId: 'project1',
|
||||
@@ -149,7 +170,7 @@ describe('Share API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/shares/:shareId', () => {
|
||||
describe('GET /shares/:shareId', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
@@ -163,16 +184,23 @@ describe('Share API', () => {
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1', {
|
||||
const res = await app.request('/shares/share1', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Share,
|
||||
id: 'share1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/shares/:shareId/assets', () => {
|
||||
describe('POST /shares/:shareId/assets', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
@@ -187,7 +215,7 @@ describe('Share API', () => {
|
||||
})
|
||||
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1/assets', {
|
||||
const res = await app.request('/shares/share1/assets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset1'] }),
|
||||
@@ -196,6 +224,20 @@ describe('Share API', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.addedCount).toBe(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Share,
|
||||
id: 'share1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
|
||||
})
|
||||
})
|
||||
|
||||
+50
-55
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
@@ -14,7 +14,7 @@ type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('json', createShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
@@ -22,9 +22,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, req)
|
||||
@@ -32,7 +33,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('query', listShareLinksRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
@@ -40,9 +41,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const res = await shareService.listProjectShareLinks({
|
||||
@@ -53,91 +55,84 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
.get('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/shares/:shareId',
|
||||
zValidator('json', updateShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
})
|
||||
.delete('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.deleteShareLink(shareId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/shares/:shareId/assets',
|
||||
zValidator('json', addAssetToShareRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
.post('/shares/:shareId/assets', zValidator('json', addAssetToShareRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
// Also check if user has read permission on the source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
// Also check if user has read permission on the source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
}
|
||||
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
})
|
||||
.delete('/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const assetId = c.req.param('assetId') // symlink asset id
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.removeAssetFromShare(shareId, assetId)
|
||||
|
||||
+41
-11
@@ -3,7 +3,7 @@ import { Hono } from 'hono'
|
||||
import skillRoute from './skill'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -16,12 +16,16 @@ vi.mock('@/api/middleware/auth', () => ({
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Skill: 'skill',
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -30,6 +34,7 @@ describe('Skill API', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/skills', () => {
|
||||
@@ -56,7 +61,11 @@ describe('Skill API', () => {
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ skills: mockSkills })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ permission: 'admin' }),
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -83,6 +92,13 @@ describe('Skill API', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
|
||||
})
|
||||
|
||||
@@ -113,7 +129,7 @@ describe('Skill API', () => {
|
||||
})
|
||||
|
||||
test('Forbidden without Admin permission', async () => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockRejectedValueOnce(new Error('Forbidden'))
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
@@ -125,21 +141,28 @@ describe('Skill API', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/skills/:id', () => {
|
||||
describe('DELETE /skills/:id', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1', {
|
||||
const res = await app.request('/skills/skill1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Skill,
|
||||
id: 'skill1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /teams/:teamId/skills/:id/config', () => {
|
||||
describe('PATCH /skills/:id/config', () => {
|
||||
test('Success', async () => {
|
||||
const mockConfig = {
|
||||
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
|
||||
@@ -156,7 +179,7 @@ describe('Skill API', () => {
|
||||
}
|
||||
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1/config', {
|
||||
const res = await app.request('/skills/skill1/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ config: mockConfig }),
|
||||
@@ -164,6 +187,13 @@ describe('Skill API', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Skill,
|
||||
id: 'skill1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
|
||||
})
|
||||
})
|
||||
|
||||
+21
-23
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
@@ -13,9 +13,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(teamId)
|
||||
@@ -27,9 +28,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
try {
|
||||
@@ -42,38 +44,34 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
throw err
|
||||
}
|
||||
})
|
||||
.delete('/teams/:teamId/skills/:id', async (c) => {
|
||||
.delete('/skills/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/skills/:id/config',
|
||||
zValidator('json', updateSkillConfigRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
.patch('/skills/:id/config', zValidator('json', updateSkillConfigRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
},
|
||||
)
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
+62
-1
@@ -5,16 +5,20 @@ import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { userMetadataService } from '@/services/user-metadata/user-metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
@@ -53,6 +57,7 @@ describe('team api', () => {
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
|
||||
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -118,6 +123,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.role).toBe('owner')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
|
||||
})
|
||||
|
||||
@@ -129,6 +141,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
|
||||
})
|
||||
|
||||
@@ -140,6 +159,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('some_value')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
@@ -155,6 +181,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('new_value')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
|
||||
})
|
||||
|
||||
@@ -170,6 +203,13 @@ describe('team api', () => {
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(2)
|
||||
expect(data[0].key).toBe('key1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
|
||||
})
|
||||
|
||||
@@ -186,6 +226,13 @@ describe('team api', () => {
|
||||
const data = await res.json()
|
||||
expect(data.key).toBe('key1')
|
||||
expect(data.value).toBe('value1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
|
||||
})
|
||||
|
||||
@@ -197,6 +244,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.allowedDomains).toEqual(['example.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
@@ -212,6 +266,13 @@ describe('team api', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.allowedDomains).toEqual(['new.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', { allowedDomains: ['new.com'] })
|
||||
})
|
||||
})
|
||||
|
||||
+17
-9
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { userMetadataService } from '@/services/user-metadata/user-metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
@@ -64,9 +64,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const me = await teamService.getMe({
|
||||
@@ -82,9 +83,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
@@ -99,9 +101,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
@@ -116,9 +119,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.updateSettings(teamId, req.key, req.value)
|
||||
@@ -130,9 +134,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.getSandboxSettings(teamId)
|
||||
@@ -147,9 +152,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.updateSandboxSettings(teamId, req)
|
||||
@@ -161,9 +167,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.listMetadata(user.id, teamId)
|
||||
@@ -179,9 +186,10 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
|
||||
|
||||
+28
-1
@@ -5,6 +5,7 @@ import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { uploadService } from '@/services/upload/upload'
|
||||
import type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload'
|
||||
import type { PaginatedData } from '@/services/pagination'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// We use any here because mocking Hono context and middleware
|
||||
@@ -19,13 +20,17 @@ vi.mock('@/api/middleware/auth', () => ({
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
@@ -39,6 +44,7 @@ describe('Upload API', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/upload/tasks', async () => {
|
||||
@@ -53,6 +59,13 @@ describe('Upload API', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.listUploadTasks).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -73,6 +86,13 @@ describe('Upload API', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.createUploadTask).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -88,6 +108,13 @@ describe('Upload API', () => {
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
|
||||
fileId: 'file1',
|
||||
})
|
||||
|
||||
+18
-4
@@ -7,7 +7,7 @@ import {
|
||||
localUploadQuerySchema,
|
||||
} from '@/dtos/upload'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3'
|
||||
@@ -48,9 +48,17 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const params = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const tasks = await uploadService.listUploadTasks(user.id, params)
|
||||
return c.json(tasks)
|
||||
})
|
||||
@@ -58,15 +66,14 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
'/teams/:teamId/upload/tasks',
|
||||
zValidator('json', createUploadTaskRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const resp = await uploadService.createUploadTask(user.id, req)
|
||||
@@ -82,6 +89,13 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
|
||||
@@ -4,16 +4,21 @@ import versionStackRoute from './versionStack'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { versionStackService } from '@/services/versionStack/versionStack'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService, ResourceType, Permission } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
@@ -35,6 +40,7 @@ describe('versionStack api', () => {
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -61,6 +67,13 @@ describe('versionStack api', () => {
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockAssetInfo)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockCreateVersionStack).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
creatorId: 'user1',
|
||||
@@ -68,28 +81,15 @@ describe('versionStack api', () => {
|
||||
})
|
||||
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ wrongField: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockCreateVersionStack).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks/:stackID/order', () => {
|
||||
describe('POST /version_stacks/:stackID/order', () => {
|
||||
it('should change order and return 200', async () => {
|
||||
mockChangeStackFileVersion.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
const res = await app.request('/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
|
||||
@@ -97,28 +97,22 @@ describe('versionStack api', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'f1',
|
||||
beforeId: 'f2',
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1' }), // missing beforeId
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockChangeStackFileVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /projects/:projectID/version_stacks/:stackID/versions', () => {
|
||||
describe('GET /version_stacks/:stackID/versions', () => {
|
||||
it('should return stack versions', async () => {
|
||||
const mockVersions = [
|
||||
{
|
||||
@@ -134,7 +128,7 @@ describe('versionStack api', () => {
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/versions', {
|
||||
const res = await app.request('/version_stacks/stack1/versions', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
@@ -142,6 +136,13 @@ describe('versionStack api', () => {
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockVersions)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { versionStackService } from '@/services/versionStack/versionStack'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
import {
|
||||
createVersionStackRequestSchema,
|
||||
changeStackFileVersionRequestSchema,
|
||||
@@ -23,9 +23,10 @@ const route = app
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const stack = await versionStackService.createVersionStack({
|
||||
@@ -40,18 +41,18 @@ const route = app
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/projects/:projectId/version_stacks/:stackId/order',
|
||||
'/version_stacks/:stackId/order',
|
||||
zValidator('json', changeStackFileVersionRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
await versionStackService.changeStackFileVersion({
|
||||
@@ -63,15 +64,15 @@ const route = app
|
||||
return new Response(null, { status: 200 })
|
||||
},
|
||||
)
|
||||
.get('/projects/:projectId/version_stacks/:stackId/versions', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
.get('/version_stacks/:stackId/versions', async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
const versions = await assetService.getStackVersions(stackId)
|
||||
|
||||
+39
-16
@@ -1,21 +1,21 @@
|
||||
import { prisma } from '@/db'
|
||||
import {
|
||||
AncestorFolder,
|
||||
AssetInfo,
|
||||
AttachmentInfo,
|
||||
ChildPreview,
|
||||
CommentInfo,
|
||||
CopyAssetsRequest,
|
||||
CreateAssetRequest,
|
||||
CreateCommentRequest,
|
||||
FieldValueInfo,
|
||||
GetAssetRequest,
|
||||
ListChildrenRequest,
|
||||
PreviewInfo,
|
||||
ReparentAssetsRequest,
|
||||
UpdateAssetNameRequest,
|
||||
UpdateAssetOrderRequest,
|
||||
UserInfo,
|
||||
AncestorFolder,
|
||||
AssetInfo,
|
||||
AttachmentInfo,
|
||||
ChildPreview,
|
||||
CommentInfo,
|
||||
CopyAssetsRequest,
|
||||
CreateAssetRequest,
|
||||
CreateCommentRequest,
|
||||
FieldValueInfo,
|
||||
GetAssetRequest,
|
||||
ListChildrenRequest,
|
||||
PreviewInfo,
|
||||
ReparentAssetsRequest,
|
||||
UpdateAssetNameRequest,
|
||||
UpdateAssetOrderRequest,
|
||||
UserInfo,
|
||||
} from '@/dtos/asset'
|
||||
import { Asset, AssetStatus, AssetType, Prisma, StorageKey } from '@/generated/prisma/client.ts'
|
||||
import { logger } from '@/logger'
|
||||
@@ -830,6 +830,29 @@ export class AssetService {
|
||||
return info
|
||||
}
|
||||
|
||||
async getAssetContext(assetId: string): Promise<{ teamId: string; projectId?: string } | null> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: {
|
||||
projectId: true,
|
||||
project: { select: { teamId: true } },
|
||||
teamRootFolder: { select: { id: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset) return null
|
||||
|
||||
if (asset.project) {
|
||||
return { teamId: asset.project.teamId, projectId: asset.projectId ?? undefined }
|
||||
}
|
||||
|
||||
if (asset.teamRootFolder) {
|
||||
return { teamId: asset.teamRootFolder.id }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async resolveTargetAssetId(assetId: string): Promise<string> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
|
||||
@@ -2,7 +2,7 @@ import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { prisma } from '@/db'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
|
||||
|
||||
describe('AuthzService', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -52,6 +52,18 @@ describe('AuthzService', () => {
|
||||
},
|
||||
})
|
||||
|
||||
// Collection
|
||||
const collection = await prisma.collection.create({
|
||||
data: {
|
||||
name: 'Collection A',
|
||||
projectId: project.id,
|
||||
filter: {
|
||||
sourceFolderId: 'root',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Project Scope User
|
||||
const userProjectEditor = await prisma.user.create({
|
||||
data: { name: 'p_editor', email: 'p_editor@example.com', password: 'pass' },
|
||||
@@ -72,7 +84,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Owner can Admin Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
@@ -81,7 +94,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Editor cannot Admin Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userEditor,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
@@ -90,7 +104,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Editor can Edit Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
@@ -99,7 +114,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Reviewer cannot Edit Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userReviewer,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
@@ -108,7 +124,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Reviewer can Read Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userReviewer,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
@@ -117,7 +134,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Non-member cannot Read Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userOther,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
@@ -127,7 +145,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Project Editor can Edit Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
@@ -136,7 +155,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Project Editor cannot Admin Project',
|
||||
req: {
|
||||
projectId: project.id,
|
||||
type: ResourceType.Project,
|
||||
id: project.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Admin,
|
||||
},
|
||||
@@ -145,7 +165,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Project Scope User can Read Team',
|
||||
req: {
|
||||
teamId: team.id,
|
||||
type: ResourceType.Team,
|
||||
id: team.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
@@ -154,7 +175,8 @@ describe('AuthzService', () => {
|
||||
{
|
||||
name: 'Project Scope User cannot Edit Team',
|
||||
req: {
|
||||
teamId: team.id,
|
||||
type: ResourceType.Team,
|
||||
id: team.id,
|
||||
user: userProjectEditor,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
@@ -162,22 +184,35 @@ describe('AuthzService', () => {
|
||||
errMessage: 'User has only project scope',
|
||||
},
|
||||
{
|
||||
name: 'Resolve Team from Asset ID',
|
||||
name: 'Resolve Context from Asset',
|
||||
req: {
|
||||
assetId: asset.id,
|
||||
type: ResourceType.Asset,
|
||||
id: asset.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Asset without Project',
|
||||
name: 'Resolve Context from Collection',
|
||||
req: {
|
||||
assetId: '01HJXXW6A61234567890ABCDEF',
|
||||
type: ResourceType.Collection,
|
||||
id: collection.id,
|
||||
user: userOwner,
|
||||
permission: Permission.Edit,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: 'Asset Not Found',
|
||||
req: {
|
||||
type: ResourceType.Asset,
|
||||
id: '01HJXXW6A61234567890ABCDEF',
|
||||
user: userOwner,
|
||||
permission: Permission.Read,
|
||||
},
|
||||
wantErr: true,
|
||||
errMessage: 'Asset not found',
|
||||
},
|
||||
]
|
||||
|
||||
@@ -191,13 +226,13 @@ describe('AuthzService', () => {
|
||||
} catch (e: any) {
|
||||
err = e
|
||||
}
|
||||
expect(err).toBeDefined()
|
||||
expect(err, tt.name).toBeDefined()
|
||||
if (tt.errMessage) {
|
||||
expect(err.message).include(tt.errMessage)
|
||||
}
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await expect(authzService.hasPermission(tt.req as any)).resolves.toBeUndefined()
|
||||
await expect(authzService.hasPermission(tt.req as any), tt.name).resolves.toBeUndefined()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
+163
-34
@@ -8,46 +8,35 @@ export enum Permission {
|
||||
Admin = 'Admin',
|
||||
}
|
||||
|
||||
export enum ResourceType {
|
||||
Team = 'team',
|
||||
Project = 'project',
|
||||
Asset = 'asset',
|
||||
Collection = 'collection',
|
||||
Agent = 'agent',
|
||||
Share = 'share',
|
||||
MetadataField = 'metadataField',
|
||||
Skill = 'skill',
|
||||
Provider = 'provider',
|
||||
Invite = 'invite',
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
}
|
||||
|
||||
export interface AuthzRequest {
|
||||
teamId?: string
|
||||
projectId?: string
|
||||
assetId?: string
|
||||
user: User
|
||||
permission: Permission
|
||||
type: ResourceType
|
||||
id: string
|
||||
}
|
||||
|
||||
export class AuthzService {
|
||||
async hasPermission(req: AuthzRequest): Promise<void> {
|
||||
if (!req.user) throw new Error('User is required')
|
||||
|
||||
let projectId = req.projectId
|
||||
let teamId: string | undefined
|
||||
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
|
||||
|
||||
// 1. Resolve ProjectID and TeamID
|
||||
if (req.assetId) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: req.assetId },
|
||||
select: { projectId: true },
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (!asset.projectId) throw new Error(`Asset ${req.assetId} does not belong to a project`)
|
||||
|
||||
projectId = asset.projectId
|
||||
}
|
||||
|
||||
if (projectId) {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id: projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!proj) throw new Error('Project not found')
|
||||
teamId = proj.teamId
|
||||
} else {
|
||||
if (!req.teamId) throw new Error('Project ID or Team ID is required')
|
||||
teamId = req.teamId
|
||||
}
|
||||
|
||||
// 2. Check Team Membership
|
||||
// 1. Check Team Membership
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
@@ -59,15 +48,17 @@ export class AuthzService {
|
||||
|
||||
if (!member) throw new Error('User is not a member of the team')
|
||||
|
||||
// 3. Check Scope
|
||||
// 2. Check Scope
|
||||
if (member.scope === 'team') {
|
||||
return this.checkRole(member.role, req.permission)
|
||||
}
|
||||
|
||||
// 4. Scope is Project
|
||||
// 3. Scope is Project
|
||||
if (!projectId) {
|
||||
// User has project scope but no project context provided.
|
||||
// Allow Read access to team context (e.g. ListProjects)
|
||||
// User has project scope but no project context provided (e.g. Team-level resource)
|
||||
// If it's a team-level resource, project-scoped users shouldn't have access except for Read maybe?
|
||||
// But usually team resources like Skills/Providers are managed by Team Owners/Editors.
|
||||
// For now, let's keep the logic: project-scoped users can't access team-level resources unless it's Read (like ListProjects).
|
||||
if (req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
@@ -89,6 +80,144 @@ export class AuthzService {
|
||||
return this.checkRole(pm.role, req.permission)
|
||||
}
|
||||
|
||||
private async resolveContext(
|
||||
type: ResourceType,
|
||||
id: string,
|
||||
): Promise<{ teamId: string; projectId?: string }> {
|
||||
switch (type) {
|
||||
case ResourceType.Team:
|
||||
return { teamId: id }
|
||||
|
||||
case ResourceType.Project: {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!proj) throw new Error('Project not found')
|
||||
return { teamId: proj.teamId, projectId: id }
|
||||
}
|
||||
|
||||
case ResourceType.Asset: {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
parentId: true,
|
||||
teamRootFolder: { select: { id: true } },
|
||||
project: { select: { id: true, teamId: true } },
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.project) {
|
||||
return { teamId: asset.project.teamId, projectId: asset.project.id }
|
||||
}
|
||||
if (asset.teamRootFolder) {
|
||||
return { teamId: asset.teamRootFolder.id }
|
||||
}
|
||||
if (asset.parentId) {
|
||||
// If it's a nested asset, we might need recursive lookup.
|
||||
// However, in this project, assets typically have projectId if they are in a project.
|
||||
// If parentId is set but no project, it might be in a team root folder.
|
||||
// For now, let's try to get context from parent.
|
||||
return this.resolveContext(ResourceType.Asset, asset.parentId)
|
||||
}
|
||||
throw new Error('Could not resolve context for asset')
|
||||
}
|
||||
|
||||
case ResourceType.Collection: {
|
||||
const coll = await prisma.collection.findUnique({
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!coll) throw new Error('Collection not found')
|
||||
return { teamId: coll.project.teamId, projectId: coll.projectId }
|
||||
}
|
||||
|
||||
case ResourceType.Agent: {
|
||||
const agent = await prisma.agent.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!agent) throw new Error('Agent not found')
|
||||
return { teamId: agent.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.AgentSession: {
|
||||
const session = await prisma.agentSession.findUnique({
|
||||
where: { id },
|
||||
include: { agent: true },
|
||||
})
|
||||
if (!session) throw new Error('Agent session not found')
|
||||
return { teamId: session.agent.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Share: {
|
||||
const share = await prisma.shareLink.findUnique({
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!share) throw new Error('Share not found')
|
||||
return { teamId: share.project.teamId, projectId: share.projectId }
|
||||
}
|
||||
|
||||
case ResourceType.MetadataField: {
|
||||
const field = await prisma.metadataField.findUnique({
|
||||
where: { key: id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!field) throw new Error('Metadata field not found')
|
||||
if (field.projectId) {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id: field.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
return { teamId: proj!.teamId, projectId: field.projectId }
|
||||
}
|
||||
if (!field.teamId) throw new Error('Metadata field has no context')
|
||||
return { teamId: field.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Skill: {
|
||||
const skill = await prisma.skill.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!skill) throw new Error('Skill not found')
|
||||
return { teamId: skill.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Provider: {
|
||||
const provider = await prisma.provider.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!provider) throw new Error('Provider not found')
|
||||
return { teamId: provider.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.Invite: {
|
||||
const invite = await prisma.invite.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!invite) throw new Error('Invite not found')
|
||||
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
|
||||
}
|
||||
|
||||
case ResourceType.Comment: {
|
||||
const comment = await prisma.assetComment.findUnique({
|
||||
where: { id },
|
||||
include: { asset: { include: { project: true } } },
|
||||
})
|
||||
if (!comment) throw new Error('Comment not found')
|
||||
if (!comment.asset.project) throw new Error('Comment asset has no project')
|
||||
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported resource type: ${type}`)
|
||||
}
|
||||
}
|
||||
|
||||
private checkRole(role: string, permission: Permission): void {
|
||||
switch (permission) {
|
||||
case Permission.Read:
|
||||
|
||||
@@ -67,6 +67,14 @@ export class MetadataService {
|
||||
return fields
|
||||
}
|
||||
|
||||
async getFieldByKey(
|
||||
key: string,
|
||||
): Promise<Prisma.MetadataFieldGetPayload<Record<string, never>> | null> {
|
||||
return this.client.metadataField.findUnique({
|
||||
where: { key },
|
||||
})
|
||||
}
|
||||
|
||||
async updateTeamField(
|
||||
teamId: string,
|
||||
fieldId: string,
|
||||
|
||||
@@ -65,6 +65,12 @@ export class ProviderService {
|
||||
}))
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
return this.prismaClient.provider.findUnique({
|
||||
where: { id },
|
||||
})
|
||||
}
|
||||
|
||||
async listModelsByProvider(teamId: string, providerId: string) {
|
||||
return this.prismaClient.model.findMany({
|
||||
where: {
|
||||
|
||||
@@ -55,15 +55,15 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
||||
initialMessage.message in AI_PLACEHOLDERS
|
||||
|
||||
const { data: polledMessage } = useQuery({
|
||||
queryKey: ['teams', teamId, 'comments', initialMessage.id],
|
||||
queryKey: ['comments', initialMessage.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].comments[':commentId'].$get({
|
||||
param: { teamId: teamId!, commentId: initialMessage.id! },
|
||||
const res = await client.api.comments[':commentId'].$get({
|
||||
param: { commentId: initialMessage.id! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comment')
|
||||
return (await res.json()) as CommentInfo
|
||||
},
|
||||
enabled: !!teamId && isRunning,
|
||||
enabled: isRunning,
|
||||
refetchInterval: (query) => {
|
||||
const data = query.state.data as CommentInfo
|
||||
if (data && (!data.message || !(data.message in AI_PLACEHOLDERS))) {
|
||||
@@ -97,15 +97,15 @@ export const MessageCard: React.FC<MessageCardProps> = ({
|
||||
const isAdmin = me?.role === 'owner'
|
||||
|
||||
const { data: logs, isLoading: isLogsLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'agent-sessions', message.sessionId, 'entries'],
|
||||
queryKey: ['agent-sessions', message.sessionId, 'entries'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId']['agent-sessions'][':sessionId'].entries.$get({
|
||||
param: { teamId: teamId!, sessionId: message.sessionId! },
|
||||
const res = await client.api['agent-sessions'][':sessionId'].entries.$get({
|
||||
param: { sessionId: message.sessionId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch session logs')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: isLogsOpen && !!message.sessionId && !!teamId,
|
||||
enabled: isLogsOpen && !!message.sessionId,
|
||||
})
|
||||
|
||||
const renderFormattedMessage = (text: string) => {
|
||||
|
||||
@@ -128,8 +128,8 @@ export function FileBrowser({
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
@@ -240,16 +240,16 @@ export function FileBrowser({
|
||||
day: 'numeric',
|
||||
})
|
||||
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].shares.$post({
|
||||
param: { projectId },
|
||||
json: { name },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create share link')
|
||||
const share = await res.json()
|
||||
|
||||
// Add assets to the new share link
|
||||
const assetsRes = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({
|
||||
param: { teamId, shareId: share.id },
|
||||
const assetsRes = await client.api.shares[':shareId'].assets.$post({
|
||||
param: { shareId: share.id },
|
||||
json: { assetIds: items.map((i) => i.id!) },
|
||||
})
|
||||
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
|
||||
@@ -273,8 +273,8 @@ export function FileBrowser({
|
||||
|
||||
const { mutate: addToShareLink } = useMutation({
|
||||
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
|
||||
const res = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({
|
||||
param: { teamId, shareId },
|
||||
const res = await client.api.shares[':shareId'].assets.$post({
|
||||
param: { shareId },
|
||||
json: { assetIds: items.map((i) => i.id!) },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to add assets')
|
||||
|
||||
@@ -87,8 +87,8 @@ export function FileCard({
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId || '', fileId: item.id || '' },
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: item.id || '' },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
|
||||
@@ -66,8 +66,8 @@ export function FileListItem({
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId || '', fileId: item.id || '' },
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: item.id || '' },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
|
||||
@@ -58,15 +58,15 @@ export function FileBrowserToolbar({
|
||||
const isCollection = !!collection
|
||||
|
||||
const { data: folderInfo } = useQuery({
|
||||
queryKey: ['folders', teamId, assetId],
|
||||
queryKey: ['folders', assetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: isCollection && !!teamId && !!assetId,
|
||||
enabled: isCollection && !!assetId,
|
||||
})
|
||||
|
||||
const { data: members } = useQuery({
|
||||
|
||||
@@ -28,7 +28,7 @@ export function useFileActions({
|
||||
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const $createFolder = client.api.teams[':teamId'].folders.$post
|
||||
const $createFolder = client.api.folders.$post
|
||||
const { mutate: createFolder } = useMutation<
|
||||
InferResponseType<typeof $createFolder, 200>,
|
||||
Error,
|
||||
@@ -41,7 +41,7 @@ export function useFileActions({
|
||||
},
|
||||
})
|
||||
|
||||
const $renameFolder = client.api.teams[':teamId'].folders[':folderId'].$put
|
||||
const $renameFolder = client.api.folders[':folderId'].$put
|
||||
const { mutate: renameFolder } = useMutation<
|
||||
InferResponseType<typeof $renameFolder, 200>,
|
||||
Error,
|
||||
@@ -54,7 +54,7 @@ export function useFileActions({
|
||||
},
|
||||
})
|
||||
|
||||
const $renameFile = client.api.teams[':teamId'].files[':fileId'].$put
|
||||
const $renameFile = client.api.files[':fileId'].$put
|
||||
const { mutate: renameFile } = useMutation<
|
||||
InferResponseType<typeof $renameFile, 200>,
|
||||
Error,
|
||||
@@ -67,7 +67,7 @@ export function useFileActions({
|
||||
},
|
||||
})
|
||||
|
||||
const $deleteFiles = client.api.teams[':teamId'].files.$delete
|
||||
const $deleteFiles = client.api.files.$delete
|
||||
const { mutate: deleteFiles } = useMutation<void, Error, InferRequestType<typeof $deleteFiles>>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $deleteFiles(request)
|
||||
@@ -75,7 +75,7 @@ export function useFileActions({
|
||||
},
|
||||
})
|
||||
|
||||
const $deleteFolders = client.api.teams[':teamId'].folders.$delete
|
||||
const $deleteFolders = client.api.folders.$delete
|
||||
const { mutate: deleteFolders } = useMutation<
|
||||
InferResponseType<typeof $deleteFolders>,
|
||||
Error,
|
||||
@@ -88,7 +88,7 @@ export function useFileActions({
|
||||
},
|
||||
})
|
||||
|
||||
const $restoreFiles = client.api.teams[':teamId'].files.restore.$post
|
||||
const $restoreFiles = client.api.files.restore.$post
|
||||
const { mutate: restoreFiles } = useMutation<void, Error, InferRequestType<typeof $restoreFiles>>(
|
||||
{
|
||||
mutationFn: async (request) => {
|
||||
@@ -98,7 +98,7 @@ export function useFileActions({
|
||||
},
|
||||
)
|
||||
|
||||
const $restoreFolders = client.api.teams[':teamId'].folders.restore.$post
|
||||
const $restoreFolders = client.api.folders.restore.$post
|
||||
const { mutate: restoreFolders } = useMutation<
|
||||
InferResponseType<typeof $restoreFolders>,
|
||||
Error,
|
||||
@@ -121,7 +121,7 @@ export function useFileActions({
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
deleteFiles(
|
||||
{ param: { teamId: teamId }, json: { ids: fileIds } },
|
||||
{ json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -134,7 +134,7 @@ export function useFileActions({
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
deleteFolders(
|
||||
{ param: { teamId: teamId }, json: { ids: folderIds } },
|
||||
{ json: { ids: folderIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -160,7 +160,7 @@ export function useFileActions({
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
restoreFiles(
|
||||
{ param: { teamId: teamId }, json: { ids: fileIds } },
|
||||
{ json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -173,7 +173,7 @@ export function useFileActions({
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
restoreFolders(
|
||||
{ param: { teamId: teamId }, json: { ids: folderIds } },
|
||||
{ json: { ids: folderIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -195,7 +195,7 @@ export function useFileActions({
|
||||
|
||||
const handleNewFolder = (name: string) => {
|
||||
createFolder(
|
||||
{ param: { teamId: teamId }, json: { name, parentId: assetId } },
|
||||
{ json: { name, parentId: assetId } },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -215,7 +215,7 @@ export function useFileActions({
|
||||
const onRenameSubmit = (item: AssetInfo, newName: string) => {
|
||||
if (item.type === 'folder') {
|
||||
renameFolder(
|
||||
{ param: { teamId: teamId, folderId: item.id! }, json: { name: newName } },
|
||||
{ param: { folderId: item.id! }, json: { name: newName } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
@@ -230,7 +230,7 @@ export function useFileActions({
|
||||
} else {
|
||||
renameFile(
|
||||
{
|
||||
param: { teamId: teamId, fileId: item.id! },
|
||||
param: { fileId: item.id! },
|
||||
json: { name: newName },
|
||||
},
|
||||
{
|
||||
|
||||
@@ -47,7 +47,7 @@ export default function FileSystemManager({
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { loadedProjectId, setFields } = useFieldStore()
|
||||
const $patchMetadata = client.api.teams[':teamId'].files[':fileId'].metadata.$patch
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
Error,
|
||||
@@ -132,10 +132,10 @@ export default function FileSystemManager({
|
||||
const { data: folderInfo } = isRecentlyDeleted
|
||||
? { data: undefined }
|
||||
: useQuery({
|
||||
queryKey: ['folders', teamId, assetId],
|
||||
queryKey: ['folders', assetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
@@ -206,8 +206,8 @@ export default function FileSystemManager({
|
||||
return { data: [], pageInfo: { total: 0 } }
|
||||
}
|
||||
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
json: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
@@ -248,8 +248,8 @@ export default function FileSystemManager({
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
}
|
||||
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({
|
||||
param: { teamId: teamId, folderId: assetId },
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
json: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
@@ -370,7 +370,7 @@ export default function FileSystemManager({
|
||||
const handleSaveField = (fileId: string, fieldId: string, value: unknown) => {
|
||||
patchMetadata(
|
||||
{
|
||||
param: { teamId: teamId, fileId: fileId },
|
||||
param: { fileId: fileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
@@ -378,7 +378,6 @@ export default function FileSystemManager({
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [
|
||||
'folders',
|
||||
teamId,
|
||||
assetId,
|
||||
'children',
|
||||
{
|
||||
|
||||
@@ -10,7 +10,6 @@ import { Button } from './ui/button'
|
||||
import { ScrollArea } from './ui/scroll-area'
|
||||
|
||||
interface FileViewerLeftSidebarProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
currentAssetId: string
|
||||
parentFolderId: string
|
||||
@@ -18,7 +17,6 @@ interface FileViewerLeftSidebarProps {
|
||||
}
|
||||
|
||||
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
teamId,
|
||||
projectId,
|
||||
currentAssetId,
|
||||
parentFolderId,
|
||||
@@ -34,7 +32,6 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({
|
||||
queryKey: [
|
||||
'folders',
|
||||
teamId,
|
||||
parentFolderId,
|
||||
'children',
|
||||
{
|
||||
@@ -42,8 +39,8 @@ export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId: teamId, folderId: parentFolderId },
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: parentFolderId },
|
||||
query: {
|
||||
assetType: 'file',
|
||||
after: pageParam,
|
||||
|
||||
@@ -99,7 +99,7 @@ export function FileViewerRightSidebar({
|
||||
} = useInfiniteQuery({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['teams', teamId, 'files', file?.id, 'comments'],
|
||||
: ['files', file?.id, 'comments'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
@@ -117,8 +117,8 @@ export function FileViewerRightSidebar({
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].comments.$get({
|
||||
param: { teamId: teamId, fileId: file!.id! },
|
||||
const res = await client.api.files[':fileId'].comments.$get({
|
||||
param: { fileId: file!.id! },
|
||||
query: { after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
@@ -168,8 +168,8 @@ export function FileViewerRightSidebar({
|
||||
if (!res.ok) throw new Error('Failed to create comment')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].comments.$post({
|
||||
param: { teamId: teamId, fileId: file!.id! },
|
||||
const res = await client.api.files[':fileId'].comments.$post({
|
||||
param: { fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
@@ -185,7 +185,7 @@ export function FileViewerRightSidebar({
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['teams', teamId, 'files', file?.id, 'comments'],
|
||||
: ['files', file?.id, 'comments'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
@@ -54,35 +54,35 @@ export function FolderTree({
|
||||
})
|
||||
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
queryKey: ['shares', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
|
||||
},
|
||||
enabled: !!teamId && !!projectId,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { data: collectionsData } = useQuery({
|
||||
queryKey: ['collections', teamId, projectId],
|
||||
queryKey: ['collections', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$get({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].collections.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch collections')
|
||||
return (await res.json()) as unknown as { data: CollectionInfo[] }
|
||||
},
|
||||
enabled: !!teamId && !!projectId,
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { mutate: createCollection } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].collections.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
name: 'Untitled Collection',
|
||||
filter: {
|
||||
@@ -98,7 +98,7 @@ export function FolderTree({
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
|
||||
toast.success('Collection created')
|
||||
navigate({
|
||||
to: '/projects/$projectId/collections/$collectionId',
|
||||
@@ -112,8 +112,8 @@ export function FolderTree({
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].shares.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
name: new Date().toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
@@ -126,7 +126,7 @@ export function FolderTree({
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', teamId, projectId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
||||
toast.success('Share link created')
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
@@ -362,7 +362,6 @@ function FolderTreeItem({
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: [
|
||||
'folders',
|
||||
teamId,
|
||||
folder.id,
|
||||
'children',
|
||||
{
|
||||
@@ -370,8 +369,8 @@ function FolderTreeItem({
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId: teamId, folderId: folder.id },
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: folder.id },
|
||||
query: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
|
||||
@@ -161,7 +161,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
|
||||
resetEditor(data)
|
||||
},
|
||||
})
|
||||
const $put = client.api.projects[':projectId'].fields[':fieldId'].$put
|
||||
const $put = client.api.fields[':fieldId'].$put
|
||||
const { mutate: updateField } = useMutation<
|
||||
InferResponseType<typeof $put>,
|
||||
Error,
|
||||
@@ -179,7 +179,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
|
||||
updateFields(newFields)
|
||||
},
|
||||
})
|
||||
const $delete = client.api.projects[':projectId'].fields[':fieldId'].$delete
|
||||
const $delete = client.api.fields[':fieldId'].$delete
|
||||
const { mutate: deleteField } = useMutation<
|
||||
InferResponseType<typeof $delete>,
|
||||
Error,
|
||||
@@ -287,7 +287,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
|
||||
const handleSaveEdit = () => {
|
||||
if (!selectedField) return
|
||||
updateField({
|
||||
param: { projectId: projectId, fieldId: selectedField.id! },
|
||||
param: { fieldId: selectedField.id! },
|
||||
json: {
|
||||
config: {
|
||||
...selectedField.config,
|
||||
@@ -303,7 +303,7 @@ export function ManageFieldsDialog({ projectId, open, onOpenChange }: ManageFiel
|
||||
const handleDelete = () => {
|
||||
if (!selectedField) return
|
||||
if (confirm('Are you sure you want to delete this field?')) {
|
||||
deleteField({ param: { projectId: projectId, fieldId: selectedField.id! } })
|
||||
deleteField({ param: { fieldId: selectedField.id! } })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ export function ProjectDialog({ open, onOpenChange, mode, teamId, project }: Pro
|
||||
},
|
||||
})
|
||||
|
||||
const $put = client.api.teams[':teamId'].projects[':projectId'].$put
|
||||
const $put = client.api.projects[':projectId'].$put
|
||||
const { mutate: updateProject } = useMutation<
|
||||
InferResponseType<typeof $put>,
|
||||
Error,
|
||||
@@ -81,7 +81,7 @@ export function ProjectDialog({ open, onOpenChange, mode, teamId, project }: Pro
|
||||
>({
|
||||
mutationFn: async (payload) => {
|
||||
const res = await $put({
|
||||
param: { teamId: teamId, projectId: project!.id! },
|
||||
param: { projectId: project!.id! },
|
||||
json: payload,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update project')
|
||||
|
||||
@@ -108,8 +108,8 @@ export function SearchFilterDialog({
|
||||
}
|
||||
if (!name) name = 'Untitled Collection'
|
||||
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({
|
||||
param: { teamId, projectId },
|
||||
const res = await client.api.projects[':projectId'].collections.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
name,
|
||||
filter: {
|
||||
@@ -125,7 +125,7 @@ export function SearchFilterDialog({
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
|
||||
toast.success('Collection saved')
|
||||
onOpenChange(false)
|
||||
navigate({
|
||||
@@ -141,8 +141,8 @@ export function SearchFilterDialog({
|
||||
const { data: searchResults, isLoading } = useQuery({
|
||||
queryKey: ['search-preview', teamId, assetId, combinedConditions],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].search.$post({
|
||||
param: { teamId, folderId: assetId },
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
json: {
|
||||
assetType: undefined,
|
||||
conditions: combinedConditions,
|
||||
|
||||
@@ -144,8 +144,8 @@ export function AgentFormDialog({
|
||||
const { data: models, isLoading: isModelsLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'providers', selectedProviderId, 'models'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, id: selectedProviderId! },
|
||||
const res = await client.api.providers[':id'].models.$get({
|
||||
param: { id: selectedProviderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch models')
|
||||
return await res.json()
|
||||
@@ -174,8 +174,8 @@ export function AgentFormDialog({
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: async ({ id, values }: { id: string; values: AgentFormValues }) => {
|
||||
const res = await client.api.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId, agentId: id },
|
||||
const res = await client.api.agents[':agentId'].$put({
|
||||
param: { agentId: id },
|
||||
json: values,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update agent')
|
||||
|
||||
@@ -82,8 +82,8 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
|
||||
const deleteAgentMutation = useMutation({
|
||||
mutationFn: async (agentId: string) => {
|
||||
const res = await client.api.teams[':teamId'].agents[':agentId'].$delete({
|
||||
param: { teamId, agentId },
|
||||
const res = await client.api.agents[':agentId'].$delete({
|
||||
param: { agentId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to delete agent')
|
||||
},
|
||||
@@ -112,8 +112,8 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
soul?: string
|
||||
skills?: string[]
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].agents[':agentId'].$put({
|
||||
param: { teamId: params.teamId, agentId: params.agentId },
|
||||
const res = await client.api.agents[':agentId'].$put({
|
||||
param: { agentId: params.agentId },
|
||||
json: {
|
||||
name: params.name,
|
||||
type: params.type,
|
||||
|
||||
@@ -105,8 +105,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
const { data: editingModels, isLoading: isModelsLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'providers', editingProviderId, 'models'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].models.$get({
|
||||
param: { teamId, id: editingProviderId! },
|
||||
const res = await client.api.providers[':id'].models.$get({
|
||||
param: { id: editingProviderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch models')
|
||||
return await res.json()
|
||||
@@ -150,8 +150,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
// Update Mutation
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: async ({ id, values }: { id: string; values: ProviderFormValues }) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].$put({
|
||||
param: { teamId, id },
|
||||
const res = await client.api.providers[':id'].$put({
|
||||
param: { id },
|
||||
json: {
|
||||
config: values.config,
|
||||
models: values.models,
|
||||
@@ -173,8 +173,8 @@ export function ProvidersSettings({ teamId }: ProvidersSettingsProps) {
|
||||
// Delete Mutation
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.teams[':teamId'].providers[':id'].$delete({
|
||||
param: { teamId, id },
|
||||
const res = await client.api.providers[':id'].$delete({
|
||||
param: { id },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete provider')
|
||||
return await res.json()
|
||||
|
||||
@@ -57,8 +57,8 @@ export const SkillsConfigCard: React.FC<SkillsConfigCardProps> = ({ teamId }) =>
|
||||
// Delete Skill
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const res = await client.api.teams[':teamId'].skills[':id'].$delete({
|
||||
param: { teamId, id },
|
||||
const res = await client.api.skills[':id'].$delete({
|
||||
param: { id },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to delete skill')
|
||||
},
|
||||
@@ -499,8 +499,8 @@ const ConfigSkillDialog = ({
|
||||
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const res = await client.api.teams[':teamId'].skills[':id'].config.$patch({
|
||||
param: { teamId, id: skill.id },
|
||||
const res = await client.api.skills[':id'].config.$patch({
|
||||
param: { id: skill.id },
|
||||
json: { config: finalConfig },
|
||||
})
|
||||
if (!res.ok) {
|
||||
|
||||
@@ -43,8 +43,8 @@ export default function ShareManager({
|
||||
const { data: shareLink } = useQuery({
|
||||
queryKey: ['share', shareId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].shares[':shareId'].$get({
|
||||
param: { teamId, shareId },
|
||||
const res = await client.api.shares[':shareId'].$get({
|
||||
param: { shareId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share link')
|
||||
return (await res.json()) as unknown as ShareLinkInfo
|
||||
@@ -101,8 +101,8 @@ export default function ShareManager({
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'folder'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId, folderId: currentFolderId! },
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: currentFolderId! },
|
||||
query: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
@@ -124,8 +124,8 @@ export default function ShareManager({
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: ['folder-children', teamId, currentFolderId, 'file'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].children.$get({
|
||||
param: { teamId, folderId: currentFolderId! },
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: currentFolderId! },
|
||||
query: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
@@ -198,11 +198,11 @@ export default function ShareManager({
|
||||
onClearSelection: handleClearSelection,
|
||||
})
|
||||
|
||||
const $removeFromShare = client.api.teams[':teamId'].shares[':shareId'].assets[':assetId'].$delete
|
||||
const $removeFromShare = client.api.shares[':shareId'].assets[':assetId'].$delete
|
||||
const { mutate: removeFromShare } = useMutation({
|
||||
mutationFn: async (assetId: string) => {
|
||||
const res = await $removeFromShare({
|
||||
param: { teamId, shareId, assetId },
|
||||
param: { shareId, assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to remove')
|
||||
},
|
||||
@@ -306,7 +306,7 @@ export default function ShareManager({
|
||||
}
|
||||
/>
|
||||
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0">
|
||||
<ShareSettingsSidebar teamId={teamId} shareLink={shareLink} />
|
||||
<ShareSettingsSidebar shareLink={shareLink} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -20,11 +20,10 @@ import React, { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { DateTimePicker } from '@/ui/components/datetime-picker'
|
||||
interface ShareSettingsSidebarProps {
|
||||
teamId: string
|
||||
shareLink: ShareLinkInfo
|
||||
}
|
||||
|
||||
export function ShareSettingsSidebar({ teamId, shareLink }: ShareSettingsSidebarProps) {
|
||||
export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [password, setPassword] = useState('')
|
||||
const [expireAt, setExpireAt] = useState<Date | undefined>(
|
||||
@@ -45,18 +44,18 @@ export function ShareSettingsSidebar({ teamId, shareLink }: ShareSettingsSidebar
|
||||
enabled: !!shareLink.projectId,
|
||||
})
|
||||
|
||||
const $updateShare = client.api.teams[':teamId'].shares[':shareId'].$put
|
||||
const $updateShare = client.api.shares[':shareId'].$put
|
||||
const { mutate: updateShare } = useMutation({
|
||||
mutationFn: async (json: UpdateShareLinkRequest) => {
|
||||
const res = await $updateShare({
|
||||
param: { teamId, shareId: shareLink.id },
|
||||
param: { shareId: shareLink.id },
|
||||
json,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', teamId, shareLink.projectId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
|
||||
toast.success('Settings updated')
|
||||
},
|
||||
|
||||
@@ -44,7 +44,7 @@ export function useFileSystemDnd({
|
||||
},
|
||||
})
|
||||
|
||||
const $reorderFolder = client.api.teams[':teamId'].folders[':folderId'].order.$patch
|
||||
const $reorderFolder = client.api.folders[':folderId'].order.$patch
|
||||
const { mutate: reorderFolder } = useMutation<
|
||||
InferResponseType<typeof $reorderFolder, 200>,
|
||||
Error,
|
||||
@@ -57,7 +57,7 @@ export function useFileSystemDnd({
|
||||
},
|
||||
})
|
||||
|
||||
const $reorderFile = client.api.teams[':teamId'].files[':fileId'].order.$patch
|
||||
const $reorderFile = client.api.files[':fileId'].order.$patch
|
||||
const { mutate: reorderFile } = useMutation<
|
||||
InferResponseType<typeof $reorderFile, 200>,
|
||||
Error,
|
||||
@@ -70,7 +70,7 @@ export function useFileSystemDnd({
|
||||
},
|
||||
})
|
||||
|
||||
const $addAssetToShare = client.api.teams[':teamId'].shares[':shareId'].assets.$post
|
||||
const $addAssetToShare = client.api.shares[':shareId'].assets.$post
|
||||
const { mutate: addAssetToShare } = useMutation<
|
||||
{ addedCount: number },
|
||||
Error,
|
||||
@@ -128,7 +128,7 @@ export function useFileSystemDnd({
|
||||
|
||||
addAssetToShare(
|
||||
{
|
||||
param: { teamId, shareId },
|
||||
param: { shareId },
|
||||
json: { assetIds },
|
||||
},
|
||||
{
|
||||
@@ -139,7 +139,7 @@ export function useFileSystemDnd({
|
||||
toast.success(`Added ${data.addedCount} item(s) to share link`)
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
queryKey: ['shares', projectId],
|
||||
})
|
||||
onClearSelection()
|
||||
},
|
||||
@@ -178,8 +178,7 @@ export function useFileSystemDnd({
|
||||
if (isFolder) {
|
||||
reorderFolder(
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
param: { teamId: teamId, folderId: draggedId } as any,
|
||||
param: { folderId: draggedId },
|
||||
json:
|
||||
position === 'before'
|
||||
? { beforeIndex: targetItem.sortIndex ?? undefined }
|
||||
@@ -201,8 +200,7 @@ export function useFileSystemDnd({
|
||||
} else {
|
||||
reorderFile(
|
||||
{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
param: { teamId: teamId, fileId: draggedId } as any,
|
||||
param: { fileId: draggedId },
|
||||
json:
|
||||
position === 'before'
|
||||
? { beforeIndex: targetItem.sortIndex ?? undefined }
|
||||
|
||||
@@ -16,13 +16,11 @@ const projectInfoQueryOptions = (projectId: string) => ({
|
||||
},
|
||||
})
|
||||
|
||||
const collectionInfoQueryOptions = (teamId: string, projectId: string, collectionId: string) => ({
|
||||
queryKey: ['collections', teamId, projectId, collectionId],
|
||||
const collectionInfoQueryOptions = (collectionId: string) => ({
|
||||
queryKey: ['collections', collectionId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[
|
||||
':collectionId'
|
||||
].$get({
|
||||
param: { teamId, projectId, collectionId },
|
||||
const res = await client.api.collections[':collectionId'].$get({
|
||||
param: { collectionId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch collection')
|
||||
return await res.json()
|
||||
@@ -40,17 +38,14 @@ function CollectionPage() {
|
||||
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
|
||||
|
||||
const { data: collection, refetch: refetchCollection } = useQuery({
|
||||
...collectionInfoQueryOptions(teamId || '', projectId, collectionId),
|
||||
enabled: !!teamId,
|
||||
...collectionInfoQueryOptions(collectionId),
|
||||
})
|
||||
|
||||
const { mutate: updateCollection } = useMutation({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mutationFn: async (updates: { name?: string; filter?: any }) => {
|
||||
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[
|
||||
':collectionId'
|
||||
].$patch({
|
||||
param: { teamId: teamId!, projectId, collectionId },
|
||||
const res = await client.api.collections[':collectionId'].$patch({
|
||||
param: { collectionId },
|
||||
json: updates,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update collection')
|
||||
@@ -64,15 +59,15 @@ function CollectionPage() {
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', teamId!, rootFolderId!],
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId!, folderId: rootFolderId! },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId && !!rootFolderId,
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder || !collection) {
|
||||
|
||||
@@ -34,7 +34,7 @@ function FileViewPage() {
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(280)
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
const $patchMetadata = client.api.teams[':teamId'].files[':fileId'].metadata.$patch
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
Error,
|
||||
@@ -65,10 +65,10 @@ function FileViewPage() {
|
||||
isError: isStackError,
|
||||
isFetching: isStackFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['teams', teamId, 'files', fileId],
|
||||
queryKey: ['files', fileId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId!, fileId: fileId },
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch stack')
|
||||
return await res.json()
|
||||
@@ -83,10 +83,10 @@ function FileViewPage() {
|
||||
isError: isVersionError,
|
||||
isFetching: isVersionFetching,
|
||||
} = useQuery({
|
||||
queryKey: ['teams', teamId, 'files', versionAssetId],
|
||||
queryKey: ['files', versionAssetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].files[':fileId'].$get({
|
||||
param: { teamId: teamId!, fileId: versionAssetId! },
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: versionAssetId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch version')
|
||||
return await res.json()
|
||||
@@ -96,10 +96,10 @@ function FileViewPage() {
|
||||
})
|
||||
|
||||
const { data: versionsList } = useQuery({
|
||||
queryKey: ['projects', projectId, 'version_stacks', fileId, 'versions'],
|
||||
queryKey: ['version_stacks', fileId, 'versions'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].version_stacks[':stackId'].versions.$get({
|
||||
param: { projectId: projectId, stackId: fileId },
|
||||
const res = await client.api.version_stacks[':stackId'].versions.$get({
|
||||
param: { stackId: fileId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch versions')
|
||||
return await res.json()
|
||||
@@ -180,13 +180,13 @@ function FileViewPage() {
|
||||
if (!teamId) return
|
||||
patchMetadata(
|
||||
{
|
||||
param: { teamId: teamId, fileId: activeFileId },
|
||||
param: { fileId: activeFileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'files', activeFileId],
|
||||
queryKey: ['files', activeFileId],
|
||||
})
|
||||
},
|
||||
},
|
||||
@@ -216,7 +216,6 @@ function FileViewPage() {
|
||||
<>
|
||||
<div style={{ width: leftSidebarWidth }} className="flex-shrink-0">
|
||||
<FileViewerLeftSidebar
|
||||
teamId={teamId!}
|
||||
projectId={projectId}
|
||||
currentAssetId={activeFileId}
|
||||
parentFolderId={
|
||||
|
||||
@@ -29,15 +29,15 @@ function FolderPage() {
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', teamId!, rootFolderId!],
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId!, folderId: rootFolderId! },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!teamId && !!rootFolderId,
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
|
||||
@@ -29,15 +29,15 @@ function ProjectPage() {
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', teamId!, rootFolderId!],
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId!, folderId: rootFolderId! },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId && !!rootFolderId,
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
|
||||
@@ -29,15 +29,15 @@ function RecentlyDeletedPage() {
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', teamId!, rootFolderId!],
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: () =>
|
||||
(async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId!, folderId: rootFolderId! },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
return await res.json()
|
||||
})(),
|
||||
enabled: !!teamId && !!rootFolderId,
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
|
||||
@@ -29,15 +29,15 @@ function SharePage() {
|
||||
const rootFolderId = projectInfo?.rootFolder
|
||||
|
||||
const { data: rootFolder } = useQuery({
|
||||
queryKey: ['folders', teamId!, rootFolderId!],
|
||||
queryKey: ['folders', rootFolderId!],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
|
||||
param: { teamId: teamId!, folderId: rootFolderId! },
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: rootFolderId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch folder')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId && !!rootFolderId,
|
||||
enabled: !!rootFolderId,
|
||||
})
|
||||
|
||||
if (!teamId || !rootFolderId || !rootFolder) {
|
||||
|
||||
Reference in New Issue
Block a user