Reputation: 39
The below code is code from [...nextauth].js . The Goal is to achieve is to send POST request to save data and to set a session token with the returned result when using google-authentication.
To explain the code written: I am using next-auth's credential and google providers. In the Credential provider I am making a POST request to check for the user in the database hosted on localhost:8080. The credentials passed as parameters include email and password.
For Google Provider, I have kept the code default from the doc.
callbacks are there to save tokens.
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
export default NextAuth({
// Configure one or more authentication providers
providers: [
CredentialsProvider({
async authorize(credentials){
//check if crenditials.email is present in database
const res =await fetch('http://localhost:8080/user/login?deviceToken=eEiLMMkzR1ypiCwp068z97:APA91bEiBpfwCmpZ5-ijVU4FKcl-4d0QkuWrBtXgcZRJF06MUw8GJvcBn_4ci-v1IFOD8wMF0bNqEheFq0LR0Vz5hXIktT-7sMwOfR52ULhy14NgjiUUW_0nNs5gBXAZHwhtifJluS7v', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
})
const x=await res.json();
// console.log(x);
const user={email:x.user.email,name:`${x.user.firstName} ${x.user.lastName}`};
if(res.ok && user){
console.log("logged In");
return user;
}
console.log("error1");
return null;
}}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
}
}),
],
jwt: {
encryption:true,
},
callbacks:{
async jwt(token,account)
{
console.log(account);
if(account){
token.accessToken = account.accessToken;
}
return token;
},
}
})
Upvotes: 3
Views: 2124
Reputation: 337
linkAccount event is exactly for this.
In configuration, specify it like this:
events: {
async linkAccount({ user, account, profile }) {
console.log('yo link account', user, account, profile);
}
},
Upvotes: 0
Reputation: 251
You could use the signIn
callback, however I'm not sure if this would be the purpose of this callback, it's what I'm doing at the moment.
This function gets called after the sign in process so you have access to the user's data.
async signIn({ account, profile }) {
if (account.provider === "google") {
// we can do DB queries here
console.log({
verified: profile.email_verified,
name: profile.given_name,
email: profile.email,
lastName: profile.family_name
})
return true
}
return true // do other things for other providers
}
Upvotes: 1