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

ac1kyiln  于 2023-03-29  发布在  Git
关注(0)|答案(1)|浏览(167)

1.问题总结

我目前正在使用Next.js和Typescript构建一个全栈网站,当用户通过Github OAuth登录时,我坚持将Github用户名存储在数据库中。
我应该存储其他东西,比如ID吗?但是,我希望我的网站能够“domain.com/[github用户名]”?
我尝试使用Github用户名作为主键,将用户数据存储在数据库(mongodb)中。
在[... nextauth]. ts中的登录回调期间,我将当前用户ID添加到数据库。
Here is my [... 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函数中。然而,我相应地声明了变量,并且User在其他任何地方都没有该属性。

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.代码深度挖掘

在这一点上,我只能得到userid,这是一个数字,也许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;

            }
46scxncf

46scxncf1#

我一直在寻找完全相同的方法,并通过覆盖GitHub OAuth提供程序的默认profile回调来返回额外的profile properties来实现它。
我使用了这个解决方案,它也返回登录名:

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,
        };
      },
    }),

相关问题