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

56lgkhnf  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(146)

早上好,
我是NextJs的新手,我正在与Google提供商进行身份验证,问题是它只返回我一个名字,我试图确保我可以拆分它,以便我的名字和姓氏在我的数据库中正确填写
我提供给你的代码我目前有
我的prisma模式:

// 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])
}

字符串
我的下一个目标

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


希望你能帮我做到这一点提前感谢!

bfhwhh0e

bfhwhh0e1#

嘿,所以如果你想从谷歌提供商那里访问用户的名字和姓氏,你应该看看下面的NextAuth文档。
下面是一个例子,可能有助于展示我是如何做类似的事情的。
第一个月

...

 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,name,email和image作为默认值。

相关问题