|
| 1 | +/** |
| 2 | + * Copyright (c) 2026, WSO2 LLC. (https://www.wso2.com). |
| 3 | + * |
| 4 | + * WSO2 LLC. licenses this file to you under the Apache License, |
| 5 | + * Version 2.0 (the "License"); you may not use this file except |
| 6 | + * in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, |
| 12 | + * software distributed under the License is distributed on an |
| 13 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | + * KIND, either express or implied. See the License for the |
| 15 | + * specific language governing permissions and limitations |
| 16 | + * under the License. |
| 17 | + */ |
| 18 | + |
| 19 | +'use server'; |
| 20 | + |
| 21 | +import {ReadonlyRequestCookies} from 'next/dist/server/web/spec-extension/adapters/request-cookies'; |
| 22 | +import {cookies} from 'next/headers'; |
| 23 | +import {TokenExchangeRequestConfig, TokenResponse} from '@asgardeo/node'; |
| 24 | +import AsgardeoNextClient from '../../AsgardeoNextClient'; |
| 25 | +import SessionManager from '../../utils/SessionManager'; |
| 26 | + |
| 27 | +/** |
| 28 | + * Exchange tokens based on the provided configuration. |
| 29 | + * This supports various token exchange grant types like organization switching. |
| 30 | + * |
| 31 | + * @param config - Token exchange request configuration |
| 32 | + * @param sessionId - Optional session ID for the exchange |
| 33 | + * @returns The token response from the exchange operation |
| 34 | + * @throws {AsgardeoRuntimeError} If the token exchange fails |
| 35 | + */ |
| 36 | +const exchangeToken = async ( |
| 37 | + config: TokenExchangeRequestConfig, |
| 38 | + sessionId?: string, |
| 39 | +): Promise<TokenResponse | Response | undefined> => { |
| 40 | + let resolvedSessionId: string | undefined = sessionId; |
| 41 | + |
| 42 | + if (!resolvedSessionId) { |
| 43 | + const cookieStore: ReadonlyRequestCookies = await cookies(); |
| 44 | + const sessionToken = cookieStore.get(SessionManager.getSessionCookieName())?.value; |
| 45 | + |
| 46 | + if (sessionToken) { |
| 47 | + try { |
| 48 | + const sessionPayload = await SessionManager.verifySessionToken(sessionToken); |
| 49 | + resolvedSessionId = sessionPayload['sessionId'] as string; |
| 50 | + } catch (error) { |
| 51 | + return undefined; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (!resolvedSessionId) { |
| 57 | + return undefined; |
| 58 | + } |
| 59 | + |
| 60 | + const client = AsgardeoNextClient.getInstance(); |
| 61 | + try { |
| 62 | + return await client.exchangeToken(config, resolvedSessionId); |
| 63 | + } catch (error) { |
| 64 | + return undefined; |
| 65 | + } |
| 66 | +}; |
| 67 | + |
| 68 | +export default exchangeToken; |
0 commit comments