Skip to content

Commit 86fb98a

Browse files
committed
moved to a defineEventHandler
1 parent cea37b4 commit 86fb98a

3 files changed

Lines changed: 42 additions & 47 deletions

File tree

server/api/auth/session.delete.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
export default defineEventHandler(async event => {
1+
import { eventHandlerWithOAuthSession } from '#server/utils/atproto'
2+
3+
export default eventHandlerWithOAuthSession(async (event, oAuthSession) => {
24
const session = await useSession(event, {
35
password: process.env.NUXT_SESSION_PASSWORD as string,
46
})
57

6-
let oauthSession = await event.context.getOAuthSession()
7-
await oauthSession?.signOut()
8+
await oAuthSession?.signOut()
89
await session.clear()
910

1011
return 'Session cleared'

server/plugins/atproto-session.ts

Lines changed: 0 additions & 42 deletions
This file was deleted.

server/utils/atproto.ts

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import 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

610
export 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

Comments
 (0)