Skip to content

Commit cea37b4

Browse files
committed
adds oauth to middleware
1 parent 1a678ee commit cea37b4

2 files changed

Lines changed: 44 additions & 2 deletions

File tree

server/api/auth/session.delete.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ export default defineEventHandler(async event => {
33
password: process.env.NUXT_SESSION_PASSWORD as string,
44
})
55

6-
//TODO clear out the oauth agent
7-
6+
let oauthSession = await event.context.getOAuthSession()
7+
await oauthSession?.signOut()
88
await session.clear()
99

1010
return 'Session cleared'

server/plugins/atproto-session.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { H3Event } from 'h3'
2+
import { getOauthClientMetadata } from '#server/utils/atproto'
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'
6+
7+
/**
8+
* Server middleware that attaches an atproto oauth session to the event context if a user is logged in.
9+
* This allows app composables to access atproto clients
10+
*/
11+
export default defineNitroPlugin(nitroApp => {
12+
const getOAuthSession = async (event: H3Event) => {
13+
const clientMetadata = getOauthClientMetadata()
14+
const stateStore = new StateStore(event)
15+
const sessionStore = new SessionStore(event)
16+
const client = new NodeOAuthClient({
17+
stateStore,
18+
sessionStore,
19+
clientMetadata,
20+
})
21+
const currentSession = await sessionStore.get()
22+
if (currentSession) {
23+
//TODO may be better to grab the session key from cookie or abstract that way some to share code
24+
return await client.restore(currentSession.tokenSet.sub)
25+
}
26+
return undefined
27+
}
28+
29+
// Attach to event context for access in composables via useRequestEvent()
30+
nitroApp.hooks.hook('request', event => {
31+
event.context.getOAuthSession = () => getOAuthSession(event)
32+
})
33+
})
34+
35+
export type GetOAuthSession = () => Promise<OAuthSession | undefined>
36+
37+
// Extend the H3EventContext type
38+
declare module 'h3' {
39+
interface H3EventContext {
40+
getOAuthSession: GetOAuthSession
41+
}
42+
}

0 commit comments

Comments
 (0)