Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
37 replies
MartinB

Having role on session, is this security issue and/or is there better way?

Hey quick question on t3 (more security and sessions) if i have this role property on the user and want to check it, everytime a call is made. Is it find to store it on the ctx.session.user object or is there a better way?

This role will obviously determine what privileges the user has and whether certain checks needs to be skip in case of the user is an admin etc.

Basically what i want to achieve is that when an admin checks a partners org it should skip the checkUserOwnsOrganization check

Code:

schema.prisma:
model User {
  id                 String         @id @default(cuid())
  name               String?
  email              String?        @unique
  emailVerified      DateTime?
  image              String?
  role               Role           @default(USER)
  accounts           Account[]
  sessions           Session[]
  ethWallets         EthWallet[]
  organizations      Organization[]
  ownedOrganizations Organization[] @relation("OrganizationOwner")
}

enum Role {
  USER
  ADMIN
  PARTNER
}


File: [...nextauth].ts
  callbacks: {
    session({ session, user }) {
      if (session.user) {
        session.user.id = user.id;
        session.user.role = user.role;
      }
      return session;
    },
  },


router > organization.ts
  getById: protectedProcedure
    .input(z.string())
    .query(async ({ ctx, input }) => {
      console.log('=====================================')
      console.log('test', ctx.session.user.role)

      await checkUserOwnsOrganization({ id: input, prisma: ctx.prisma, userId: ctx.session.user.id })

      const organization = await ctx.prisma.organization.findUnique({
        where: { id: input },
      });

      return organization;
    }),
Was this page helpful?