mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 04:09:29 +00:00
refactor(api): enforce layered architecture by moving db queries to core services
This commit is contained in:
@@ -2,7 +2,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { authMiddleware } from './auth'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
vi.mock('@shumai/core/src/auth/auth', () => ({
|
||||
auth: {
|
||||
@@ -12,14 +13,15 @@ vi.mock('@shumai/core/src/auth/auth', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/db', () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
teamMember: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
vi.mock('@shumai/core/src/user/user', () => ({
|
||||
userService: {
|
||||
getUserById: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/team/team', () => ({
|
||||
teamService: {
|
||||
hasWritableRoleInAnyTeam: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -39,7 +41,7 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test')
|
||||
expect(res.status).toBe(200)
|
||||
@@ -61,7 +63,7 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test')
|
||||
expect(res.status).toBe(200)
|
||||
@@ -71,8 +73,8 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue(null) // No owner/editor role
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false) // No owner/editor role
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(403)
|
||||
@@ -83,7 +85,7 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
|
||||
const res = await app.request('/test/search', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
@@ -93,12 +95,8 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
|
||||
id: 'member1',
|
||||
role: 'owner',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true)
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
@@ -108,12 +106,8 @@ describe('authMiddleware', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
|
||||
id: 'member1',
|
||||
role: 'editor',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
|
||||
vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true)
|
||||
|
||||
const res = await app.request('/test', { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { userService } from '@shumai/core/src/user/user'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
@@ -24,9 +25,7 @@ export const authMiddleware = createMiddleware<{
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
})
|
||||
const user = await userService.getUserById(session.user.id)
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
@@ -38,14 +37,9 @@ export const authMiddleware = createMiddleware<{
|
||||
const method = c.req.method.toUpperCase()
|
||||
const path = c.req.path
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) {
|
||||
const member = await prisma.teamMember.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
role: { in: ['owner', 'editor'] },
|
||||
},
|
||||
})
|
||||
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
|
||||
|
||||
if (!member) {
|
||||
if (!hasWritable) {
|
||||
return c.json({ error: 'System is in read-only mode' }, 403)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { tokenAuthMiddleware } from './tokenAuth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
vi.mock('@shumai/db', () => ({
|
||||
prisma: {
|
||||
apiToken: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
vi.mock('@shumai/core/src/user/api-token', () => ({
|
||||
apiTokenService: {
|
||||
validateToken: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -31,21 +30,11 @@ describe('tokenAuthMiddleware', () => {
|
||||
})
|
||||
|
||||
it('sets user when valid Authorization Bearer token is provided', async () => {
|
||||
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
|
||||
id: 'token1',
|
||||
token: 'ulid_token_123',
|
||||
name: 'cli-key',
|
||||
userId: 'user123',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
user: {
|
||||
id: 'user123',
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
},
|
||||
// Mocking the complex PrismaPromise return type of findUnique is not feasible without any here.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.mocked(apiTokenService.validateToken).mockResolvedValue({
|
||||
id: 'user123',
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
} as unknown as Prisma.UserGetPayload<Record<string, never>>)
|
||||
|
||||
const res = await app.request('/test', {
|
||||
headers: {
|
||||
@@ -54,28 +43,15 @@ describe('tokenAuthMiddleware', () => {
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('user:user123')
|
||||
expect(prisma.apiToken.findUnique).toHaveBeenCalledWith({
|
||||
where: { token: 'ulid_token_123' },
|
||||
include: { user: true },
|
||||
})
|
||||
expect(apiTokenService.validateToken).toHaveBeenCalledWith('ulid_token_123')
|
||||
})
|
||||
|
||||
it('sets user when valid x-api-key header is provided', async () => {
|
||||
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
|
||||
id: 'token1',
|
||||
token: 'ulid_token_123',
|
||||
name: 'cli-key',
|
||||
userId: 'user123',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
user: {
|
||||
id: 'user123',
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
},
|
||||
// Mocking the complex PrismaPromise return type of findUnique is not feasible without any here.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.mocked(apiTokenService.validateToken).mockResolvedValue({
|
||||
id: 'user123',
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
} as unknown as Prisma.UserGetPayload<Record<string, never>>)
|
||||
|
||||
const res = await app.request('/test', {
|
||||
headers: {
|
||||
@@ -87,7 +63,7 @@ describe('tokenAuthMiddleware', () => {
|
||||
})
|
||||
|
||||
it('returns 401 when invalid token is provided', async () => {
|
||||
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue(null)
|
||||
vi.mocked(apiTokenService.validateToken).mockResolvedValue(null)
|
||||
|
||||
const res = await app.request('/test', {
|
||||
headers: {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
@@ -16,16 +16,13 @@ export const tokenAuthMiddleware = createMiddleware<{
|
||||
: c.req.header('x-api-key') || null
|
||||
|
||||
if (token) {
|
||||
const apiToken = await prisma.apiToken.findUnique({
|
||||
where: { token },
|
||||
include: { user: true },
|
||||
})
|
||||
const user = await apiTokenService.validateToken(token)
|
||||
|
||||
if (!apiToken) {
|
||||
if (!user) {
|
||||
return c.json({ error: 'Unauthorized: Invalid API Key' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', apiToken.user)
|
||||
c.set('user', user)
|
||||
}
|
||||
|
||||
await next()
|
||||
|
||||
Reference in New Issue
Block a user