atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
974 stars 91 forks source link

Add example for redirecting back to the "referer" page #152

Open ipanamski opened 2 months ago

ipanamski commented 2 months ago

I'm trying to make the plugin redirect to the page from which the user navigated to /auth/github. I can't get the ''Referer" header, since I can't access the event object outside of onSuccess. What is the recommended method and can we add it to the documentation?

// Code from README.md example
export default oauthGitHubEventHandler({
  config: {
    emailRequired: true
  },
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, {
      user: {
        githubId: user.id
      }
    })
    return sendRedirect(event, '/') // Redirect back to the referrer
  },
  onError(event, error) {
    console.error('GitHub OAuth error:', error)
    return sendRedirect(event, '/') // Redirect back to the referrer
  },
})
Barbapapazes commented 2 months ago

Hey,

This is called intended redirect (I'm working on a module) but you have to store the current path in a cookie when your Nuxt Middleware detect that the user should be logged in.

Then, in the onSuccess, you just have to get the cooke value and to redirect to it or the default value if it does not exists.

ipanamski commented 2 months ago

How can I implement this currently as there is no access to the current route outside of onSuccess? I don't want to store the cookie on 10 different places for each scenario where the user logs in.

Can't we add a beforeRequest method that exposes the h3 event, to the event handler interface, so we can set a cookie there?

Barbapapazes commented 2 months ago

In your Nuxt application (./app), you should have a middleware named auth or similar that restrict access to some parts of your application. Within the middleware, you use the composable useCookie, https://nuxt.com/docs/api/composables/use-cookie to write a cookie with the route that the user want to access using from.

Then, in the Nitro part (server), you can read this cookie and redirect the Nuxt app to this page.

ipanamski commented 2 months ago

What about the case when a user just clicks a login button in the toolbar from some of the pages (which is a direct link to /auth/github)? I would need to set a cookie on every page the user visits. I'm talking about the scenario when the user logs in willingly, without being forced into a login page.

Barbapapazes commented 2 months ago

You can intercept the click, set the cookie and then redirect using navigateTo.