11import type { OAuthClientMetadataInput } from '@atproto/oauth-client-node'
2+ import type { EventHandlerRequest , H3Event } from 'h3'
3+ import type { OAuthSession } from '@atproto/oauth-client-node'
4+ import { NodeOAuthClient } from '@atproto/oauth-client-node'
5+ import { SessionStore , StateStore } from '#server/api/auth/atproto.get'
26
3- // TODO: limit scope as features gets added
4- export const scope = 'atproto transition:generic '
7+ // TODO: limit scope as features gets added. atproto just allows login so no scary login screen till we have scopes
8+ export const scope = 'atproto'
59
610export function getOauthClientMetadata ( ) {
711 const dev = import . meta. dev
@@ -26,3 +30,35 @@ export function getOauthClientMetadata() {
2630 dpop_bound_access_tokens : true ,
2731 } as OAuthClientMetadataInput
2832}
33+
34+ type EventHandlerWithOAuthSession < T extends EventHandlerRequest , D > = (
35+ event : H3Event < T > ,
36+ session : OAuthSession | undefined ,
37+ ) => Promise < D >
38+
39+ async function getOAuthSession ( event : H3Event ) : Promise < OAuthSession | undefined > {
40+ const clientMetadata = getOauthClientMetadata ( )
41+ const stateStore = new StateStore ( event )
42+ const sessionStore = new SessionStore ( event )
43+
44+ const client = new NodeOAuthClient ( {
45+ stateStore,
46+ sessionStore,
47+ clientMetadata,
48+ } )
49+
50+ const currentSession = await sessionStore . get ( )
51+ if ( ! currentSession ) return undefined
52+
53+ // restore using the subject
54+ return await client . restore ( currentSession . tokenSet . sub )
55+ }
56+
57+ export function eventHandlerWithOAuthSession < T extends EventHandlerRequest , D > (
58+ handler : EventHandlerWithOAuthSession < T , D > ,
59+ ) {
60+ return defineEventHandler ( async event => {
61+ const oAuthSession = await getOAuthSession ( event )
62+ return await handler ( event , oAuthSession )
63+ } )
64+ }
0 commit comments