Skip to content

Commit

Permalink
SHIP IT
Browse files Browse the repository at this point in the history
  • Loading branch information
dac09 committed Nov 2, 2023
1 parent bb0b36e commit 9fafcf8
Show file tree
Hide file tree
Showing 8 changed files with 24 additions and 37 deletions.
1 change: 0 additions & 1 deletion packages/api/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export const getAuthenticationContext = async ({
}

const { schema, token } = parseAuthorizationHeader(event)
console.log(`👉 \n ~ file: index.ts:79 ~ token:`, token)

let authDecoders: Array<Decoder> = []

Expand Down
16 changes: 7 additions & 9 deletions packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ export class DbAuthHandler<
corsContext: CorsContext | undefined
sessionExpiresDate: string
webAuthnExpiresDate: string
encryptedSession: string | null = null

// class constant: list of auth methods that are supported
static get METHODS(): AuthMethodNames[] {
Expand Down Expand Up @@ -402,9 +403,9 @@ export class DbAuthHandler<
}

try {
const [session, csrfToken] = decryptSession(
getSession(this.cookie, this.options.cookie?.name)
)
this.encryptedSession = getSession(this.cookie, this.options.cookie?.name)

const [session, csrfToken] = decryptSession(this.encryptedSession)
this.session = session
this.sessionCsrfToken = csrfToken
} catch (e) {
Expand Down Expand Up @@ -568,12 +569,8 @@ export class DbAuthHandler<

async getToken() {
try {
const user = await this._getCurrentUser()

// need to return *something* for our existing Authorization header stuff
// to work, so return the user's ID in case we can use it for something
// in the future
return [user[this.options.authFields.id]]
// Just return the encrypted session cookie, to be passed back in the Authorization header
return [this.encryptedSession || '']
} catch (e: any) {
if (e instanceof DbAuthError.NotLoggedInError) {
return this._logoutResponse()
Expand Down Expand Up @@ -1435,6 +1432,7 @@ export class DbAuthHandler<
_ok(body: string, headers = {}, options = { statusCode: 200 }) {
return {
statusCode: options.statusCode,
// @TODO should we do a null check in body?!
body: typeof body === 'string' ? body : JSON.stringify(body),
headers: { 'Content-Type': 'application/json', ...headers },
}
Expand Down
17 changes: 3 additions & 14 deletions packages/auth-providers/dbAuth/api/src/decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,17 @@ export const createAuthDecoder = (cookieNameOption: string): Decoder => {
return null
}

// @TODO for SSR we need to make sure we are passing the cookie from the FE to the BE
const session = dbAuthSession(req.event, cookieNameOption)
const authHeaderUserId = token

if (session.id.toString() !== authHeaderUserId) {
console.error('Authorization header does not match decrypted user ID')
throw new Error('Authorization header does not match decrypted user ID')
}

// We no longer compare the session id with the bearer token
// Because we only pass around the encrypted session (in both cookie and header)
return session
}
}

/** @deprecated use `createAuthDecoder` */
export const authDecoder: Decoder = async (
authHeaderValue: string,
_authHeaderValue: string, // Browser: 4, FEServer: encryptedSession
type: string,
req: { event: APIGatewayProxyEvent }
) => {
Expand All @@ -37,12 +32,6 @@ export const authDecoder: Decoder = async (
// it fall back to the default cookie name `session`, making it backwards
// compatible with existing RW apps.
const session = dbAuthSession(req.event, undefined)
const authHeaderUserId = authHeaderValue

if (session.id.toString() !== authHeaderUserId) {
console.error('Authorization header does not match decrypted user ID')
throw new Error('Authorization header does not match decrypted user ID')
}

return session
}
9 changes: 5 additions & 4 deletions packages/auth-providers/dbAuth/api/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const extractCookie = (event: APIGatewayProxyEvent) => {
return eventGraphiQLHeadersCookie(event) || eventHeadersCookie(event)
}

function extractSessionFromHeader(event: APIGatewayProxyEvent) {
function extractEncryptedSessionFromHeader(event: APIGatewayProxyEvent) {
return event.headers.authorization?.split(' ')[1]
}

Expand Down Expand Up @@ -88,17 +88,18 @@ export const dbAuthSession = (
cookieNameOption: string | undefined
) => {
const cookieHeader = extractCookie(event)
const sessionInAuthHeader = extractSessionFromHeader(event)
const sessionInAuthHeader = extractEncryptedSessionFromHeader(event)

if (cookieHeader && !sessionInAuthHeader) {
if (cookieHeader) {
// i.e. Browser making a request
const [session, _csrfToken] = decryptSession(
getSession(cookieHeader, cookieNameOption)
)
return session
} else if (sessionInAuthHeader) {
// i.e. FE Sever makes the request, and adds encrypted session to the Authorization header
const [session, _csrfToken] = decryptSession(sessionInAuthHeader)

console.log(`👉 \n ~ file: shared.ts:103 ~ session:`, session)
return session
} else {
return null
Expand Down
7 changes: 2 additions & 5 deletions packages/auth/src/AuthProvider/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,10 @@ export function createAuthProvider<
logIn,
logOut,
getToken:
// When its rendering on the server, just get the token from the serverAuthState
typeof window === 'undefined'
? async () => {
console.log(
'xxxxx definitely calling this function',
serverAuthState
)
return serverAuthState.token || null
return serverAuthState.encryptedSession || null
}
: getToken,
getCurrentUser,
Expand Down
4 changes: 2 additions & 2 deletions packages/auth/src/AuthProvider/ServerAuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { AuthProviderState } from './AuthProviderState'
import { defaultAuthProviderState } from './AuthProviderState'

export const ServerAuthContext = React.createContext<
AuthProviderState<never> & { token: string | null }
>({ ...defaultAuthProviderState, token: null })
AuthProviderState<never> & { encryptedSession: string | null }
>({ ...defaultAuthProviderState, encryptedSession: null })

export const ServerAuthProvider = ServerAuthContext.Provider
6 changes: 5 additions & 1 deletion packages/vite/src/streaming/createReactStreamingHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,11 @@ export const createReactStreamingHandler = async (
const middleware = entryServerImport.middleware

if (middleware) {
decodedAuthState = await middleware(req)
try {
decodedAuthState = (await middleware(req)).context
} catch (e) {
console.error('Whooopsie, error in middleware', e)
}
}
}

Expand Down
1 change: 0 additions & 1 deletion packages/web/src/apollo/links.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export function createAuthApolloLink(
) {
return new ApolloLink((operation, forward) => {
const { token } = operation.getContext()

// Only add auth headers when there's a token. `token` is `null` when `!isAuthenticated`.
const authHeaders = token
? {
Expand Down

0 comments on commit 9fafcf8

Please sign in to comment.