21
21
import { Organization , AsgardeoAPIError , TokenResponse } from '@asgardeo/node' ;
22
22
import getSessionId from './getSessionId' ;
23
23
import AsgardeoNextClient from '../../AsgardeoNextClient' ;
24
+ import logger from '../../utils/logger' ;
25
+ import SessionManager from '../../utils/SessionManager' ;
26
+ import { cookies } from 'next/headers' ;
24
27
25
28
/**
26
29
* Server action to switch organization.
@@ -30,11 +33,10 @@ const switchOrganization = async (
30
33
sessionId : string | undefined ,
31
34
) : Promise < TokenResponse | Response > => {
32
35
try {
36
+ const cookieStore = await cookies ( ) ;
33
37
const client : AsgardeoNextClient = AsgardeoNextClient . getInstance ( ) ;
34
- const response : TokenResponse | Response = await client . switchOrganization (
35
- organization ,
36
- sessionId ?? ( ( await getSessionId ( ) ) as string ) ,
37
- ) ;
38
+ const _sessionId : string = sessionId ?? ( ( await getSessionId ( ) ) as string ) ;
39
+ const response : TokenResponse | Response = await client . switchOrganization ( organization , _sessionId ) ;
38
40
39
41
// After switching organization, we need to refresh the page to get updated session data
40
42
// This is because server components don't maintain state between function calls
@@ -43,10 +45,30 @@ const switchOrganization = async (
43
45
// Revalidate the current path to refresh the component with new data
44
46
revalidatePath ( '/' ) ;
45
47
48
+ if ( response ) {
49
+ const idToken = await client . getDecodedIdToken ( _sessionId , ( response as TokenResponse ) . idToken ) ;
50
+ const userIdFromToken = idToken [ 'sub' ] ;
51
+ const accessToken = ( response as TokenResponse ) . accessToken ;
52
+ const scopes = ( response as TokenResponse ) . scope ;
53
+ const organizationId = idToken [ 'user_org' ] || idToken [ 'organization_id' ] ;
54
+
55
+ const sessionToken = await SessionManager . createSessionToken (
56
+ accessToken ,
57
+ userIdFromToken as string ,
58
+ _sessionId as string ,
59
+ scopes ,
60
+ organizationId ,
61
+ ) ;
62
+
63
+ logger . debug ( '[switchOrganization] Session token created successfully.' ) ;
64
+
65
+ cookieStore . set ( SessionManager . getSessionCookieName ( ) , sessionToken , SessionManager . getSessionCookieOptions ( ) ) ;
66
+ }
67
+
46
68
return response ;
47
69
} catch ( error ) {
48
70
throw new AsgardeoAPIError (
49
- `Failed to switch the organizations: ${ error instanceof Error ? error . message : String ( error ) } ` ,
71
+ `Failed to switch the organizations: ${ error instanceof Error ? error . message : String ( JSON . stringify ( error ) ) } ` ,
50
72
'switchOrganization-ServerActionError-001' ,
51
73
'nextjs' ,
52
74
error instanceof AsgardeoAPIError ? error . statusCode : undefined ,
0 commit comments