Init
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { operators } from '@telemt/db'
|
||||
|
||||
export interface AuthOperator {
|
||||
id: string
|
||||
username: string
|
||||
role: string
|
||||
}
|
||||
|
||||
declare module '@fastify/jwt' {
|
||||
interface FastifyJWT {
|
||||
payload: { sub: string; username: string; role: string }
|
||||
user: { sub: string; username: string; role: string }
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireAuth(request: FastifyRequest, reply: FastifyReply) {
|
||||
try {
|
||||
await request.jwtVerify()
|
||||
} catch {
|
||||
return reply.code(401).send({ error: { code: 'unauthorized', message: 'Требуется вход' } })
|
||||
}
|
||||
|
||||
const row = request.server.db
|
||||
.select()
|
||||
.from(operators)
|
||||
.where(eq(operators.id, request.user.sub))
|
||||
.get()
|
||||
|
||||
if (!row || row.disabled) {
|
||||
return reply.code(401).send({ error: { code: 'unauthorized', message: 'Оператор недоступен' } })
|
||||
}
|
||||
|
||||
;(request as FastifyRequest & { operator: AuthOperator }).operator = {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
role: row.role,
|
||||
}
|
||||
}
|
||||
|
||||
export function getOperator(request: FastifyRequest): AuthOperator {
|
||||
return (request as FastifyRequest & { operator: AuthOperator }).operator
|
||||
}
|
||||
Reference in New Issue
Block a user