Pass a parameter through from the signIn function on the front end to signIn callback in auth.ts. #12192
-
Hi everyone. I've spent nearly a week now trying to figure out how to leverage this awesome tool and not have to just make the auth myself. Issue here:
To clarify: the user already has a JWT session and are logged in. I now want to modify their user entry in the DB with data from the new session that comes back after attempting to 'link' another account. Any help here would be great, I've gone fish-eyed looking at it all. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey, I may found a solution for your problem. I think you should store the necessary user information directly in the jwt. I created a auth.ts file which may be working. // auth.ts
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
callbacks: {
jwt: async ({ token, user, account }) => {
if (user) {
token.userId = user.id;
token.providers = user.providers || [];
}
if (account) {
token.currentProvider = {
provider: account.provider,
providerAccountId: account.providerAccountId
};
}
return token;
},
session: async ({ session, token }) => {
if (token.userId) {
session.user.id = token.userId;
session.user.providers = token.providers;
session.currentProvider = token.currentProvider;
}
return session;
},
signIn: async ({ user, account, profile }) => {
if (!account || !user.id) return true;
try {
const existingUser = await prisma.user.findUnique({
where: { id: user.id },
include: { accounts: true }
});
if (existingUser) {
const hasProvider = existingUser.accounts.some(
acc => acc.provider === account.provider
);
if (!hasProvider) {
await prisma.account.create({
data: {
userId: existingUser.id,
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
access_token: account.access_token,
refresh_token: account.refresh_token,
expires_at: account.expires_at,
token_type: account.token_type,
scope: account.scope,
id_token: account.id_token,
session_state: account.session_state,
},
});
}
}
return true;
} catch (error) {
console.error("Fehler beim Account-Linking:", error);
return false;
}
}
}
}; In this example, I defined |
Beta Was this translation helpful? Give feedback.
Hey, I may found a solution for your problem. I think you should store the necessary user information directly in the jwt. I created a auth.ts file which may be working.