initial platform gateway service
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
import { config } from '../config'
|
||||
import type { AuthUser } from '../types'
|
||||
|
||||
export type AuthVariables = {
|
||||
user: AuthUser
|
||||
accessToken: string
|
||||
}
|
||||
|
||||
export const authRequired: MiddlewareHandler<{ Variables: AuthVariables }> = async (c, next) => {
|
||||
const header = c.req.header('authorization')
|
||||
const token = header?.match(/^Bearer\s+(.+)$/i)?.[1]
|
||||
if (!token) return c.json({ error: 'missing_authorization' }, 401)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${config.authServerUrl}/auth/me`, {
|
||||
headers: { authorization: `Bearer ${token}` }
|
||||
})
|
||||
if (!response.ok) return c.json({ error: 'invalid_authorization' }, 401)
|
||||
|
||||
const payload = await response.json() as { user?: AuthUser }
|
||||
if (!payload.user?.id) return c.json({ error: 'invalid_authorization' }, 401)
|
||||
|
||||
c.set('user', payload.user)
|
||||
c.set('accessToken', token)
|
||||
return next()
|
||||
} catch {
|
||||
return c.json({ error: 'auth_server_unavailable' }, 503)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user