feat: add tma authorization middleware
This commit is contained in:
parent
22eb41b0bc
commit
4a8b0ac806
1 changed files with 28 additions and 0 deletions
28
src/middleware/auth.ts
Normal file
28
src/middleware/auth.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { createMiddleware } from 'hono/factory'
|
||||||
|
import { InitDataError, validateInitData } from '@/lib/initdata.js'
|
||||||
|
import { config } from '@/shared/config.js'
|
||||||
|
|
||||||
|
export interface AuthEnv {
|
||||||
|
Variables: { userId: bigint }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authMiddleware = createMiddleware<AuthEnv>(async (c, next) => {
|
||||||
|
const header = c.req.header('Authorization') ?? ''
|
||||||
|
const idx = header.indexOf(' ')
|
||||||
|
const scheme = idx === -1 ? '' : header.slice(0, idx)
|
||||||
|
const raw = idx === -1 ? '' : header.slice(idx + 1)
|
||||||
|
if (scheme !== 'tma' || !raw)
|
||||||
|
return c.json({ error: 'missing-tma-authorization' }, 401)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { userId } = validateInitData(raw, config.botToken, config.authDateMaxAgeSeconds)
|
||||||
|
c.set('userId', userId)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
if (e instanceof InitDataError)
|
||||||
|
return c.json({ error: e.code }, 401)
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
|
||||||
|
await next()
|
||||||
|
})
|
||||||
Loading…
Add table
Add a link
Reference in a new issue