当我的用户表包含名字和姓氏时,如何使用 nextauth 处理身份验证

问题描述 投票:0回答:1

早上好,

我是 NextJs 的新手,我正在向 Google 提供商进行身份验证,问题是它只返回我的名字,我试图确保我可以将它分开,以便我的名字和姓氏在我的数据库中正确填写

我向您提供我目前拥有的代码

我的棱镜模式:

// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  firstname     String?
  lastname      String?
  email         String?   @unique
  password      String?
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

我的nextauth.d.ts


declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: DefaultSession["user"] & {
      /** The user's id address. */
      id?: string;
      firstname?: string;
      lastname?: string;
    };
  }

  interface User {
    firstname?: string;
    lastname?: string;
  }
}

和 [...nextauth].ts 文件

import NextAuth, { AuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/src/lib/db";

export const authOptions: AuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: env.GOOGLE_ID,
      clientSecret: env.GOOGLE_SECRET,
    }),
  ],
  callbacks: {
    session({ session, user }) {
      session.user.id = user.id;
      session.user.image = user.image;

      return session;
    },
  },
  pages: {
    signIn: "/login",
  },
};

export default NextAuth(authOptions);

希望你能帮我做这件事,提前致谢!

next.js google-oauth prisma next-auth
1个回答
0
投票

嘿,如果您想从 Google 提供商访问用户的名字和姓氏,您应该在 NextAuth 上查看以下文档。

下面是一个示例,可能有助于展示我如何完成类似的事情。

next-auth.d.ts

...

 interface Profile {
    sub?: string;
    name?: string;
    email?: string;
    image?: string;
    given_name?: string;
    family_name?: string;
  }

auth.ts

callbacks: {
    async jwt({
      token,
      user,
      account,
      profile,
      trigger,
      session,
    }: {
      token: JWT;
      user: User | AdapterUser;
      account: Account | null;
      profile?: Profile;
      trigger?: "signIn" | "signUp" | "update";
      isNewUser?: boolean;
      session?: Session;
    }) {
      // initial sign in
      if (user) {
        // assuming that you are only using google signin
        user.firstName = profile?.given_name;
        user.lastName = profile?.family_name;
        user.email = profile?.email; // incase you want the email also
        return user;
      }

      // This I would test, not sure if you should be returning the token or the session here. 
      // This case is for when the you are trying to fetch the session within the nextjs app. 
      // It will run through all these callbacks.
      return session;
    },
    session({ session, user }) {
      session.user.id = user.id;
      session.user.firstName = user.firstName;
      session.user.lastName = user.lastName;
      session.user.image = user.image;

      return session;
    },
 }

PSA:我会删除用户界面并使用

import { Account, Profile, Session, User } from "next-auth";
中的用户界面,因为它已经将 id、姓名、电子邮件和图像作为默认值。

© www.soinside.com 2019 - 2024. All rights reserved.