Giter VIP home page Giter VIP logo

sidebase / nuxt-auth Goto Github PK

View Code? Open in Web Editor NEW
1.1K 1.1K 125.0 2.47 MB

πŸ” Nuxt user authentication and sessions via authjs (next-auth), local and refresh providers. nuxt-auth wraps NextAuth.js to offer the reliability & convenience of a 12k star library to the nuxt 3 ecosystem with a native developer experience (DX)

Home Page: https://sidebase.io/nuxt-auth/

License: MIT License

Vue 12.22% TypeScript 87.78%
authentication local nuxt refresh session typescript users

nuxt-auth's Introduction

sidebase

CI Status GitHub stars License Follow us on Twitter Join our Discord

sidebase is a web development kit to build production ready fullstack Nuxt 3 apps quickly. sidebase relies on modern, fully-typed and best-practice technology to achieve this goal. sidebase embraces the fullstack TypeScript approach to app development: Code sharing between client and server, reduced learning curve for engineers and code-reuse across apps are things we love about this approach. That said, you can also use sidebase to build client-side only apps.

Visit sidebase.io/sidebase for quick-start, docs, guides and more!

To get started, run:

npm create sidebase@latest

And you are ready to go! The sidebase CLI will guide you through the process. Afterwards, or if you still want to know more, read the documentation to continue.

sidebase

Features

With sidebase you can build production ready, robust, maintainable, fullstack applications:

  • πŸŽ’ Fullstack: Develop frontend and backend in a single TypeScript code base
  • 🏎️ Fast to code: Database, example tests, example components and example pages are all there for you to fill out
  • πŸ› Fewer bugs: Strong data-validation using Prisma to validate all data coming into the database at runtime
  • 😊 Easy to use: Designed to follow best practices and to be ready-to-go for development, without additional dev-dependencies like docker that make it hard to get started
  • πŸš€ Ready for launch: Github Actions CI, Dockerfile, easy switch to most popular SQL-databases are all there, out of the box (get in touch if you're missing something)

To facilitate this sidebase bootstraps a nuxt 3 project that permits developing a backend and a frontend using just Nuxt 3 with overarching TypeScript support. We want to show the world how enjoyable end-to-end typescript programming can be, displacing the myth that JS/TS-backends are no good. This starter solves a lot of the "real-world" problems that occur after you start using Nuxt or any other framework: How to write backend tests? How to write component tests? How to calculate test coverage? How to integrate a database? How to build a docker image? ...?

If you have any problems with this project (e.g., setting it up on your PC) open an issue and we'll figure it out together with you πŸŽ‰

License

MIT

nuxt-auth's People

Contributors

abdallahalhaddad avatar anischihi avatar anjarupnik avatar asokr avatar atinux avatar bmhtech07 avatar bracketjohn avatar danielroe avatar danielwinkelmann avatar dependabot[bot] avatar dommi10 avatar flrnt avatar hiimphteve avatar hitochan777 avatar jericho1060 avatar joaopedroas51 avatar justserdar avatar kylesmith0905 avatar louishaftmann avatar mannil avatar mlutsiuk avatar nielsjanssen avatar pascalwengerter avatar phoenix-ru avatar timbological avatar trijpstra-fourlights avatar vanling avatar vijayabhaskar96 avatar zerekw avatar zoey-kaiser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nuxt-auth's Issues

Proposal to improve the experience of `useSession`

Describe the feature

Hi! I'm JoΓ£o Pedro. I'm one of the maintainers of the nuxt 2 auth module :)

So, currently, each time useSession is used it makes a request to the api to get the session, which means we have to await for the request and this makes the component asynchronous. And if it's used in more than one component, it will make unnecessary requests.

My proposal is to use useSession only to get the data stored with useState, and fetch the session on load the page through a plugin.

This follows the same approach of the auth module, which fetches the user on load the auth plugin.

Additional information

No response

Support redirects on `signOut`

Describe the feature

We want to support redirects after successful signout calls. E.g.:

await signOut({ callbackUrl: '/signout' })

should redirect the user to /signout after the signout happened.

Additional information

No response

Credential login: How to perform custom error handling?

Ask your question

Im using custom signin page and trying to implement or display error message on the same page.

I've tried the setting

const { data, status, signIn } = useSession({redirect: false})

and also this one,

@click="signIn('credentials', { redirect: false, email: form.email, password: form.password })"

but the return response is always

url: "http://localhost:3000/api/auth/error?error=CredentialsSignin&provider=credentials"

Anyone able to implement custom signin with error message display on the same page? Thanks in advance!

Additional information

No response

How to exclude login page when enableGlobalAppMiddlware is true

Hi , my nuxt.config.ts is :
auth: { isEnabled: true, enableGlobalAppMiddleware: true, }
I am using custom pages , so I need to implement credentials and providers on my own login page , used this config in my server/api/[...].ts :
pages: { signIn: '/login', },
Now it will be on redirect loop , how to exclude my pages/login.vue from global middleware ?
I need no auth for some pages or some layouts!

Static generated pages `nuxi generate`

Ask your question

Silly question πŸ˜“

Does nuxt-auth work nuxi generate?


Off-topic question:

I'm new to using Auth Providers
How to handle sign-up with Credentials way or redirect after login with Google Provider (for example)

Additional information

No response

Improve middleware to fully abort a navigation when the server-side auth check failed

Describe the feature

Browbeat on discord reported that components still shortly flash to the end-user even iof the auth middleware detected that the user is not logged in. It's the expectation that we should be able to navigate away on the server side, so that the content is not visible to the end-user.

  • create a reporduction
  • look into the behavior

Additional information

No response

Add a security section

Add a security section similar to nuxt-session:

  • general security advice
  • specific security problems of nuxt-auth
  • email adress to file security issues

how can we access jwt token

Ask your question

how can we access jwt token in our Nuxt composable as fetch interceptor ..
no way to access the original JWT token we received from Credentials provider ?

Additional information

No response

Custom fields for Credentials Provider

Describe the feature

I would like to suggest a custom/optional field in the user interface object to store additional data.
F.e when logging in with Strapi using Credential flow, the server will return a JWT. This token needs to stay unaltered otherwise the secret is no longer valid. I would like to propose a extra optional field for users, so that they can add in content that can be then safely stored within the encoded session jwt. By using getToken in Nitro we could then reacquire the original raw JWT token from Strapi.

Additional information

Within the [...].ts auth catch all endpoint:

`if (user) {

      const u = {
        id: user.id,
        name: user.user.username,
        // Passing the OG JWT through the email field.
        email: user.jwt
      };

      return u;
    } else {
      // If you return null then an error will be displayed advising the user to check their details.
      return null;

      // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
    }`

And then in Nitro Api I hack it out the email field currently with getToken:
`const token = await getToken({ event });

const settings = {
  method: "GET",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer " + token.email,
  },
};`

No response

See if we can support laravel sanctum

It is a request to have laravel sanctum support, so far I've encountered this 3 times:

  • 2 times on twitter people asking me
  • 1 time on nuxt-alt/auth: it's docs specifically refer to the use-case

The way to support this would be to add it upstream in NextAuth.

How to mock useSession composable

Ask your question

Hey folks,

I got a nuxt3 project and due to the fact that the nuxt-community/auth-module is not yet migrated for nuxt3, we try out your solution.
The integration itself works, but when it comes to test I got headache.
I'm not the biggest professional for testing with vitest or jest, but in the end I found no solution thats why I asked for help.

I tried several approaches to mock useSession, but non of them helped, or maybe I misconfigured them
Someone has a clue how to mock it and help me out?

Additional information

My project:

  • node 18
  • nuxt-3
  • @sidebase/nuxt-auth
  • vitest
  • pnpm

Here is my component which should just render the header bar with Buttons and logged in username

<template>
  <header>
      <div class='flex'>
        <MyLogo />
        <div v-if="!isEmptyObject(session)">
          <p class='text-white mr-3'>{{ session?.user?.name }}</p>
        </div>
        <Button v-if="!isEmptyObject(session)" @click="signOut()"  />
        <Button v-else @click="signIn('myProvider', { callbackUrl: '/dashboard' })"  />
      </div>
  </header>
</template>

<script setup lang='ts'>
const { signIn, signOut, getSession } = useSession()
const session = await getSession()
</script>

When I run the tests I got this:
ReferenceError: useSession is not defined

Here is how my TheHeader.test.ts looks like

import { render } from '@testing-library/vue'
import TheHeader from '~/components/TheHeader.vue'

describe('App', () => {
  test('should render MyLogo correctly', async () => {
    const { getByTestId } = render(TheHeader)
    expect(getByTestId('logo')).toBeInTheDocument()
  })
})

signIn credentials missing SignInOptions prop

Environment

No response

Reproduction

No response

Describe the bug

I am trying to use the module with credentials signIn method passing username and password on the frontend. Issue occurs when I am trying to pass username and password as SignInOptions.

signIn("credentials", {
    username: username.value,
    password: password.value,
})

Editor says Argument of type '{ username: string; password: string; }' is not assignable to parameter of type 'SignInOptions'. and when I checked modules source code, it is not there indeed, only callbackUrl and redirect are.
Am I missing something?

Additional context

No response

Logs

No response

DiscordProvider always leads to having to authorize the page when signing in

Environment

Reproduction

No response

Describe the bug

As the title says, the DiscordProvider always leads to having to authorize the page when signing in a user.
That's not the normal Discord login-flow, as far as I know.

Additional context

No response

Logs

No response

Is there anyway to enforce refresh session?

Ask your question

While in development (npm run dev), my useSession() works perfectly without any problem. But, while production (npm run build) and use node .output/server/index.mjs, the { data } from useSession is null.

The issue can be solved after a browser tab switch (switch to another tab, and then switch back). Guess it triggered tab-refocus (enableSessionRefreshOnWindowFocus: true). Is there anything to enforce SessionRefresh from javascript?

Additional information

No response

RFC: Strip preact

Describe the feature

After doing the size analysis of nuxt-auth in comparison to other packages we can already see that it may make sense to strip out as much (p)react as we can just for the likely size-reduction.

In addition it may make sense from a security perspective to reduce the needed dependencies of the project.

Additional information

Output of an exampe build:

❯ npm run build:playground

> @sidebase/[email protected] build:playground
> nuxi build playground

Nuxi 3.0.0                                                                                                                                                                                                                                                                                                        21:23:08
Nuxt 3.0.0 with Nitro 1.0.0                                                                                                                                                                                                                                                                                       21:23:08
β„Ή Setting up auth...                                                                                                                                                                                                                                                                                    nuxt-auth 21:23:08
β„Ή Using http://localhost:3000/api/auth as the auth API location, make sure the [...].ts file with the export default NuxtAuthHandler({ ... }) is added there. Use the nuxt.config.ts auth.origin and auth.basePath config keys to change the API location                                               nuxt-auth 21:23:08
β„Ή When building for production ensure to (1) set the application origin using auth.origin inside your nuxt.config.ts and (2) set the secret inside the NuxtAuthHandler({ secret: ... })                                                                                                                 nuxt-auth 21:23:08
βœ” Auth module setup done                                                                                                                                                                                                                                                                                nuxt-auth 21:23:08
β„Ή Client built in 855ms                                                                                                                                                                                                                                                                                           21:23:09
β„Ή Building server...                                                                                                                                                                                                                                                                                              21:23:09
βœ” Server built in 285ms                                                                                                                                                                                                                                                                                           21:23:09
βœ” Generated public playground/.output/public                                                                                                                                                                                                                                                                nitro 21:23:09
β„Ή Building Nitro Server (preset: node-server)                                                                                                                                                                                                                                                               nitro 21:23:09

 ERROR  (node:6875) [DEP0148] DeprecationWarning: Use of deprecated folder mapping "./regenerator/" in the "exports" field module resolution of the package at /Users/nils/repos/sidebase/nuxt-auth/node_modules/@babel/runtime/package.json imported from /Users/nils/repos/sidebase/nuxt-auth/playground/node_modules.
Update this package.json to use a subpath pattern like "./regenerator/*".
(Use `node --trace-deprecation ...` to show where the warning was created)

βœ” Nitro server built                                                                                                                                                                                                                                                                                        nitro 21:23:12
  β”œβ”€ playground/.output/server/package.json (1 kB) (415 B gzip)                                                                                                                                                                                                                                                   21:23:13

  β”œβ”€ playground/.output/server/index.mjs (529 B) (277 B gzip)                                                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/token.get.mjs.map (259 B) (180 B gzip)                                                                                                                                                                                                                                      21:23:13

  β”œβ”€ playground/.output/server/chunks/token.get.mjs (586 B) (294 B gzip)                                                                                                                                                                                                                                          21:23:13

  β”œβ”€ playground/.output/server/chunks/rollup/_virtual_head-static.mjs.map (111 B) (112 B gzip)                                                                                                                                                                                                                    21:23:13

  β”œβ”€ playground/.output/server/chunks/rollup/_virtual_head-static.mjs (301 B) (217 B gzip)                                                                                                                                                                                                                        21:23:13

  β”œβ”€ playground/.output/server/chunks/nitro/node-server.mjs.map (101 kB) (6.96 kB gzip)                                                                                                                                                                                                                           21:23:13

  β”œβ”€ playground/.output/server/chunks/nitro/node-server.mjs (29.4 kB) (8.7 kB gzip)                                                                                                                                                                                                                               21:23:13

  β”œβ”€ playground/.output/server/chunks/middleware.mjs.map (253 B) (186 B gzip)                                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/middleware.mjs (263 B) (201 B gzip)                                                                                                                                                                                                                                         21:23:13

  β”œβ”€ playground/.output/server/chunks/inline.mjs.map (456 B) (240 B gzip)                                                                                                                                                                                                                                         21:23:13

  β”œβ”€ playground/.output/server/chunks/inline.mjs (783 B) (383 B gzip)                                                                                                                                                                                                                                             21:23:13

  β”œβ”€ playground/.output/server/chunks/handlers/renderer.mjs.map (20 kB) (3.47 kB gzip)                                                                                                                                                                                                                            21:23:13

  β”œβ”€ playground/.output/server/chunks/handlers/renderer.mjs (16.1 kB) (4.95 kB gzip)                                                                                                                                                                                                                              21:23:13

  β”œβ”€ playground/.output/server/chunks/error-500.mjs.map (1.06 kB) (386 B gzip)                                                                                                                                                                                                                                    21:23:13

  β”œβ”€ playground/.output/server/chunks/error-500.mjs (4.26 kB) (1.82 kB gzip)                                                                                                                                                                                                                                      21:23:13

  β”œβ”€ playground/.output/server/chunks/app/styles.mjs.map (395 B) (228 B gzip)                                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/app/styles.mjs (426 B) (245 B gzip)                                                                                                                                                                                                                                         21:23:13

  β”œβ”€ playground/.output/server/chunks/app/server.mjs.map (57.9 kB) (8.56 kB gzip)                                                                                                                                                                                                                                 21:23:13

  β”œβ”€ playground/.output/server/chunks/app/server.mjs (49.6 kB) (12.2 kB gzip)                                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/app/client.manifest.mjs.map (3.3 kB) (599 B gzip)                                                                                                                                                                                                                           21:23:13

  β”œβ”€ playground/.output/server/chunks/app/client.manifest.mjs (4.54 kB) (733 B gzip)                                                                                                                                                                                                                              21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/signout.e6655c07.mjs.map (759 B) (378 B gzip)                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/signout.e6655c07.mjs (756 B) (424 B gzip)                                                                                                                                                                                                                         21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/named.47fdd10d.mjs.map (792 B) (400 B gzip)                                                                                                                                                                                                                       21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/named.47fdd10d.mjs (758 B) (436 B gzip)                                                                                                                                                                                                                           21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/inline.a6fff960.mjs.map (794 B) (400 B gzip)                                                                                                                                                                                                                      21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/inline.a6fff960.mjs (762 B) (436 B gzip)                                                                                                                                                                                                                          21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/index.763cda12.mjs.map (991 B) (467 B gzip)                                                                                                                                                                                                                       21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/index.763cda12.mjs (1.63 kB) (714 B gzip)                                                                                                                                                                                                                         21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/globally.367d7396.mjs.map (761 B) (381 B gzip)                                                                                                                                                                                                                    21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/globally.367d7396.mjs (810 B) (459 B gzip)                                                                                                                                                                                                                        21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-component.b43d0943.mjs.map (2.36 kB) (818 B gzip)                                                                                                                                                                                                           21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-component.b43d0943.mjs (2.02 kB) (895 B gzip)                                                                                                                                                                                                               21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-500.7bc6f06d.mjs.map (1.71 kB) (628 B gzip)                                                                                                                                                                                                                 21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-500.7bc6f06d.mjs (3.35 kB) (1.48 kB gzip)                                                                                                                                                                                                                   21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-500-styles.7cd9fb4f.mjs.map (390 B) (234 B gzip)                                                                                                                                                                                                            21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-500-styles.7cd9fb4f.mjs (2.22 kB) (865 B gzip)                                                                                                                                                                                                              21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-404.9c31d516.mjs.map (2.35 kB) (801 B gzip)                                                                                                                                                                                                                 21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-404.9c31d516.mjs (4.21 kB) (1.76 kB gzip)                                                                                                                                                                                                                   21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-404-styles.1cbad781.mjs.map (390 B) (236 B gzip)                                                                                                                                                                                                            21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/error-404-styles.1cbad781.mjs (3.92 kB) (1.25 kB gzip)                                                                                                                                                                                                            21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/composables.88b70936.mjs.map (316 B) (232 B gzip)                                                                                                                                                                                                                 21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/composables.88b70936.mjs (211 B) (174 B gzip)                                                                                                                                                                                                                     21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/auth.a18d99ae.mjs.map (493 B) (290 B gzip)                                                                                                                                                                                                                        21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/auth.a18d99ae.mjs (960 B) (458 B gzip)                                                                                                                                                                                                                            21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/_plugin-vue_export-helper.a1a6add7.mjs.map (479 B) (288 B gzip)                                                                                                                                                                                                   21:23:13

  β”œβ”€ playground/.output/server/chunks/app/_nuxt/_plugin-vue_export-helper.a1a6add7.mjs (254 B) (200 B gzip)                                                                                                                                                                                                       21:23:13

  β”œβ”€ playground/.output/server/chunks/_..._.mjs.map (984 B) (452 B gzip)                                                                                                                                                                                                                                          21:23:13

  └─ playground/.output/server/chunks/_..._.mjs (1.53 kB) (637 B gzip)                                                                                                                                                                                                                                            21:23:13

Ξ£ Total size: 3.93 MB (966 kB gzip)                                                                                                                                                                                                                                                                               21:23:13
βœ” You can preview this build using node playground/.output/server/index.mjs                                                                                                                                                                                                                                 nitro 21:23:13

Investigate whether we can drop the requirement of setting an `origin` for production

Describe the feature

At the moment we require an origin for production and fallback to defaults for development.

This was based on the deployment guide of next auth: https://next-auth.js.org/deployment

In a recent PR @JoaoPedroAS51 raised that we may be able to drop it: #69 (comment)

I found no convincing reasons to not drop it, however this should be investigated first as it may be security related (e.g.: for oauth callbacks).

Additional information

No response

Not working with Credentials provider

Environment

Nuxi 3.0.0-rc.11
Nuxt 3.0.0-rc.11 with Nitro 0.5.4
@sidebase/nuxt-auth 0.0.1-beta.3

Reproduction

No response

Describe the bug

Thank you for this awesome module, it is the missing piece for the Nuxt universe.

I have try to setup nuxt-auth with the credentials Provider which is the most common type when using a decoupled backend.

this is my auth config in nuxt.config.ts copied from official docs in NextAuth

NUXT_URL = http://localhost/api/auth/

  auth: {
    nextAuth: {
      url: process.env.NUXT_URL,
      options: {
        secret: process.env.NUXT_SECRET,
        providers: [
          CredentialsProvider({
            // The name to display on the sign in form (e.g. 'Sign in with...')
            name: 'Credentials',
            // The credentials is used to generate a suitable form on the sign in page.
            // You can specify whatever fields you are expecting to be submitted.
            // e.g. domain, username, password, 2FA token, etc.
            // You can pass any HTML attribute to the <input> tag through the object.
            credentials: {
              username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
              password: { label: 'Password', type: 'password' },
            },
            async authorize(credentials, req) {
              // You need to provide your own logic here that takes the credentials
              // submitted and returns either a object representing a user or value
              // that is false/null if the credentials are invalid.
              // e.g. return { id: 1, name: 'J Smith', email: '[email protected]' }
              // You can also use the `req` object to obtain additional parameters
              // (i.e., the request IP address)
              // eslint-disable-next-line no-console
              console.log(credentials)
              const user = { id: '1', name: 'J Smith', email: '[email protected]' }

              if (user) {
                // Any object returned will be saved in `user` property of the JWT
                return user
              }
              else {
                // If you return null then an error will be displayed advising the user to check their details.
                return null

                // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
              }
            },
          }),
        ],
      },
    },

Login form its showing but not matter what is the input for username and password it always show the error: "Sign in failed. Check the details you provided are correct."

the authorize function its never reach when submitting the form.

Is there anything else I am missing in order to make it work

Additional context

No response

Logs

No response

Example of using it with Laravel JWT

Describe the feature

Any idea or any example of how can be implemented with Laravel JWT? I was using Laravel JWT provider of Nuxt Auth, and was super easy to implement, but now i do not know how to implement with this awesome module.

Additional information

No response

`getSession`'s status is always unauthenticated on server-side in route middlewares

Environment

Nuxi 3.0.0-rc.13
RootDir: /Users/nook/work/tls-interim-front
Nuxt project info: (copied to clipboard)



Reproduction

No response

Describe the bug

Given I am authenticated:

When trying to guard a route, the session is always null (unauthenticated) on server side, but available on client side

definePageMeta({
  middleware: [async () => {
    const { status } = await useSession();
    console.log(status.value); // 'unauthenticated' on server, 'authenticated' on client
    if (status.value === 'authenticated') {
      return true;
    } else {
      console.log('hmm not ok');
      console.log(status.value); // 'unauthenticated' on server
    }
  }],
});

Additional context

No response

Logs

No response

import getToken within Nitro Api results in useCookies is undefined

Heads ups:
When adding getToken in the nitro server on version, results in an error.

// example file: server/api/licenses/retrieve.ts
import { getToken } from '#auth'

export default defineEventHandler(async (event) => {
    const config = useRuntimeConfig();

    const token = await getToken({ event, raw: true })

    const settings = {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + token.value
      },
    }

    const response = await $fetch(
        'http://your.domain.com/api/...';
      return response;
  });

After successfully authenticating and hitting the above endpoint the following error output is shown in the terminal when trying to retrieve the token:
[nuxt] [request error] [unhandled] [500] useCookies is not defined

"@sidebase/nuxt-auth": "^0.0.1-beta.6",
"nuxt": "3.0.0-rc.12",

Unable to authenticate on safari web browsers using custom page

Environment

  • Operating System: Darwin
  • Node Version: v19.1.0
  • Nuxt Version: 3.0.0
  • Nitro Version: 1.0.0
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: head, modules, auth, css, postcss
  • Runtime Modules: @sidebase/[email protected]
  • Build Modules: -

Reproduction

LoginComp.vue

    <div class="w-full max-w-sm p-6 m-auto mx-auto  rounded-lg shadow-md bg-gray-800 border border-slate-600">
        <h1 class="text-3xl font-semibold text-center text-white">Dollan</h1>

        <form class="mt-6">
            <div>
                <label for="username" class="block text-sm text-gray-200">AnvΓ€ndarnamn</label>
                <input type="text"
                    class="block w-full px-4 py-2 mt-2   rounded-lg bg-gray-800 text-gray-300 border-gray-600 focus:border-blue-400 focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40"
                    v-model="login.username" />
            </div>

            <div class="mt-4">
                <div class="flex items-center justify-between">
                    <label for="password" class="block text-sm  text-gray-200">LΓΆsenord</label>
                    <NuxtLink to="/user/forgotpassword" class="text-xs  text-gray-400 hover:underline">GlΓΆmt lΓΆsenordet?
                    </NuxtLink>
                </div>

                <input type="password"
                    class="block w-full px-4 py-2 mt-2  rounded-lg bg-gray-800 text-gray-300 border-gray-600 focus:border-blue-400  focus:ring-blue-300 focus:outline-none focus:ring focus:ring-opacity-40 "
                    v-model="login.password" />
            </div>

            <div class="mt-6">
                <button
                    class="w-full px-6 py-2.5 text-sm font-medium tracking-wide text-white capitalize transition-colors duration-300 transform bg-orange-500 rounded-lg hover:bg-orange-600 focus:outline-none focus:ring focus:ring-orange-300 focus:ring-opacity-50"
                    type="submit"
                    @click="signIn('credentials', { username: login.username, password: login.password, callbackUrl: '/' })">
                    Logga in
                </button>
            </div>
        </form>

        <div class="flex items-center justify-between mt-4">
            <span class="w-1/5 border-b border-gray-600 lg:w-1/5"></span>

            <a href="#" class="text-xs text-center  uppercase text-gray-400 hover:underline">
                eller logga in genom
            </a>

            <span class="w-1/5 border-b border-gray-400 lg:w-1/5"></span>
        </div>

        <div class="flex items-center mt-6 -mx-2">
            <button type="button"
                class="flex items-center justify-center w-40 px-6 py-2 text-sm font-medium text-white transition-colors duration-300 transform bg-sky-800 rounded-lg hover:bg-sky-700 focus:bg-blue-400 focus:outline-none mx-2"
                @click="signOut()">
                <svg fill="#ffff" width="30" height="30" x="0px" y="0px" viewBox="0 0 64 64"
                    style="enable-background:new 0 0 64 64;">
                    <g>
                        <path
                            d="M31.9,0.9C15.7,0.9,2.1,13.5,1,29.5l16.6,6.9c1.4-1,3.1-1.4,4.9-1.4c0.1,0,0.4,0,0.4,0l7.3-10.9c0-0.1,0-0.1,0-0.1
		c0-6.5,5.2-11.7,11.7-11.7S53.7,17.5,53.7,24S48.5,35.7,42,35.7c-0.1,0-0.1,0-0.3,0l-10.6,7.6c0,0.1,0,0.3,0,0.4
		c0,4.8-3.9,8.9-8.9,8.9c-4.2,0-7.9-3.1-8.6-7L2,40.5c3.7,13,15.8,22.7,29.9,22.7C49,63.1,63,49.2,63,32S49,0.9,31.9,0.9z" />
                        <path d="M20.4,48.1l-3.8-1.5c0.7,1.4,1.8,2.7,3.4,3.2c3.2,1.4,7.2-0.1,8.6-3.5c0.7-1.7,0.7-3.4,0-5.1s-2-3-3.5-3.7
		c-1.6-0.7-3.2-0.6-4.8-0.1l3.9,1.7c2.4,1.1,3.7,3.9,2.7,6.3C25.8,47.9,23,49,20.4,48.1z" />
                        <path d="M50,24c0-4.2-3.5-7.9-7.9-7.9c-4.2,0-7.9,3.5-7.9,7.9s3.7,7.9,7.9,7.9S50,28.3,50,24z M36.4,24c0-3.2,2.7-5.8,5.8-5.8
		c3.2,0,5.8,2.7,5.8,5.8c0,3.2-2.7,5.8-5.8,5.8C39,29.9,36.4,27.2,36.4,24z" />
                    </g>
                </svg>

                <span class="hidden mx-2 sm:inline">Steam</span>
            </button>
            <button type="button"
                class="flex items-center justify-center w-40 px-6 py-2 text-sm font-medium text-white transition-colors duration-300 transform bg-blue-400 rounded-lg hover:bg-blue-300 focus:bg-blue-400 focus:outline-none mx-2"
                @click="signIn('discord')">
                <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-discord"
                    viewBox="0 0 16 16">
                    <path
                        d="M13.545 2.907a13.227 13.227 0 0 0-3.257-1.011.05.05 0 0 0-.052.025c-.141.25-.297.577-.406.833a12.19 12.19 0 0 0-3.658 0 8.258 8.258 0 0 0-.412-.833.051.051 0 0 0-.052-.025c-1.125.194-2.22.534-3.257 1.011a.041.041 0 0 0-.021.018C.356 6.024-.213 9.047.066 12.032c.001.014.01.028.021.037a13.276 13.276 0 0 0 3.995 2.02.05.05 0 0 0 .056-.019c.308-.42.582-.863.818-1.329a.05.05 0 0 0-.01-.059.051.051 0 0 0-.018-.011 8.875 8.875 0 0 1-1.248-.595.05.05 0 0 1-.02-.066.051.051 0 0 1 .015-.019c.084-.063.168-.129.248-.195a.05.05 0 0 1 .051-.007c2.619 1.196 5.454 1.196 8.041 0a.052.052 0 0 1 .053.007c.08.066.164.132.248.195a.051.051 0 0 1-.004.085 8.254 8.254 0 0 1-1.249.594.05.05 0 0 0-.03.03.052.052 0 0 0 .003.041c.24.465.515.909.817 1.329a.05.05 0 0 0 .056.019 13.235 13.235 0 0 0 4.001-2.02.049.049 0 0 0 .021-.037c.334-3.451-.559-6.449-2.366-9.106a.034.034 0 0 0-.02-.019Zm-8.198 7.307c-.789 0-1.438-.724-1.438-1.612 0-.889.637-1.613 1.438-1.613.807 0 1.45.73 1.438 1.613 0 .888-.637 1.612-1.438 1.612Zm5.316 0c-.788 0-1.438-.724-1.438-1.612 0-.889.637-1.613 1.438-1.613.807 0 1.451.73 1.438 1.613 0 .888-.631 1.612-1.438 1.612Z" />
                </svg>

                <span class="hidden mx-2 sm:inline">Discord</span>
            </button>
        </div>


        <p class="mt-8 text-xs font-light text-center text-gray-400"> Har du inget konto? <NuxtLink to="/user/register"
                class="font-medium text-gray-200 hover:underline ">Skapa ett</NuxtLink>
        </p>
    </div>
    <pre v-if="data" class="mt-8 text-xs font-light text-center text-gray-400"><span>Data:</span> {{ data }}</pre>
</template>

<script setup>
const { signOut, signIn, data } = useSession()
let login = {
    username: '',
    password: '',
}
</script>

Credentialsprovider

CredentialsProvider.default({
      // The name to display on the sign in form (e.g. "Sign in with...")
      name: "Credentials",
      // `credentials` is used to generate a form on the sign in page.
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      // You can pass any HTML attribute to the <input> tag through the object.
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials, req) {
        // Add logic here to look up the user from the credentials supplied
        const user = { id: "1", name: "J Smith", email: "[email protected]" }
  
        if (user) {
          // Any object returned will be saved in `user` property of the JWT
          return user
        } else {
          // If you return null then an error will be displayed advising the user to check their details.
          return null
  
          // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
        }
      }
    })

Describe the bug

For me this happens when I use a custom signing page using and then use the signIn function provided by useSession()
when using the standard one made by the module it works as intended, this issue is really strange and something I do not know the cause of. Chromium does not complain about anything but safari complains about "Failed to load resource: you do not have access" and "Unhandled Promise Rejection: FetchError: Load failed ()"

Additional context

No response

Logs

No response

bridge: nuxt.options.runtimeConfig is undefined

Environment


  • Operating System: Linux
  • Node Version: v16.17.0
  • Nuxt Version: 2.16.0-27720022.54e852f
  • Nitro Version: 0.6.1
  • Package Manager: [email protected]
  • Builder: webpack
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

Install nuxt-auth in a project with nuxt bridge, but without runtimeConfig section in nuxt.config.js

Describe the bug

Nuxt 2 bridge does not create empty runtimeConfig if none was specified in nuxt.config.js. It leads to fail during module installing process

Additional context

No response

Logs

No response

First Release

What do we still want to do before this library get's an alpha release?

  • general
    • create a logo
    • test whether the following works, if it doesn't work potentially support it:
      • api
      • client api
      • middleware server
      • middleware client
      • server side access of auth data
      • optional: auth wrapper component -> out of scope
    • expand docs
      • client api
      • rest api
  • composable
    • resolve remaining todos
    • move the composable into the module
    • optional: type _fetch better to get better typing for all methods
  • next-auth backend proxy
    • resolve remaining todos
    • remove all console logs
    • cleanup proxy
  • polishing & config
    • rename to @sidebase/nuxt-auth
    • pass through config
      • pass nextAuth config through nuxt.config to module to api endpoint, support complex provider objects
      • see nuxt/nuxt#15237 by @danielroe
      • NEXTAUTH_SECRET support
      • optional: NEXTAUTH_URL support
      • optional: all config
    • remove test oauth credentials + delete oauth app
    • deploy a test-web-app at https://nuxt-user-example.sidebase.io/, @zoey-kaiser
  • publishing
    • test publish alpha
    • package + publish
    • test it out in vanilla nuxt3 app
      • does it work?
      • does typing work?
    • do a beta testing release & collect feedback
    • do the first full release

How to get session in [...].ts | NuxtAuthHandler get session from event

Describe the feature

How can we get a session from NuxtAuthHandler as I am able to understand how to get event as I see example

export default eventHandler(async (event) => {
  const session = await getServerSession(event)
})

it use event to get session data

Additional information

No response

503 Server Unavailable

Environment


  • Operating System: Darwin
  • Node Version: v18.12.1
  • Nuxt Version: 3.0.0
  • Nitro Version: 1.0.0
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

yarn add --dev @sidebase/nuxt-auth
yarn dev

Describe the bug

The App cannnot start with below messages.

Additional context

No response

Logs

file:///siteroot/nuxt3.merkmal/httpdocs/.nuxt/dev/index.mjs:13
import { NextAuthHandler } from 'file:///siteroot/nuxt3.merkmal/httpdocs/node_modules/next-auth/core/index.js';

SyntaxError: Named export 'NextAuthHandler' not found. The requested module 'file:///siteroot/nuxt3.merkmal/httpdocs/node_modules/next-auth/core/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'file:///siteroot/nuxt3.merkmal/httpdocs/node_modules/next-auth/core/index.js';
const { NextAuthHandler } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:123:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:189:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

Accessing the JWT to reach an external API

Describe the feature

I'm currently working with 2 providers:

  • Credentials
    • will return me a JWT with the user info
  • Google
    • The JWT callback reaches my API to create an API issued JWT to be used from the client

However, I need the JWT issued by the API to be able to do the requests, how can I achieve this ? The NextAuth issues/conversation say the only way to achieve this is to attach the token to the user session on the jwt creation

Additional information

No response

Add nuxt-auth to modules.nuxt.org

Open a PR in the nuxt modules repo to add nuxt-auth to the officially available modules.

See past nuxt-session PR in same repo for procedure.

If applicable: Pre-coordinate some things like naming & presentation with the nuxt team / do it in the PR with @Atinux and co

Check whether nitro virtual code needs OS-independent newlines

Describe the feature

We use os-dependent newlines (\n) in two places in our module.ts:

${providerImports.join('\n')}

].join('\n')

We should figure out whether that's ok (e.g., whether nitro compiles it correctly) or whether we need to do a checking step to determine whether we need to use \n (*nix based) or \n\r (windows).

Additional information

No response

Extending a bit more documentation about provider flow

Describe the feature

Default session middleware provider will return you to /api/auth/signin while in my case I want this to be to the custom sign in page at /auth/signin in the pages folder.

When trying to create custom login/signin pages, I came to the following settings that enable the module to redirect to the proper custom route.

My suggestion is to add these parameters to the current proper documentation.

// ./server/api/auth/[...].ts 
// Custom redirect paths when using custom sign in pages.
{
...
  pages: {
    signIn: '/auth/signin',
  },
...
}

This would be interesting too.
A better commented object that represents the most commonly used args

signIn("Credentials", { redirect: false, ...})

Additional information

No response

how to custom session field and user field? (CredentialsProvider) [ts language]

Describe the feature

Hi, i'm read doc & try set custom session field and user field

i want set some field in user

{
  accessToken: 'dddddddLZ_pCi1bLqdac3sdfdsfdsfdsfdsf6Jxlw0VyVCzHDopjXuYAviolnA',
  accessTokenExpiresIn: 604800,
  refreshToken: '7c43400b-xxxx-xxxx-xxxx-99b0f91bd570',
  user: {
    id: '7c43400b-xxxx-xxxx-xxxx-99b0f91bd570',
    createdAt: '2021-05-19T17:24:50.579279+07:00',
    displayName: 'test',
    avatarUrl: 'https://s.gravatar.com/avatar/ac44930a62044d038e16f027629b9206?r=g&default=blank',
    locale: 'en',
    email: '[email protected]',
    isAnonymous: false,
    defaultRole: 'admin',
    metadata: { permissions: ['xx'] },
    emailVerified: true,
    phoneNumber: null,
    phoneNumberVerified: false,
    activeMfaType: null,
    roles: [ 'me', 'user' ]
  }
}

Additional information

No response

[nuxt] [request error] [unhandled] [500] nuxt instance unavailable

Environment

❯ npx nuxi info
Nuxi 3.0.0 14:43:08
14:43:08
RootDir: /Users/nils/repos/sidebase/nuxt-auth/playground 14:43:08
Nuxt project info: (copied to clipboard) 14:43:08


  • Operating System: Darwin
  • Node Version: v16.14.2
  • Nuxt Version: 3.0.0
  • Nitro Version: 1.0.0
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: modules, auth
  • Runtime Modules: ()
  • Build Modules: -

πŸ‘‰ Report an issue: https://github.com/nuxt/framework/issues/new 14:43:08

πŸ‘‰ Suggest an improvement: https://github.com/nuxt/framework/discussions/new

πŸ‘‰ Read documentation: https://v3.nuxtjs.org

Reproduction

To reproduce:

> git clone https://github.com/sidebase/nuxt-auth

> cd nuxt-auth

# Open your code editor, add `origin: 'localhost:3000'` to the `nuxt.config.ts`, add `secret: 'bla'` into the `playground/server/api/auth/[...].ts` `NuxtAuthHandler`  handler

> npm run dev:prepare && npm run build:playground && npm run start:playground

Then visit http://[::]:3000 (IPv6 writing is important here, this error seems to be related to using the incorrect origin)

Describe the bug

The following error appears:

> @sidebase/[email protected] start:playground
> node playground/.output/server/index.mjs

Listening http://[::]:3000
[nuxt] [request error] [unhandled] [500] nuxt instance unavailable
  at useNuxtApp (./playground/.output/server/chunks/app/server.mjs:157:13)  
  at useRequestEvent (./playground/.output/server/chunks/app/server.mjs:420:36)  
  at getRequestURL (./playground/.output/server/chunks/app/server.mjs:982:25)  
  at Object.onRequest (./playground/.output/server/chunks/app/server.mjs:1093:37)  
  at $fetchRaw2 (./playground/.output/server/node_modules/ofetch/dist/shared/ofetch.5cb01515.mjs:122:29)  
  at onError (./playground/.output/server/node_modules/ofetch/dist/shared/ofetch.5cb01515.mjs:102:16)  
  at ./playground/.output/server/node_modules/ofetch/dist/shared/ofetch.5cb01515.mjs:147:14

Additional context

This is likely related to use of nested composables inside an async context. See nuxt/nuxt#14269 for a long form comment by @pi0 on this.

Logs

No response

RFC: Documentation Ideas

Describe the feature

Add documentation and optionally sample code for:

Additional information

[1] attempt at strapi from discord user Hum+ (thanks πŸ™‡ )

import CredentialsProvider from "next-auth/providers/credentials";
import { NuxtAuthHandler } from "#auth";

export default NuxtAuthHandler({
  secret: process.env.NUXT_SECRET,
  providers: [
    // @ts-ignore Import is exported on .default during SSR, so we need to call it this way. May be fixed via Vite at some point
    CredentialsProvider.default({
      // The name to display on the sign in form (e.g. 'Sign in with...')
      name: "Credentials",

      // Strapi expects { identifier: 'username or email', password: 'abcde' } we can deal with this at the fetch req
      credentials: {
        username: { label: 'Username', type: 'text', placeholder: 'Test user' },
        password: { label: 'Password', type: 'password' }
      },
      async authorize(credentials: any) {

        const user = await $fetch(`${process.env.STRAPI_BASE_URL}/api/auth/local/`, {
          method: "POST",
          body: JSON.stringify({
            identifier: credentials.username,
            password: credentials.password,
          }),
        });

        if (user) {
         
          return user;
        } else {
         
          return null;

        }
      },
    }),
  ],
  session: {
    jwt: true,
  },

});

[2] passing username and password to signIn, e.g., to use on ytour own page:

await signIn('credentials', { callbackUrl: '/', username: 'jsmith', password: 'hunter2' })

[500] Cannot find module '~/nuxt-auth-app/.output/server/node_modules/next-auth/providers/github.js'

Environment

Nuxi 3.0.0-rc.12                                                          18:07:56
RootDir: ~/nuxt-auth-app                                               18:07:56
Nuxt project info: (copied to clipboard)                                  18:07:56

------------------------------
- Operating System: `Darwin`
- Node Version:     `v16.14.2`
- Nuxt Version:     `3.0.0-rc.12`
- Nitro Version:    `0.6.0`
- Package Manager:  `[email protected]`
- Builder:          `vite`
- User Config:      `modules`, `auth`
- Runtime Modules:  `@sidebase/[email protected]`
- Build Modules:    `-`
------------------------------

Reproduction

No response

Describe the bug

With 0.0.1-beta.1 I get this error when using a fresh starter, setting up the module w. github provider and then doing:

> npm run build

> npm run start

in a second terminal:

> curl localhost:3000/api/auth/session

then back in the first terminal we get:

> start
> node .output/server/index.mjs

Listening http://[::]:3000
[nuxt] [request error] [unhandled] [500] Cannot find module '/.tmp/nuxt-auth-app/.output/server/node_modules/next-auth/providers/github.js' imported from /.tmp/nuxt-auth-app/.output/server/chunks/nitro/node-server.mjs
  at new NodeError (node:internal/errors:371:5)  
  at finalizeResolution (node:internal/modules/esm/resolve:418:11)  
  at moduleResolve (node:internal/modules/esm/resolve:983:10)  
  at defaultResolve (node:internal/modules/esm/resolve:1080:11)  
  at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)  
  at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)  
  at ESMLoader.import (node:internal/modules/esm/loader:332:22)  
  at importModuleDynamically (node:internal/modules/esm/translators:106:35)  
  at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)  
  at ./.output/server/chunks/nitro/node-server.mjs:568:73

Additional context

No response

Logs

No response

How to get directus setup to work?

Ask your question

Asked by @madsh93 here #30 (comment):

Hi @BracketJohn

Would it be possible to add Directus CMS documentation as well? I am having troubles with refresh tokens.
I've made a gist on my current setup.

https://gist.github.com/madsh93/eb2e36d19af3e73bfec8251f51448bc5

I'll happily provide access to a Directus CMS to test. I'm on Sidebase Discord server if you'd like to discuss it "Mads#6530".

A remaining problem seems to be refresh tokens.

Additional information

This gist should already be helpful to get most of the way: https://gist.github.com/madsh93/eb2e36d19af3e73bfec8251f51448bc5

Add an `ignorePaths` option to the global middleware

Describe the feature

Add an ignorePaths option to the global middleware, so that pages can be excluded from the global protetction without adding:

definePageMeta({ auth: false }) 

to them.

This approach has some advantages:

  • it works if a project hast just a app.vue. Currently, in this case, the app.vue cannot be excluded as the definePageMeta macro does not work on it
  • it may offer a more intuitive way for some users to configure the excluded paths directly in the nuxt.config.ts

Additional information

Originally proposed here: #81 (comment)

Interface proposal for config:

enableGlobalAppMiddleware: boolean | {
  enabled: boolean
  ignoresPaths: string[]
}

Use nuxt nitro config to set host and port in local development

Describe the feature

Currently in dev-mode we set the origin for the user unless they set their own origin using the module config:

nuxt-auth/src/module.ts

Lines 61 to 62 in 44a159c

// TODO: see if we can figure out localhost + port dynamically from the nuxt instance
usedOrigin = 'http://localhost:3000'

This leads to problems when users have their app running during development on a non-standard port (or host) during development. It does not lead to a production problem as we enforce a manually set origin during production for security reasons.

On discord:

Let's apply the solution as discussed on discord. We should ensure a fallback to 3000 in case nothing is set:

nuxt.options.server.port || process.env.PORT || process.env.NITRO_PORT || 3000

Let's:

  • make port-detection dynamic
  • make host-detection dynamic

[1]
image

Additional information

No response

RFC: Add a reproduction-template

Describe the feature

Add a nuxt-auth reproduction template, e.g., via CodeSandbox or StackBlitz.

This could also have dual use: Act as a reproduction template and a playground where users can test out the module.

Additional information

Thanks to @JoaoPedroAS51 for the idea ❀️ πŸ’―

#auth is not available in imports

Environment

Nuxi 3.0.0-rc.13
RootDir: /Users/nook/work/tls-interim-front
Nuxt project info: (copied to clipboard)



πŸ‘‰ Report an issue: https://github.com/nuxt/framework/issues/new

πŸ‘‰ Suggest an improvement: https://github.com/nuxt/framework/discussions/new

πŸ‘‰ Read documentation: https://v3.nuxtjs.org

Reproduction

No response

Describe the bug

By following the documentation, I used the external config provider (no config in nuxt.config.ts).

However #auth doesn't exist. It is not listed in the .nuxt/tsconfig.json paths

Additional context

No response

Logs

No response

Session is not refreshed and always valid

Ask your question

I use nuxt-auth to authenticate my users agains my ID provider.
However, after a user signed in, he is always able to access the system. If I terminate his session via my ID provider or if I revoke a role which is required for the authentication, this data is not getting updated in my Nuxt application, the user is still authenticated there ...

How to work with this issue correctly?

Additional information

No response

Status should only be `loading` if the session was not fetched yet

Environment

No response

Reproduction

Use getSession.

Describe the bug

Every time we make a request to get the session, the status is changed to loading. This should not happen for two reasons:

  1. This behaviour doesn't match the status of NextAuth.js. The status is only set to loading when the session was not fetched yet.
  2. When we get the session after being authenticated, the session is already "loaded", we only want to be sure that data is up-to-date. So if we perfom a check to ensure that status is authenticated, changing it to loading would cause this check to fail.

Additional context

No response

Logs

No response

Discord `signIn` in middleware leads to `400` Bad Request

Environment

No response

Reproduction

Use https://github.com/parafeu/question-astral

Run:

npm run build

npm run preview

and visit localhost:3000 -> the error should appear in the server side console. You do not need to configure the discord provider for this, only setting secret & origin is enough

Describe the bug

Reported by @parafeu on discord here: https://discord.com/channels/1024643779711483944/1045285735575593010

Additional context

No response

Logs

No response

Login with cypress

Ask your question

I have a project with a custom OAuth provider. The login works fine. Now I want to introduce e2e tests. Unfortunately I got stuck directly with the second test step, which reads as follows:

Scenario Outline: Anonymous user starts login process
    Given Anonymous user is on the landing page
    When Anonymous user triggers the login via "<action>"
    Then the page redirects to provider login page
    And login form is visible on provider login page

    Examples:
      | action |
      | click  |
      | touch  |

When cypress executes this line (we have a custom getByTestId command to get elements)

cy.getByTestId('btn-login-header').click({force: true})

the browser calls /api/auth/providers, /api/auth/csrf and /api/auth/session

BildschirmΒ­foto 2022-12-12 um 15 18 15

But when I click the button myself in the Cypress window, I can see that /api/auth/providers, /api/auth/csrf and a POST to/api/auth/signin/providernamegets fired.

After spending almost 2 days of troubleshooting and research I am pretty clueless.

So my question is: Does anyone have experience with setting up cypress tests with nuxt-auth?

While I'm hoping for an answer, I will do some more digging here and here

Additional information

No response

Ideas to more explicit with the next-auth providers dependencies

Describe the feature

I noticed that the current recommended pattern for providers is to import from the next-auth package.

As this package is a dependency of @sidebase/nuxt-auth, and not necessarily a dependency of the nuxt application using @sidebase/nuxt-auth, it means either relying on the implicit hoisting of dependencies by a subset of package managers, or explicitly adding next-auth as a dependency in the nuxt application.

I chose to do the latter for better explicit dependency tracking and to avoid potential conflicts with pnpm.

Today, I encountered an issue due to a minor version bump of next-auth during a routine package upgrade, and noticed that in @sidebase/nuxt-auth a specific version of next-auth is pinned.

I pinned to the specific version in my project's package.json, but it got me wondering if there was a better way.

A couple options I see:

  • explicitly re-export the providers from next-auth in @sidebase/nuxt-auth, so the exact versions from next-auth that work with @sidebase/nuxt-auth can be used
  • add next-auth to peerDependencies in addition to dependencies in @sidebase/nuxt-auth, so package managers will present a warning if there's no explicit next-auth dependency in the nuxt project, or if the explicit dependency falls outside @sidebase/nuxt-auth's pinned version of next-auth

Additional information

No response

Docs custom sign in page: Note that `auth: false` needs to be set to avoid redirect loop

Describe the feature

When a user wants to create a custom sign in page while having the global auth-middleware enabled, they need to add auth: false as a definePageMeta attribute to that page.

Additional information

Another idea: allow path matching / specification that is ignored by global middleware.

related discord thread of affected user: https://discord.com/channels/1024643779711483944/1024705710455533598/1049160681489956874
image

Setup deployment of the docs page

Goal
In order to improve our DX, we want to publish are own extensive docs page. The docs have already been created in https://github.com/sidebase/docs and need to be transferred into the respective module repositories.
Afterwards we hope to host each documentation with GitHub Pages, allowing them to be redeployed after every merge to the main branch.

In order to do this we first need to check how we can correctly assign subdomains to a specific github page. In this case we want to use the subdomain https://nuxt-auth.sidebase.io to publish our docs.

As far as I see, we just need to add a CNAME record for all subdomains of sidebase.io to point to the GitHub servers. Once done, we can verify the subdomain through the GitHub verification process to provide proof of ownership.

Links
https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages
https://sean-coughlin.medium.com/how-to-host-a-site-with-a-subdomain-on-github-pages-33202341f711

Tasks

  • Finish documentation (@zoey-kaiser for finishing, @BracketJohn for review)
  • Setup CNAME record for the domain (@IronicUsername)
  • Add documentation folder to nuxt-auth repo (@zoey-kaiser)
  • Setup Github Actions to rebuild docs so we do not need to do it manually (optional, depending on how much extra work it presents, @IronicUsername)

Infer correct data and authenticated types

Environment

No response

Reproduction

No response

Describe the bug

In some recent release the type information for data and status was lost. We should restore it.

Additional context

No response

Logs

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.