diff --git a/oauth/src/connections/puzzleIo/init.ts b/oauth/src/connections/puzzleIo/init.ts new file mode 100644 index 00000000..8a8d8120 --- /dev/null +++ b/oauth/src/connections/puzzleIo/init.ts @@ -0,0 +1,49 @@ +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; + +export const init = async ({ body }: DataObject): Promise => { + try { + const { + clientId: client_id, + clientSecret: client_secret, + metadata: { code, redirectUri: redirect_uri, environment }, + } = body; + + const baseUrl: string = + environment === 'test' + ? 'https://staging.southparkdata.com' + : 'https://api.puzzle.io'; + + const response = await axios({ + url: `${baseUrl}/oauth/token`, + method: 'POST', + data: { + grant_type: 'authorization_code', + code, + client_id, + client_secret, + redirect_uri, + }, + }); + + const { + access_token: accessToken, + refresh_token: refreshToken, + token_type: tokenType, + expires_in: expiresIn, + } = response.data; + + return { + accessToken, + refreshToken, + expiresIn, + tokenType: tokenType === 'bearer' ? 'Bearer' : tokenType, + meta: { + environment, + PUZZLE_BASE_URL: baseUrl, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Puzzle.io: ${error}`); + } +}; diff --git a/oauth/src/connections/puzzleIo/refresh.ts b/oauth/src/connections/puzzleIo/refresh.ts new file mode 100644 index 00000000..ecf5a3df --- /dev/null +++ b/oauth/src/connections/puzzleIo/refresh.ts @@ -0,0 +1,49 @@ +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; + +export const refresh = async ({ body }: DataObject): Promise => { + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + OAUTH_REQUEST_PAYLOAD: { redirectUri: redirect_uri }, + OAUTH_METADATA: { meta }, + } = body; + + const { environment } = meta; + + const baseUrl: string = + environment === 'test' + ? 'https://staging.southparkdata.com' + : 'https://api.puzzle.io'; + + const response = await axios({ + url: `${baseUrl}/oauth/token`, + method: 'POST', + data: { + grant_type: 'refresh_token', + refresh_token, + client_id, + client_secret, + redirect_uri, + }, + }); + + const { + access_token: accessToken, + token_type: tokenType, + expires_in: expiresIn, + } = response.data; + + return { + accessToken, + refreshToken: refresh_token, + expiresIn, + tokenType: tokenType === 'bearer' ? 'Bearer' : tokenType, + meta, + }; + } catch (error) { + throw new Error(`Error fetching access token for Puzzle.io: ${error}`); + } +};