无法在next-auth中实现用户角色,“user”没有相同的修饰符

qgzx9mmu  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(83)

我试图在next-auth中实现用户角色。在我的数据库中,我将prisma enum UserRole设置为'ADMIN and USER`。在我的auth.ts文件中,我将角色添加到会话对象中,我收到以下错误:

All declarations of 'user' must have identical modifiers.ts(2687)
⚠ Error(TS2687)  |  

All declarations of user must have identical modifiers.
(property) Session.user?: {
    id: string;
    role: UserRole;
    email?: string | null | undefined;
    image?: string | null | undefined;
    name?: string | null | undefined;
} & {
    id: string;
    role: UserRole;
    email?: string | null | undefined;
    image?: string | null | undefined;
    name?: string | null | undefined;
}

当我在前端注销我的会话时,与用户角色的会话如预期的那样通过。我试图根据我在SO上发现的另一篇文章制作一个next-auth.d.ts文件,其中包含以下内容:

import type { UserRole } from "@prisma/client";
import type { DefaultUser } from "next-auth";
declare module "next-auth" {
  interface Session {
    user?: DefaultUser & {
      id: string;
      role: UserRole;
      name?: string | null | undefined;
      email?: string | null | undefined;
      image?: string | null | undefined;
    };
  }

  interface User extends DefaultUser {
    id: string;
    role: UserRole;
    name?: string | null | undefined;
    email?: string | null | undefined;
    image?: string | null | undefined;
  }
}

下面是我的auth.ts文件,其中发生了错误:

declare module "next-auth" {
  interface Session extends DefaultSession {
    user: {
      id: string;
      // ...other properties
      role: UserRole;
      email?: string | null | undefined;
      image?: string | null | undefined;
      name?: string | null | undefined;
    } & DefaultSession["user"];
  }

 export const authOptions: NextAuthOptions = {
  callbacks: {
    session({ session, user }) {
      if (session?.user) {
        session.user.id = user.id;

        session.user.role = user.role;
        session.user.email = user.email;
        session.user.image = user.image;
        session.user.name = user.name;
      }

      return session;
    },
  },
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    }),

我不知道我在这里错过了什么,以获得错误消失。如果我发布的代码不足以看到发生了什么,我有这里的项目:https://github.com/sjohnston82/quarter-master2
感谢您的时间和知识。

unftdfkk

unftdfkk1#

在Typescript中,已知以下修饰符:

  • public
  • protected
  • private
  • readonly

阅读更多:https://www.tutorialsteacher.com/typescript/data-modifiers
错误消息警告您有几个user的声明,并且它们的访问修饰符相互矛盾。关于访问修饰符的经验法则是,它们是您指定的,如果您没有为资源指定访问修饰符,则默认情况下class中的所有内容都是public,而默认情况下module中的所有内容都是private。除非你使用export关键字。
为了解决你的问题,你需要记住上面的内容,重新访问user的所有声明,并确保它们在访问修饰符方面是兼容的。

相关问题