forked from asgardeo/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsgardeoProvider.tsx
More file actions
233 lines (211 loc) · 8.37 KB
/
AsgardeoProvider.tsx
File metadata and controls
233 lines (211 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use server';
import {BrandingPreference, AsgardeoRuntimeError, IdToken, Organization, User, UserProfile} from '@asgardeo/node';
import {AsgardeoProviderProps} from '@asgardeo/react';
import {FC, PropsWithChildren, ReactElement} from 'react';
import clearSession from './actions/clearSession';
import createOrganization from './actions/createOrganization';
import getAllOrganizations from './actions/getAllOrganizations';
import getBrandingPreference from './actions/getBrandingPreference';
import getCurrentOrganizationAction from './actions/getCurrentOrganizationAction';
import getMyOrganizations from './actions/getMyOrganizations';
import getSessionId from './actions/getSessionId';
import getSessionPayload from './actions/getSessionPayload';
import getUserAction from './actions/getUserAction';
import getUserProfileAction from './actions/getUserProfileAction';
import handleOAuthCallbackAction from './actions/handleOAuthCallbackAction';
import isSignedIn from './actions/isSignedIn';
import refreshToken from './actions/refreshToken';
import signInAction from './actions/signInAction';
import signOutAction from './actions/signOutAction';
import signUpAction from './actions/signUpAction';
import switchOrganization from './actions/switchOrganization';
import updateUserProfileAction from './actions/updateUserProfileAction';
import AsgardeoNextClient from '../AsgardeoNextClient';
import AsgardeoClientProvider from '../client/contexts/Asgardeo/AsgardeoProvider.js';
import {AsgardeoNextConfig} from '../models/config';
import logger from '../utils/logger';
import {SessionTokenPayload} from '../utils/SessionManager';
/**
* Props interface of {@link AsgardeoServerProvider}
*/
export type AsgardeoServerProviderProps = Partial<AsgardeoProviderProps> & {
clientSecret?: string;
};
/**
* Server-side provider component for Asgardeo authentication.
* Wraps the client-side provider and handles server-side authentication logic.
* Uses the singleton AsgardeoNextClient instance for consistent authentication state.
*
* @param props - Props injected into the component.
*
* @example
* ```tsx
* <AsgardeoServerProvider config={asgardeoConfig}>
* <YourApp />
* </AsgardeoServerProvider>
* ```
*
* @returns AsgardeoServerProvider component.
*/
const AsgardeoServerProvider: FC<PropsWithChildren<AsgardeoServerProviderProps>> = async ({
children,
afterSignInUrl,
afterSignOutUrl,
..._config
}: PropsWithChildren<AsgardeoServerProviderProps>): Promise<ReactElement> => {
const asgardeoClient: AsgardeoNextClient = AsgardeoNextClient.getInstance();
let config: Partial<AsgardeoNextConfig> = {};
try {
await asgardeoClient.initialize(_config as AsgardeoNextConfig);
logger.debug('[AsgardeoServerProvider] Asgardeo client initialized successfully.');
config = await asgardeoClient.getConfiguration();
} catch (error) {
logger.error('[AsgardeoServerProvider] Failed to initialize Asgardeo client:', error?.toString());
throw new AsgardeoRuntimeError(
`Failed to initialize Asgardeo client: ${error?.toString()}`,
'next-ConfigurationError-001',
'next',
'An error occurred while initializing the Asgardeo client. Please check your configuration.',
);
}
if (!asgardeoClient.isInitialized) {
return <></>;
}
// Try to get session information from JWT first, then fall back to legacy
const sessionPayload: SessionTokenPayload | undefined = await getSessionPayload();
const sessionId: string = sessionPayload?.sessionId || (await getSessionId()) || '';
const signedIn: boolean = await isSignedIn(sessionId);
let user: User = {};
let userProfile: UserProfile = {
flattenedProfile: {},
profile: {},
schemas: [],
};
let currentOrganization: Organization = {
id: '',
name: '',
orgHandle: '',
};
let myOrganizations: Organization[] = [];
let brandingPreference: BrandingPreference | null = null;
if (signedIn) {
let updatedBaseUrl: string | undefined = config?.baseUrl;
if (sessionPayload?.organizationId) {
updatedBaseUrl = `${config?.baseUrl}/o`;
config = {...config, baseUrl: updatedBaseUrl};
} else if (sessionId) {
try {
const idToken: IdToken = await asgardeoClient.getDecodedIdToken(sessionId);
if (idToken?.['user_org']) {
updatedBaseUrl = `${config?.baseUrl}/o`;
config = {...config, baseUrl: updatedBaseUrl};
}
} catch {
// Continue without organization info
}
}
// Check if user profile fetching is enabled (default: true)
const shouldFetchUserProfile: boolean = config?.preferences?.user?.fetchUserProfile !== false;
// Check if organization fetching is enabled (default: true)
const shouldFetchOrganizations: boolean = config?.preferences?.user?.fetchOrganizations !== false;
if (shouldFetchUserProfile) {
try {
const userResponse: {
data: {user: User | null};
error: string | null;
success: boolean;
} = await getUserAction(sessionId);
const userProfileResponse: {
data: {userProfile: UserProfile};
error: string | null;
success: boolean;
} = await getUserProfileAction(sessionId);
user = userResponse.data?.user || {};
userProfile = userProfileResponse.data?.userProfile ?? userProfile;
} catch (error) {
logger.warn('[AsgardeoServerProvider] Failed to fetch user profile from SCIM2:', error?.toString());
}
}
if (shouldFetchOrganizations) {
try {
const currentOrganizationResponse: {
data: {organization?: Organization; user?: Record<string, unknown>};
error: string | null;
success: boolean;
} = await getCurrentOrganizationAction(sessionId);
if (sessionId) {
myOrganizations = await getMyOrganizations({}, sessionId);
} else {
logger.warn('[AsgardeoServerProvider] No session ID available, skipping organization fetch');
}
currentOrganization = currentOrganizationResponse?.data?.organization as Organization;
} catch (error) {
logger.warn('[AsgardeoServerProvider] Failed to fetch organization info:', error?.toString());
}
}
}
// Fetch branding preference if branding is enabled in config
if (config?.preferences?.theme?.inheritFromBranding !== false) {
try {
brandingPreference = await getBrandingPreference(
{
baseUrl: config?.baseUrl as string,
locale: 'en-US',
name: config.applicationId || config.organizationHandle,
type: config.applicationId ? 'APP' : 'ORG',
},
sessionId,
);
} catch (error) {
// eslint-disable-next-line no-console
console.warn('[AsgardeoServerProvider] Failed to fetch branding preference:', error);
}
}
return (
<AsgardeoClientProvider
organizationHandle={config?.organizationHandle}
applicationId={config?.applicationId}
baseUrl={config?.baseUrl}
signIn={signInAction}
clearSession={clearSession}
refreshToken={refreshToken}
signOut={signOutAction}
signUp={signUpAction}
handleOAuthCallback={handleOAuthCallbackAction}
signInUrl={config?.signInUrl}
signUpUrl={config?.signUpUrl}
preferences={config?.preferences}
clientId={config?.clientId}
user={user}
currentOrganization={currentOrganization}
userProfile={userProfile}
updateProfile={updateUserProfileAction}
isSignedIn={signedIn}
myOrganizations={myOrganizations}
getAllOrganizations={getAllOrganizations}
switchOrganization={switchOrganization}
brandingPreference={brandingPreference}
createOrganization={createOrganization}
>
{children}
</AsgardeoClientProvider>
);
};
export default AsgardeoServerProvider;