mirror of
https://github.com/hellodigua/ChatLab.git
synced 2026-05-23 15:00:41 +08:00
26 lines
741 B
TypeScript
26 lines
741 B
TypeScript
/**
|
|
* ChatLab API — Bearer Token authentication hook
|
|
*/
|
|
|
|
import type { FastifyRequest, FastifyReply } from 'fastify'
|
|
import { loadConfig } from './config'
|
|
import { unauthorized, errorResponse } from './errors'
|
|
|
|
export async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
|
const authHeader = request.headers.authorization
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
const err = unauthorized()
|
|
reply.code(err.statusCode).send(errorResponse(err))
|
|
return
|
|
}
|
|
|
|
const token = authHeader.slice(7)
|
|
const config = loadConfig()
|
|
|
|
if (!config.token || token !== config.token) {
|
|
const err = unauthorized()
|
|
reply.code(err.statusCode).send(errorResponse(err))
|
|
return
|
|
}
|
|
}
|