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: Add a composable to make authenticated requests #787

Closed
wants to merge 5 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const {
signUp,
signIn,
signOut,
authFetch,
} = useAuth()

// Session status, either `unauthenticated`, `loading`, `authenticated`
Expand Down Expand Up @@ -108,6 +109,9 @@ await signOut()

// Trigger a sign-out and send the user to the sign-out page afterwards
await signOut({ callbackUrl: '/signout' })

// Make an authenticated fetch that passes the token in request headers (options is a NitroFetchOptions object https://nuxt.com/docs/api/composables/use-fetch#params)
await authFetch(path, options)
```
```ts [refresh]
const {
Expand Down
6 changes: 5 additions & 1 deletion playground-local/app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { ref } from 'vue'
import { useAuth } from '#imports'

const { signIn, token, data, status, lastRefreshedAt, signOut, getSession } = useAuth()
const { signIn, token, data, status, lastRefreshedAt, signOut, getSession, authFetch } = useAuth()

const username = ref('')
const password = ref('')
Expand Down Expand Up @@ -32,6 +32,10 @@ const password = ref('')
sign out
</button>
<br>
<button data-testid="auth-fetch" @click="authFetch('/user', { method: 'get' })">
manual authenticated fetch
</button>
<br>
<button data-testid="refresh-required-false" @click="getSession({ required: false })">
refresh session (required: false)
</button>
Expand Down
9 changes: 8 additions & 1 deletion playground-local/tests/local.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ describe('Local Provider', async () => {
browser: true
})

test('load, sign in, reload, refresh, sign out', async () => {
test('load, sign in, reload, refresh, auth fetch, sign out', async () => {
const page = await createPage('/')
const [
usernameInput,
passwordInput,
submitButton,
status,
signoutButton,
authFetchButton,
refreshRequiredFalseButton,
refreshRequiredTrueButton
] = await Promise.all([
Expand All @@ -27,6 +28,7 @@ describe('Local Provider', async () => {
page.getByTestId('submit'),
page.getByTestId('status'),
page.getByTestId('signout'),
page.getByTestId('auth-fetch'),
page.getByTestId('refresh-required-false'),
page.getByTestId('refresh-required-true')
])
Expand All @@ -47,6 +49,11 @@ describe('Local Provider', async () => {
await page.reload()
await playwrightExpect(status).toHaveText(STATUS_AUTHENTICATED)

// Ensure that a manual authenticated fetch is successful while authenticated
const authFetchResponse = page.waitForResponse(/\/api\/auth\/user/)
await authFetchButton.click()
await playwrightExpect((await authFetchResponse).status()).toBe(200)

// Refresh (required: false), status should not change
await refreshRequiredFalseButton.click()
await playwrightExpect(status).toHaveText(STATUS_AUTHENTICATED)
Expand Down
26 changes: 25 additions & 1 deletion src/runtime/composables/local/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,32 @@ const signUp = async (credentials: Credentials, signInOptions?: SecondarySignInO
return signIn(credentials, signInOptions)
}

const authFetch = async (path: string, options: Parameters<typeof $fetch>[1]) => {
const nuxt = useNuxtApp()

const config = useTypedBackendConfig(useRuntimeConfig(), 'local')

const { token: tokenState, _internal } = useAuthState()
let token = tokenState.value
token ??= formatToken(_internal.rawTokenCookie.value)

if (path) {
const headers = {
...options?.headers,
...(token ? { [config.token.headerName]: token } : {}) // append auth token if it exists
}
try {
return await _fetch(nuxt, path, { ...options, headers })
} catch (err) {
console.error(`Error during authenticated fetch:, ${(err as Error).message}`)
}
}
}

interface UseAuthReturn extends CommonUseAuthReturn<typeof signIn, typeof signOut, typeof getSession, SessionData> {
signUp: typeof signUp
token: Readonly<Ref<string | null>>
authFetch: typeof authFetch
token: Readonly<Ref<string | null>>,
}
export const useAuth = (): UseAuthReturn => {
const {
Expand All @@ -156,6 +179,7 @@ export const useAuth = (): UseAuthReturn => {
signIn,
signOut,
signUp,
authFetch,
refresh: getSession
}
}