Skip to content

Commit

Permalink
adding new authLink
Browse files Browse the repository at this point in the history
  • Loading branch information
pellicceama committed Nov 25, 2024
1 parent f34d9ad commit e20fed1
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 72 deletions.
35 changes: 0 additions & 35 deletions packages/fetch-links/links/authHeadersLink.ts

This file was deleted.

39 changes: 39 additions & 0 deletions packages/fetch-links/links/authLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
AuthClientOptions,
mergeHeaders,
modifyRequest,
openIntProxyLink,
} from '@opensdks/runtime'
import {Link} from '../link.js'

export function authLink(auth: AuthClientOptions, baseUrl: string): Link {
if (!auth) {
// No Op
return (req, next) => next(req)
}

if (auth.openInt) {
return openIntProxyLink(auth.openInt, baseUrl)
}

const headers = {
['authorization']: auth.oauth?.accessToken
? `Bearer ${auth.oauth.accessToken}`
: auth?.bearer
? `Bearer ${auth.bearer}`
: auth?.basic
? `Basic ${btoa(`${auth.basic?.username}:${auth.basic?.password}`)}`
: '',
} satisfies HeadersInit

return async (req, next) => {
req.headers.delete('authorization')
const res = await next(
modifyRequest(req, {
headers: mergeHeaders(req.headers, headers, {}),
body: req.body,
}),
)
return res
}
}
23 changes: 10 additions & 13 deletions packages/fetch-links/links/openIntProxyLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,14 @@ interface OpenIntProxyHeaders {

function removeEmptyHeaders(headers: OpenIntProxyHeaders): HeadersInit {
return Object.fromEntries(
Object.entries(headers).filter(([_, value]) => value !== ''),
Object.entries(headers).filter(([_, value]) => value && value !== ''),
) satisfies HeadersInit
}

export function openIntProxyLink(opts: OpenIntProxyLinkOptions): Link {
export function openIntProxyLink(
opts: OpenIntProxyLinkOptions,
baseUrl: string,
): Link {
validateOpenIntProxyLinkOptions(opts)
const {apiKey, token, resourceId, endUserId, connectorName} = opts

Expand All @@ -70,13 +73,12 @@ export function openIntProxyLink(opts: OpenIntProxyLinkOptions): Link {
}) satisfies HeadersInit

return async (req, next) => {
const baseUrl = getBaseUrl(req.url)
const proxyUrl = 'https://app.openint.dev/api/proxy/'
// if (req.url.includes(proxyUrl)) {
// // Was previously necessary as link called twice leading to /api/proxy/api/proxy/?
// return next(req)
// }
const proxyUrl = 'https://api.openint.dev/proxy'

if (req.url.includes(proxyUrl)) {
// QQ: why is this necessary? why is this link called twice leading to /api/proxy/api/proxy/?
return next(req)
}
req.headers.delete('authorization')
const res = await next(
modifyRequest(req, {
Expand All @@ -88,8 +90,3 @@ export function openIntProxyLink(opts: OpenIntProxyLinkOptions): Link {
return res
}
}

function getBaseUrl(urlStr: string) {
const url = new URL(urlStr)
return `${url.protocol}//${url.host}/`
}
10 changes: 9 additions & 1 deletion packages/runtime/createClient.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import {createFormUrlEncodedBodySerializer} from '@opensdks/runtime'
import {
createClient,
createFormUrlEncodedBodySerializer,
} from '@opensdks/runtime'

test('application/x-www-form-urlencoded defaut dot style', () => {
const formUrlEncodedBodySerializer = createFormUrlEncodedBodySerializer({})
Expand Down Expand Up @@ -50,3 +53,8 @@ test('application/x-www-form-urlencoded bracket style', () => {
'account=acct_111222&components[account_onboarding][enabled]=true&components[nested][0]=hello&components[nested][1][key]=world',
)
})

test('expect links array to have 2 elements', () => {
const client = createClient()
expect(client.links.length).toBe(2)
})
29 changes: 6 additions & 23 deletions packages/runtime/createClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import type {PathsWithMethod} from 'openapi-typescript-helpers'
import {
applyLinks,
fetchLink,
openIntProxyLink,
OpenIntProxyLinkOptions,
validateOpenIntProxyLinkOptions,
type HTTPMethod,
type Link,
} from '@opensdks/fetch-links'
import {authLink} from '../fetch-links/links/authLink.js'
import {HTTPError} from './HTTPError.js'
import {flattenNestedObject, FlattenOptions} from './utils.js'

Expand All @@ -18,11 +17,10 @@ type _ClientOptions = NonNullable<Parameters<typeof _createClient>[0]>
export type AuthClientOptions = {
openInt?: OpenIntProxyLinkOptions
// to be passed as Authorization header as a bearer token
oauth?: {accessToken: string}
authorizationHeader?: {
basic?: {username: string; password: string}
bearer?: string
}
oauth?: {accessToken: string; refreshToken?: string; expiresAt?: number}
basic?: {username: string; password: string}
/** non oauth / directly specifying bearer token */
bearer?: string
}
export interface ClientOptions extends _ClientOptions {
links?: Link[] | ((defaultLinks: Link[]) => Link[])
Expand All @@ -46,22 +44,7 @@ export function createClient<Paths extends {}>({
}: ClientOptions = {}) {
const links = typeof _links === 'function' ? _links(defaultLinks) : _links

const expectsAuthProxy = validateOpenIntProxyLinkOptions(
clientOptions.auth?.openInt ?? {},
)

const hasOtherAuthMethods =
clientOptions.auth?.authorizationHeader || clientOptions.auth?.oauth

if (expectsAuthProxy && hasOtherAuthMethods) {
throw new Error('Cannot use both openInt proxy and other auth methods')
}

if (expectsAuthProxy) {
links.unshift(openIntProxyLink(clientOptions.auth?.openInt ?? {}))
} else if (hasOtherAuthMethods) {
links.unshift(fetchLink())
}
links.unshift(authLink(clientOptions.auth ?? {}, clientOptions.baseUrl ?? ''))

const customFetch: typeof fetch = (url, init) =>
applyLinks(new Request(url, init), links)
Expand Down

0 comments on commit e20fed1

Please sign in to comment.