Skip to content

Instantly share code, notes, and snippets.

@olivopablo
Last active January 8, 2023 20:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save olivopablo/a497efcc75482b172d6df05a8f9f6a60 to your computer and use it in GitHub Desktop.
Save olivopablo/a497efcc75482b172d6df05a8f9f6a60 to your computer and use it in GitHub Desktop.
Strapi Next-Auth credentials provider
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
const options = {
providers: [
Providers.Credentials({
// 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.
credentials: {
email: { label: "Email", type: "text"},
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
// 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: 'jsmith@example.com' }
var fetch_url = `${process.env.NEXT_PUBLIC_API_URL}/auth/local`;
var params = {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
identifier: credentials.email,
password: credentials.password
})
}
let response = await fetch(fetch_url, params);
const data = await response.json();
const user = { ...data.user, jwt: data.jwt }
if (user) {
return user
} else {
return null
}
}
})
],
database: process.env.NEXT_PUBLIC_DATABASE_URL,
session: {
jwt: true,
},
callbacks: {
session: async (session, user) => {
session.jwt = user.jwt;
session.id = user.id;
return Promise.resolve(session);
},
jwt: async (token, user, account) => {
const isSignIn = user ? true : false;
if (isSignIn) {
if (account.type == 'credentials') {
token.jwt = user.jwt;
token.id = user.id;
} else {
var fetch_url = `${process.env.NEXT_PUBLIC_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}`;
let response = await fetch(fetch_url, params);
const data = await response.json();
token.jwt = data.jwt;
token.id = data.user.id;
}
}
return Promise.resolve(token);
},
},
};
const Auth = (req, res) =>
NextAuth(req, res, options);
export default Auth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment