如何在Github OAuth Next.js登录回调中获取GitHub用户名以添加到数据库?

3

1. 问题概述

我正在使用Next.js和TypeScript构建全栈网站,但在通过Github OAuth进行登录时,无法将Github用户名持久化存储到数据库中。

我应该存储其他内容,例如ID吗?但是,我希望我的网站能够“domain.com/[github用户名]”这样的形式呈现?

我正在尝试使用Github用户名作为主键,在数据库(mongodb)中存储用户数据。

我当前在[...nextauth].ts文件中的登录回调中向数据库添加用户ID。

以下是我的[...nextauth].ts文件:

/*
File: [..nextauth].ts
Description: This file will uses nextAuth to handle the requests, res of any OAuth...
*/
import NextAuth from "next-auth/next";
import GitHubProvider from "next-auth/providers/github"
import type {CredentialsProvider} from "next-auth/providers";
import axios from "axios"
import clientPromise from "../../../lib/mongodb";
import {useSession} from "next-auth/react";

export default NextAuth({
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_CLIENT_ID,
            clientSecret : process.env.GITHUB_CLIENT_SECRET,
            
        }),
    ],
    callbacks: {
        async jwt({ token, user, account, profile, isNewUser }) {
        // Persist the OAuth access_token to the token right after signin
        if(profile){
            token.login = profile.login
            // @ts-ignore
            user.login = profile.login
            console.log(user)
            // code up here is the user name in the jwt but user.login isn't being persisted in session nor signin
            token.id = profile.id
        }
        if (account) {
            token.accessToken = account.access_token
        }
        return token
        },
        async session({ session, token, user}) {
            // Send properties to the client, like an access_token from a provider.
            session.accessToken = token.accessToken
            session.login = token.login;
            session.id = token.id;
            // @ts-ignore
            console.log(user.name)
            return session
        },
        async signIn({ user: User, account:Account, profile: profile, email:Email }) {
            // define client
            const client = await clientPromise;

            // define database
            const db = client.db("userData");

            // define users
            const users = db.collection("users");

            console.log(User.login)


            try{
                // get user data
                const insertDocument = {"_id":User.id, "User":User}
                // @ts-ignore
                const dataUsers = await db.collection("users").insertOne(insertDocument);
                if(dataUsers){
                    console.log("Added " + String(User.id) + " to database!")
                    return true;
                }

                // if we are here user simply could not be added at all...

                return false;
            } catch (error) {
                console.log("User could not be added to database due to an error or either existing")
                return true;

            }
            return true;
        },
    },
    debug:true,
});


然而,真正的问题在于我似乎无法在给定函数的参数中找到“登录/用户名”的信息。
       async signIn({ user: User, account:Account, profile: profile, email:Email }) {

2. 描述我尝试过的内容

我发现 Github 用户名在 JWT 函数中。然而,我相应地声明了变量,但其他地方用户没有该属性。

async jwt({ token, user, account, profile, isNewUser }) {
        // Persist the OAuth access_token to the token right after signin
        if(profile){
            token.login = profile.login
            // @ts-ignore
            user.login = profile.login // code here is the user name in the jwt but user.login isn't being saved in the other functions for Arg User
            persisted in session nor signin
            token.id = profile.id
        }
        if (account) {
            token.accessToken = account.access_token
        }
        return token
        },

3. 代码深入分析

目前,我只能获取用户ID,这可能是Github用来存储数据的数字。但是,我需要 Github用户名。

try{
                // get user data
                const insertDocument = {"_id":User.id, "User":User}
                // @ts-ignore
                const dataUsers = await db.collection("users").insertOne(insertDocument);
                if(dataUsers){
                    console.log("Added " + String(User.id) + " to database!")
                    return true;
                }

                // if we are here user simply could not be added at all...

                return false;
            } catch (error) {
                console.log("User could not be added to database due to an error or either existing")
                return true;

            }
1个回答

0

我一直在寻找完全相同的解决方案,并通过覆盖GitHub OAuth提供程序的默认profile回调来返回其他配置文件属性来实现它。

我选择了这个解决方案,它还返回登录信息:

    GitHubProvider({
      clientId: env.GITHUB_CLIENT_ID,
      clientSecret: env.GITHUB_CLIENT_SECRET,
      profile(profile: GithubProfile) {
        return {
          id: profile.id.toString(),
          name: profile.name,
          userName: profile.login,
          email: profile.email,
          image: profile.avatar_url,
        };
      },
    }),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接