ghoshnirmalya / nextjs-strapi-boilerplate

:art: Boilerplate for building applications using Strapi and Next.js
https://nextjs-strapi-boilerplate.vercel.app
MIT License
313 stars 85 forks source link

Strapi internal email-password login method #39

Open lifehome opened 4 years ago

lifehome commented 4 years ago

Hi,

First of all, huge thanks to @ghoshnirmalya for the boilerplate, really appreciate it! It is however, I plan to use the default "Users" collection sits inside Strapi, with the "Email" provider.

Does anyone succeed with such a combination? I am currently trying to implement a "Credentials" provider from NextAuth, but sadly despite I stuff the user object with user id, email and even the JWT token returned from /auth/local at Strapi side, I am still confused how to use such method to call methods from Strapi, e.g. authenticated GraphQL queries.

Here is my ugly code referencing the boilerplate, still debugging, so it might not work:

Providers.Credentials({
  id: 'email',
  name: 'Email', // The name to display on the sign in form (e.g. 'Sign in with...')

  // 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.
  credentials: {
    email: { label: "Email", type: "text", placeholder: "jsmith@example.org" },
    password: {  label: "Password", type: "password" }
  },

  authorize: async (credentials) => {
    const response = await fetch(
      `${process.env.STRAPI_APIENDPOINT}/auth/local`, {
        body: JSON.stringify({
          identifier: credentials.email,
          password: credentials.password
        }),
        headers: {
          'content-type': 'application/json'
        },
        method: "POST"
      }
    )

    const data = await response.json();

    if(typeof data.user.id !== 'undefined') {
      const user = {
        id: data.user.id,
        name: data.user.username,
        email: data.user.email,
        strapi_jwt: data.jwt
      }

      return Promise.resolve(user)
    } else {
      return Promise.resolve(null)
    }
  }
})

Regards, Ivan

lenybernard commented 4 years ago

Hey @lifehome, I'd be interested by this too, did you figured out ?

ghost commented 3 years ago

@lenybernard I have managed to implement authorized graphql queries from both google oauth and email provider. You have to pass the token from the jwt callback so that it's accessible in the session callback, where you can then add it as a property to the sesssion object. You can then access the token using getSession(); To authorize the queries to strapi you pass the token in the authorization header of the request. header: { Authorization: "Bearer ${token}" }

ghoshnirmalya commented 3 years ago

@NuggetOfOdium Would you be interested in creating a pull request with the changes that you suggested?

ghost commented 3 years ago

@ghoshnirmalya Sure thing, ill look into it on the weekend