Skip to content

Commit

Permalink
fix typos and set correct origin for local development
Browse files Browse the repository at this point in the history
  • Loading branch information
divyam234 committed Dec 28, 2023
1 parent f527541 commit 6366a99
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 23 deletions.
7 changes: 4 additions & 3 deletions packages/auth-js/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Auth js middleware for Hono
# Auth.js middleware for Hono

This is a [Auth js](https://next-auth.js.org) third-party middleware for [Hono](https://github.com/honojs/hono).
This is a [Auth.js](https://authjs.dev) third-party middleware for [Hono](https://github.com/honojs/hono).

This middleware can be used to inject the Auth js session into the request context.
This middleware can be used to inject the Auth.js session into the request context.

## Installation

Expand All @@ -16,6 +16,7 @@ Before starting using the middleware you must set the following environment vari

```plain
AUTH_SECRET=#required
AUTH_URL=#optional
```

## How to Use
Expand Down
31 changes: 13 additions & 18 deletions packages/auth-js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Auth } from '@auth/core'
import type { AdapterUser } from '@auth/core/adapters'
import type { JWT } from '@auth/core/jwt'
import type { Session } from '@auth/core/types'
import type { Context, HonoRequest, MiddlewareHandler } from 'hono'
import type { Context, MiddlewareHandler } from 'hono'
import { HTTPException } from 'hono/http-exception'

declare module 'hono' {
Expand All @@ -25,23 +25,17 @@ export type AuthUser = {
user?: AdapterUser
}

export interface AuthConfig extends Omit<AuthConfigCore, 'raw'> {

}
export interface AuthConfig extends Omit<AuthConfigCore, 'raw'> {}

export type ConfigHandler = (c: Context) => AuthConfig

function detectOrigin(req:HonoRequest): URL {

const host = req.header('x-forwarded-host') ?? req.header('host')
const protocol = req.header('x-forwarded-proto') === 'http' ? 'http' : 'https'

return new URL(`${protocol}://${host}`)
function reqWithEnvUrl(req: Request, authUrl?: string): Request {
return authUrl ? new Request(new URL(req.url, authUrl).href, req) : req
}

function setEnvDefaults(env: AuthEnv, config: AuthConfig) {
config.secret ??= env.AUTH_SECRET
config.trustHost = true
config.trustHost = true
config.redirectProxyUrl ??= env.AUTH_REDIRECT_PROXY_URL
config.providers = config.providers.map((p) => {
const finalProvider = typeof p === 'function' ? p({}) : p
Expand All @@ -59,7 +53,7 @@ function setEnvDefaults(env: AuthEnv, config: AuthConfig) {

export async function getAuthUser(c: Context): Promise<AuthUser | null> {
const config = c.get('authConfig')
const origin = detectOrigin(c.req)
const origin = new URL(c.req.url, c.env.AUTH_URL).origin
const request = new Request(`${origin}/session`, {
headers: { cookie: c.req.header('cookie') ?? '' },
})
Expand All @@ -74,23 +68,24 @@ export async function getAuthUser(c: Context): Promise<AuthUser | null> {
...config.callbacks,
async session(...args) {
authUser = args[0]
const session = (await config.callbacks?.session?.(...args)) ?? args[0].session
const session =
(await config.callbacks?.session?.(...args)) ?? args[0].session
// @ts-expect-error either user or token will be defined
const user = args[0].user ?? args[0].token
const user = args[0].user ?? args[0].token
return { user, ...session } satisfies Session
},
},
})) as Response

const session = (await response.json()) as Session | null

return session && session.user ? authUser : null
}

export function verifyAuth(): MiddlewareHandler {
return async (c, next) => {
const authUser = await getAuthUser(c)
const isAuth = (!!authUser?.token) || (!!authUser?.user)
const isAuth = !!authUser?.token || !!authUser?.user
if (!isAuth) {
const res = new Response('Unauthorized', {
status: 401,
Expand All @@ -117,10 +112,10 @@ export function authHandler(): MiddlewareHandler {
setEnvDefaults(c.env, config)

if (!config.secret) {
throw new HTTPException(500, {message:'Missing AUTH_SECRET'})
throw new HTTPException(500, { message: 'Missing AUTH_SECRET' })
}

const res = await Auth(c.req.raw,config)
const res = await Auth(reqWithEnvUrl(c.req.raw, c.env.AUTH_URL), config)
return new Response(res.body, res)
}
}
4 changes: 2 additions & 2 deletions packages/auth-js/src/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export { SessionProviderProps }
class AuthConfigManager {
private static instance: AuthConfigManager | null = null
_config: AuthClientConfig = {
baseUrl: parseUrl(window.location.href).origin,
basePath: parseUrl(window.location.href).path,
baseUrl: parseUrl(window.location.origin).origin,
basePath: parseUrl(window.location.origin).path,
credentials:'same-origin',
_lastSync: 0,
_session: undefined,
Expand Down

0 comments on commit 6366a99

Please sign in to comment.