mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 19:39:27 +00:00
fix(api): enforce SHUMAI_DEMO_MODE for API token and CLI requests (#413)
This commit is contained in:
@@ -11,44 +11,44 @@ export const authMiddleware = createMiddleware<{
|
||||
user: User
|
||||
}
|
||||
}>(async (c, next) => {
|
||||
if (c.get('user')) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
let user = c.get('user')
|
||||
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
if (!user) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await userService.getUserById(session.user.id)
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
try {
|
||||
const fetchedUser = await userService.getUserById(session.user.id)
|
||||
|
||||
if (process.env.SHUMAI_DEMO_MODE === '1') {
|
||||
const method = c.req.method.toUpperCase()
|
||||
const path = c.req.path
|
||||
const isAllowedDemoWrite =
|
||||
method === 'POST' && (path.endsWith('/search') || path.endsWith('/recents/view'))
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !isAllowedDemoWrite) {
|
||||
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
|
||||
if (!fetchedUser) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
}
|
||||
|
||||
if (!hasWritable) {
|
||||
return c.json({ error: 'System is in read-only mode' }, 403)
|
||||
}
|
||||
user = fetchedUser
|
||||
c.set('user', user)
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.SHUMAI_DEMO_MODE === '1') {
|
||||
const method = c.req.method.toUpperCase()
|
||||
const path = c.req.path
|
||||
const isAllowedDemoWrite =
|
||||
method === 'POST' && (path.endsWith('/search') || path.endsWith('/recents/view'))
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !isAllowedDemoWrite) {
|
||||
const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
|
||||
|
||||
if (!hasWritable) {
|
||||
return c.json({ error: 'System is in read-only mode' }, 403)
|
||||
}
|
||||
}
|
||||
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
|
||||
await next()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user