@@ -86,32 +86,45 @@ export function createAuthServer(config: ObjectStackAuthServerConfig) {
8686 // Create Better-Auth instance
8787 const auth = betterAuth ( authOptions ) ;
8888
89- // RBAC Integration: Inject permissions into session
90- // This is a custom plugin hook that runs after session retrieval
91- if ( onGetPermissions ) {
92- const originalGetSession = auth . api . getSession . bind ( auth . api ) ;
93- auth . api . getSession = async ( request : any ) => {
94- const session = await originalGetSession ( request ) ;
89+ // RBAC Integration: Enhanced session retrieval with permissions
90+ // Note: This wraps the session retrieval to inject permissions
91+ // If Better-Auth provides official plugin hooks in the future, migrate to those
92+ return {
93+ ...auth ,
94+
95+ // Enhanced getSession that includes permissions
96+ getSessionWithPermissions : async ( request : Request ) => {
97+ const session = await auth . api . getSession ( { request } ) ;
9598
96- if ( session ?. user ?. id ) {
99+ if ( session ?. user ?. id && onGetPermissions ) {
97100 try {
98101 // Query ObjectOS for user permissions
99102 const permissions = await onGetPermissions ( session . user . id ) ;
100103
101- // Inject permissions into session object
102- session . user . permissions = permissions ;
104+ // Return enhanced session with permissions
105+ return {
106+ ...session ,
107+ user : {
108+ ...session . user ,
109+ permissions,
110+ } ,
111+ } ;
103112 } catch ( error ) {
104113 console . error ( 'Failed to load user permissions:' , error ) ;
105- // Don't fail the session if permissions fail to load
106- session . user . permissions = null ;
114+ // Return session without permissions on error
115+ return {
116+ ...session ,
117+ user : {
118+ ...session . user ,
119+ permissions : null ,
120+ } ,
121+ } ;
107122 }
108123 }
109124
110125 return session ;
111- } ;
112- }
113-
114- return auth ;
126+ } ,
127+ } ;
115128}
116129
117130/**
@@ -136,8 +149,17 @@ export interface ObjectStackSession {
136149}
137150
138151/**
139- * Utility to extract session from request
152+ * Utility to extract session with permissions from request
140153 */
141- export async function getSession ( auth : ReturnType < typeof createAuthServer > , request : Request ) : Promise < ObjectStackSession | null > {
154+ export async function getSession (
155+ auth : ReturnType < typeof createAuthServer > ,
156+ request : Request
157+ ) : Promise < ObjectStackSession | null > {
158+ // Use the enhanced getSessionWithPermissions if available
159+ if ( 'getSessionWithPermissions' in auth && typeof auth . getSessionWithPermissions === 'function' ) {
160+ return await auth . getSessionWithPermissions ( request ) as ObjectStackSession | null ;
161+ }
162+
163+ // Fallback to standard getSession
142164 return await auth . api . getSession ( { request } ) as ObjectStackSession | null ;
143165}
0 commit comments