11import type { NodeSavedSession , NodeSavedSessionStore } from '@atproto/oauth-client-node'
22import type { UserServerSession } from '#shared/types/userSession'
33import type { SessionManager } from 'h3'
4+ import { OAUTH_CACHE_STORAGE_BASE } from '#server/utils/atproto/storage'
45
56export class OAuthSessionStore implements NodeSavedSessionStore {
6- private readonly session : SessionManager < UserServerSession >
7+ private readonly serverSession : SessionManager < UserServerSession >
8+ private readonly storage = useStorage ( OAUTH_CACHE_STORAGE_BASE )
79
810 constructor ( session : SessionManager < UserServerSession > ) {
9- this . session = session
11+ this . serverSession = this . serverSession = session
1012 }
1113
12- async get ( ) : Promise < NodeSavedSession | undefined > {
13- const sessionData = this . session . data
14- if ( ! sessionData ) return undefined
15- return sessionData . oauthSession
14+ private createStorageKey ( did : string , sessionId : string ) {
15+ return `sessions:${ did } :${ sessionId } `
1616 }
1717
18- async set ( _key : string , val : NodeSavedSession ) {
19- // We are ignoring the key since the mapping is already done in the session
18+ async get ( key : string ) : Promise < NodeSavedSession | undefined > {
19+ const serverSessionData = this . serverSession . data
20+ if ( ! serverSessionData ) return undefined
21+ if ( ! serverSessionData . oauthSessionId ) {
22+ console . warn ( '[oauth session store] No oauthSessionId found in session data' )
23+ return undefined
24+ }
25+
26+ let session = await this . storage . getItem < NodeSavedSession > (
27+ this . createStorageKey ( key , serverSessionData . oauthSessionId ) ,
28+ )
29+ return session ?? undefined
30+ }
31+
32+ async set ( key : string , val : NodeSavedSession ) {
33+ let sessionId = crypto . randomUUID ( )
34+
2035 try {
21- await this . session . update ( {
22- oauthSession : val ,
36+ await this . serverSession . update ( {
37+ oauthSessionId : sessionId ,
2338 } )
39+
40+ await this . storage . setItem < NodeSavedSession > ( this . createStorageKey ( key , sessionId ) , val )
2441 } catch ( error ) {
2542 // Not sure if this has been happening. But helps with debugging
2643 console . error (
@@ -31,9 +48,16 @@ export class OAuthSessionStore implements NodeSavedSessionStore {
3148 }
3249 }
3350
34- async del ( ) {
35- await this . session . update ( {
36- oauthSession : undefined ,
51+ async del ( key : string ) {
52+ const serverSessionData = this . serverSession . data
53+ if ( ! serverSessionData ) return undefined
54+ if ( ! serverSessionData . oauthSessionId ) {
55+ console . warn ( '[oauth session store] No oauthSessionId found in session data' )
56+ return undefined
57+ }
58+ await this . storage . removeItem ( this . createStorageKey ( key , serverSessionData . oauthSessionId ) )
59+ await this . serverSession . update ( {
60+ oauthSessionId : undefined ,
3761 } )
3862 }
3963}
0 commit comments