Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow custom base path #169

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions docs/nuxt-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default defineNuxtConfig({
// guestRedirectTo: "/", // where to redirect if the user is not authenticated
// authenticatedRedirectTo: "/", // where to redirect if the user is authenticated
// baseUrl: "" // should be something like https://www.my-app.com
// basePath: "/api/auth" // must match catch-all NuxtAuthHandler route
// },
runtimeConfig: {
authJs: {
Expand Down
1 change: 1 addition & 0 deletions packages/authjs-nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"defu": "^6.1.2",
"immer": "^10.0.3",
"jose": "^4.15.4",
"ufo": "^1.4.0",
"unctx": "^2.3.1"
},
"devDependencies": {
Expand Down
7 changes: 7 additions & 0 deletions packages/authjs-nuxt/src/auth-config.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
declare module "#auth-config" {
export const verifyClientOnEveryRequest: boolean
export const guestRedirectTo: string
export const authenticatedRedirectTo: string
export const baseUrl: string
export const basePath: string
}
24 changes: 21 additions & 3 deletions packages/authjs-nuxt/src/module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addImports, addPlugin, addRouteMiddleware, addTypeTemplate, createResolver, defineNuxtModule, useLogger } from "@nuxt/kit"
import { addImports, addPlugin, addRouteMiddleware, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, useLogger } from "@nuxt/kit"
import { defu } from "defu"
import { configKey } from "./runtime/utils"

Expand All @@ -9,6 +9,7 @@ export interface ModuleOptions {
guestRedirectTo?: string
authenticatedRedirectTo?: string
baseUrl: string
basePath?: string
}

export default defineNuxtModule<ModuleOptions>({
Expand All @@ -20,7 +21,8 @@ export default defineNuxtModule<ModuleOptions>({
verifyClientOnEveryRequest: true,
guestRedirectTo: "/",
authenticatedRedirectTo: "/",
baseUrl: ""
baseUrl: "",
basePath: "/api/auth"
},
setup(userOptions, nuxt) {
const logger = useLogger(NAME)
Expand Down Expand Up @@ -50,7 +52,19 @@ export default defineNuxtModule<ModuleOptions>({
nuxt.options.alias["#auth"] = resolve("./runtime/lib/client")
// nuxt.options.build.transpile.push(resolve("./runtime/lib/client")) This doesn't look it's needed ?

// 4. Add types
// 5. Add auth config
const { dst: authConfigDst } = addTemplate({
filename: "auth.config.mjs",
write: true,
getContents: () => [
"// Generated by @auth/nuxt module",
"",
...Object.entries(options).map(([key, value]) => `export const ${key} = ${JSON.stringify(value)}`)
].join("\n")
})
nuxt.options.alias["#auth-config"] = authConfigDst

// 6. Add types
addTypeTemplate({
filename: "types/auth.d.ts",
write: true,
Expand All @@ -62,6 +76,10 @@ export default defineNuxtModule<ModuleOptions>({
` const getServerSession: typeof import('${resolve("./runtime/lib/server")}').getServerSession`,
` const NuxtAuthHandler: typeof import('${resolve("./runtime/lib/server")}').NuxtAuthHandler`,
` const getServerToken: typeof import('${resolve("./runtime/lib/server")}').getServerToken`,
"}",
"",
"declare module '#auth-config' {",
...Object.keys(options).map(key => ` const ${key}: typeof import('${authConfigDst}').${key}`),
"}"
].join("\n")
})
Expand Down
11 changes: 7 additions & 4 deletions packages/authjs-nuxt/src/runtime/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
// @todo find a way to make this reference work
import type { BuiltInProviderType, Provider, RedirectableProviderType } from "@auth/core/providers"
import type { Session } from "@auth/core/types"
import { joinURL } from "ufo"
import { makeNativeHeadersFromCookieObject } from "../utils"
import { useAuth } from "../composables/useAuth"
import type { LiteralUnion, SignInAuthorizationParams, SignInOptions, SignOutParams } from "./types"
import { navigateTo, reloadNuxtApp, useRouter } from "#imports"

import { basePath } from "#auth-config"

async function postToInternal({
url,
options,
Expand Down Expand Up @@ -73,7 +76,7 @@ export async function signIn<P extends RedirectableProviderType | undefined = un
const isSupportingReturn = isCredentials || isEmail

// TODO: Handle custom base path
freality marked this conversation as resolved.
Show resolved Hide resolved
const signInUrl = `/api/auth/${isCredentials ? "callback" : "signin"}/${providerId}`
const signInUrl = joinURL(basePath, isCredentials ? "callback" : "signin", providerId || "")
const _signInUrl = `${signInUrl}?${new URLSearchParams(authorizationParams)}`

// TODO: Handle custom base path
Expand Down Expand Up @@ -117,7 +120,7 @@ export async function signOut(options?: SignOutParams) {
status.value = "unauthenticated"
const { callbackUrl = window.location.href } = options ?? {}
// TODO: Custom base path
const data = await $fetch<{ url: string }>("/api/auth/signout", {
const data = await $fetch<{ url: string }>(joinURL(basePath, "signout"), {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Expand Down Expand Up @@ -148,7 +151,7 @@ export async function signOut(options?: SignOutParams) {
* See [OAuth Sign In](https://authjs.dev/guides/basics/pages#oauth-sign-in) for more details.
*/
export async function getProviders() {
return $fetch<Record<string, Provider>[]>("/api/auth/providers")
return $fetch<Record<string, Provider>[]>(joinURL(basePath, "providers"))
}
/**
* Verify if the user session is still valid
Expand All @@ -161,7 +164,7 @@ export async function verifyClientSession() {
if (cookies.value === null)
throw new Error("No session found")

const data = await $fetch<Session>("/api/auth/session", {
const data = await $fetch<Session>(joinURL(basePath, "session"), {
headers: makeNativeHeadersFromCookieObject(cookies.value)
})
const hasSession = data && Object.keys(data).length
Expand Down
15 changes: 14 additions & 1 deletion packages/authjs-nuxt/src/runtime/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import type { H3Event } from "h3"
import { eventHandler, getRequestHeaders, getRequestURL } from "h3"
import type { AuthConfig, Session } from "@auth/core/types"
import { getToken } from "@auth/core/jwt"
import { parseURL, resolveURL, stringifyParsedURL } from "ufo"
import { checkOrigin, getAuthJsSecret, getRequestFromEvent, getServerOrigin, makeCookiesFromCookieString } from "../utils"

import { basePath } from "#auth-config"

if (!globalThis.crypto) {
// eslint-disable-next-line no-console
console.log("Polyfilling crypto...")
Expand All @@ -18,6 +21,16 @@ if (!globalThis.crypto) {
})
}

/**
* Returns the domain part of a given URL.
* @param url string|URL - The URL to extract the domain from
* @returns The domain part of the URL
*/
function getDomain(url: string | URL): string {
const { protocol, auth, host } = parseURL(String(url))
return stringifyParsedURL({ protocol, auth, host })
}

/**
* This is the event handler for the catch-all route.
* Everything can be customized by adding a custom route that takes priority over the handler.
Expand Down Expand Up @@ -84,7 +97,7 @@ async function getServerSessionResponse(
options: AuthConfig
) {
options.trustHost ??= true
const url = new URL("/api/auth/session", getRequestURL(event))
const url = resolveURL(getDomain(getRequestURL(event)), basePath, "session")
return Auth(
new Request(url, { headers: getRequestHeaders(event) as any }),
options
Expand Down
5 changes: 4 additions & 1 deletion packages/authjs-nuxt/src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import type { Session } from "@auth/core/types"
import { joinURL } from "ufo"
import { useAuth } from "./composables/useAuth"
import { makeCookiesFromCookieString } from "./utils"
import { defineNuxtPlugin, useRequestHeaders } from "#app"

import { basePath } from "#auth-config"

export default defineNuxtPlugin(async () => {
// We try to get the session when the app SSRs. No need to repeat this on the client.
if (import.meta.server) {
const { updateSession, removeSession, cookies } = useAuth()
const headers = useRequestHeaders() as any
const data = await $fetch<Session>("/api/auth/session", {
const data = await $fetch<Session>(joinURL(basePath, "session"), {
headers
})
const hasSession = data && Object.keys(data).length
Expand Down
46 changes: 46 additions & 0 deletions test/custom-base-path.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { fileURLToPath } from "node:url"
import { describe, expect, it } from "vitest"
import { $fetch, setup } from "@nuxt/test-utils"
import { createPage } from "@nuxt/test-utils/e2e"

describe("custom base path test", async () => {
await setup({
rootDir: fileURLToPath(new URL("./fixtures/custom-base-path", import.meta.url))
})

it("displays homepage", async () => {
const html = await $fetch("/")
expect(html).toContain("Sign In")
})

it("displays signin page", async () => {
const page = await $fetch("/custom/auth/signin")
expect(page).toContain("Username")
expect(page).toContain("Password")
})

it("fetches auth providers", async () => {
const json = await $fetch("/custom/auth/providers")
expect(json).toMatchObject(expect.objectContaining({
credentials: expect.objectContaining({
id: "credentials",
name: "Credentials",
type: "credentials",
signinUrl: expect.stringMatching(/\/custom\/auth\/signin\/credentials$/),
callbackUrl: expect.stringMatching(/\/custom\/auth\/callback\/credentials$/)
})
}))
})

// @todo: requires install playwright-core
it.skip("can signin", async () => {
const page = await createPage("/custom/auth/signin")
expect(await page.title()).toBe("Sign In")

await page.getByLabel("Username").fill("admin")
await page.getByLabel("Password").fill("admin")
await page.locator("#submitButton").click()

expect(await page.getByText("authenticated")).toBeTruthy()
})
})
18 changes: 18 additions & 0 deletions test/fixtures/custom-base-path/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export default defineNuxtConfig({
modules: ["../../packages/authjs-nuxt/src/module.ts"],
authJs: {
baseUrl: "http://localhost:3000",
basePath: "/custom/auth",
verifyClientOnEveryRequest: true
},
experimental: {
renderJsonPayloads: true
},
runtimeConfig: {
authJs: { secret: "/OEjlRC2DK74ZEj5nl8qHNy+E6/JptnouIyHnANbBz0=" },
github: {
clientId: "",
clientSecret: ""
}
}
})
8 changes: 8 additions & 0 deletions test/fixtures/custom-base-path/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "basic-fixture",
"private": true,
"dependencies": {
"@hebilicious/authjs-nuxt": "latest",
"nuxt": "3.7.4"
}
}
21 changes: 21 additions & 0 deletions test/fixtures/custom-base-path/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<script setup lang="ts">
const { signIn, signOut, session, status, cookies } = useAuth()
</script>

<template>
<div>
<div>
<button @click="signIn(`credentials`)">
Sign In
</button>
<button @click="signOut()">
Sign Out
</button>
</div>
<div>
<pre>{{ status }}</pre>
<pre>{{ session?.user }}</pre>
<pre>{{ cookies }}</pre>
</div>
</div>
</template>
7 changes: 7 additions & 0 deletions test/fixtures/custom-base-path/pages/private.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script setup>
definePageMeta({ middleware: "auth" })
</script>

<template>
<h1>PRIVATE</h1>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import CredentialsProvider from "@auth/core/providers/credentials"
import type { AuthConfig } from "@auth/core/types"

import { NuxtAuthHandler } from "#auth"

// The #auth virtual import comes from this module. You can use it on the client
// and server side, however not every export is universal. For example do not
// use sign-in and sign-out on the server side.

const runtimeConfig = useRuntimeConfig()

// Refer to Auth.js docs for more details

export const authOptions: AuthConfig = {
secret: runtimeConfig.authJs.secret,
providers: [
CredentialsProvider({
credentials: {
username: { label: "Username", type: "text", placeholder: "admin" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
if (
credentials.username === "admin"
&& credentials.password === "admin"
)
return { id: "1", name: "admin", email: "admin", role: "test" }
return null
}
})
]
}

export default NuxtAuthHandler(authOptions, runtimeConfig)
// If you don't want to pass the full runtime config,
// you can pass something like this: { public: { authJs: { baseUrl: "" } } }