11import { and , eq } from "drizzle-orm" ;
22import { createMiddleware } from "hono/factory" ;
33import { auth } from "hono/utils/basic-auth" ;
4+ import { z } from "zod" ;
45import { db } from "../db.ts" ;
56import { requestBody } from "../helpers.ts" ;
67import {
@@ -9,12 +10,10 @@ import {
910 type AccountOwner ,
1011 type Application ,
1112 type Scope ,
13+ accessTokens ,
1214 applications ,
1315} from "../schema.ts" ;
1416
15- import { z } from "zod" ;
16- import { getAccessToken } from "./helpers.ts" ;
17-
1817export type Variables = {
1918 token : AccessToken & {
2019 application : Application ;
@@ -149,11 +148,23 @@ export const clientAuthentication = createMiddleware<{
149148
150149export const tokenRequired = createMiddleware < { Variables : Variables } > (
151150 async ( c , next ) => {
152- const accessToken = await getAccessToken ( c ) ;
153- if ( typeof accessToken === "undefined" ) {
154- return c . json ( { error : "unauthorized" } , 401 ) ;
151+ const authorization = c . req . header ( "Authorization" ) ;
152+ if ( authorization == null ) return c . json ( { error : "unauthorized" } , 401 ) ;
153+ const match = / ^ (?: b e a r e r ) \s + ( .+ ) $ / i. exec ( authorization ) ;
154+ if ( match == null ) return c . json ( { error : "unauthorized" } , 401 ) ;
155+ const token = match [ 1 ] ;
156+
157+ const accessToken = await db . query . accessTokens . findFirst ( {
158+ where : eq ( accessTokens . code , token ) ,
159+ with : {
160+ accountOwner : { with : { account : { with : { successor : true } } } } ,
161+ application : true ,
162+ } ,
163+ } ) ;
164+
165+ if ( accessToken === undefined ) {
166+ return c . json ( { error : "invalid_token" } , 401 ) ;
155167 }
156- if ( accessToken === null ) return c . json ( { error : "invalid_token" } , 401 ) ;
157168
158169 c . set ( "token" , accessToken ) ;
159170 await next ( ) ;
0 commit comments