Skip to content

Commit

Permalink
multivaluehaders
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobbe committed Jun 28, 2024
1 parent 50cfd14 commit 6e991de
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 11 deletions.
34 changes: 25 additions & 9 deletions packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ import {

import * as DbAuthError from './errors'
import {
buildDbAuthResponse,
cookieName,
decryptSession,
encryptSession,
extractCookie,
extractHashingOptions,
getDbAuthResponseBuilder,
getSession,
hashPassword,
hashToken,
Expand Down Expand Up @@ -303,6 +303,7 @@ type Params = AuthenticationResponseJSON &
}

type DbAuthSession<T = unknown> = Record<string, T>
type CorsHeaders = Record<string, string>

const DEFAULT_ALLOWED_USER_FIELDS = ['id', 'email']

Expand All @@ -326,12 +327,25 @@ export class DbAuthHandler<
sessionExpiresDate: string
webAuthnExpiresDate: string
encryptedSession: string | null = null
createResponse: (
response: {
body?: string
statusCode: number
headers?: Headers
},
corsHeaders: CorsHeaders,
) => {
headers: Record<string, string | string[]>
body?: string | undefined
statusCode: number
}

public get normalizedRequest() {
if (!this._normalizedRequest) {
// This is a dev time error, no need to throw a specialized error
throw new Error(
'dbAuthHandler has not been initialised. Either await dbAuthHandler.invoke() or call await dbAuth.init()',
'dbAuthHandler has not been initialized. Either await ' +
'dbAuthHandler.invoke() or call await dbAuth.init()',
)
}
return this._normalizedRequest
Expand Down Expand Up @@ -455,6 +469,8 @@ export class DbAuthHandler<

this.cookie = extractCookie(event) || ''

this.createResponse = getDbAuthResponseBuilder(event)

this._validateOptions()

this.db = this.options.db
Expand Down Expand Up @@ -523,14 +539,14 @@ export class DbAuthHandler<
corsHeaders = this.corsContext.getRequestHeaders(this.normalizedRequest)
// Return CORS headers for OPTIONS requests
if (this.corsContext.shouldHandleCors(this.normalizedRequest)) {
return buildDbAuthResponse({ body: '', statusCode: 200 }, corsHeaders)
return this.createResponse({ body: '', statusCode: 200 }, corsHeaders)
}
}

// if there was a problem decryption the session, just return the logout
// response immediately
if (this.hasInvalidSession) {
return buildDbAuthResponse(
return this.createResponse(
this._ok(...this._logoutResponse()),
corsHeaders,
)
Expand All @@ -549,12 +565,12 @@ export class DbAuthHandler<

// get the auth method the incoming request is trying to call
if (!DbAuthHandler.METHODS.includes(method)) {
return buildDbAuthResponse(this._notFound(), corsHeaders)
return this.createResponse(this._notFound(), corsHeaders)
}

// make sure it's using the correct verb, GET vs POST
if (this.httpMethod !== DbAuthHandler.VERBS[method]) {
return buildDbAuthResponse(this._notFound(), corsHeaders)
return this.createResponse(this._notFound(), corsHeaders)
}

// call whatever auth method was requested and return the body and headers
Expand All @@ -573,12 +589,12 @@ export class DbAuthHandler<
console.log('------')
console.log('')

return buildDbAuthResponse(this._ok(body, headers, options), corsHeaders)
return this.createResponse(this._ok(body, headers, options), corsHeaders)
} catch (e: any) {
if (e instanceof DbAuthError.WrongVerbError) {
return buildDbAuthResponse(this._notFound(), corsHeaders)
return this.createResponse(this._notFound(), corsHeaders)
} else {
return buildDbAuthResponse(
return this.createResponse(
this._badRequest(e.message || e),
corsHeaders,
)
Expand Down
50 changes: 48 additions & 2 deletions packages/auth-providers/dbAuth/api/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,12 +258,58 @@ export const cookieName = (name: string | undefined) => {
return cookieName
}

export function getDbAuthResponseBuilder(
event: APIGatewayProxyEvent | Request,
) {
return (
response: {
body?: string
statusCode: number
headers?: Headers
},
corsHeaders: CorsHeaders,
) => {
const headers: Record<string, string | Array<string>> = {
...Object.fromEntries(response.headers?.entries() || []),
...corsHeaders,
}

const multiValueHeaders: Record<string, Array<string>> = {}
const setCookieHeaders = response.headers?.getSetCookie() || []

if (setCookieHeaders.length > 0) {
if ((event as any).multiValueHeaders) {
console.log('getDbAuthResponseBuilder: multiValueHeaders')
multiValueHeaders['Set-Cookie'] = setCookieHeaders
} else {
headers['set-cookie'] = setCookieHeaders
}
}

const dbAuthResponse = {
...response,
headers,
}

console.log('')
console.log('------')
console.log('')
console.log('dbAuthResponse from builder', dbAuthResponse)
console.log('')
console.log('------')
console.log('')

return dbAuthResponse
}
}

/**
* Returns a lambda response!
* Returns a lambda response
*
* This is used as the final call to return a response from the handler.
*
* Converts "Set-Cookie" headers to an array of strings.
* Converts "Set-Cookie" headers to an array of strings or a multiValueHeaders
* object
*/
export const buildDbAuthResponse = (
response: {
Expand Down

0 comments on commit 6e991de

Please sign in to comment.