Next-Auth Admin Permissions


I would like to implement permissions authorisation in my nextjs app, which uses nextauth and Google oAuth with mongodb for authentication. I am finding issues in assigning user roles on login, for example ‘User’ or ‘Admin’ so some routes may be protected. Below is my […next-auth].js file.

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

export default(req, res) => NextAuth(req, res, {
  session: {
    jwt: true,
  },
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_IDENTITY,
      clientSecret: process.env.GOOGLE_SECRET_KEY,
    }),
  ],
  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (account?.accessToken) {
        token.accessToken = account.accessToken
      }
      if (user?.roles) {
        token.roles = user.roles
      }
      return token
    },
    async session(session, token) {
      if(token?.accessToken) {
        session.accessToken = token.accessToken
      }
      if (token?.roles) {
        session.user.roles = token.roles
      }
      return session
    }
  }
});

Below is my mongoose model.

import mongoose from 'mongoose';

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    email: {
        type: String,
    },
    permissions: {
        type: String,
        default: 'User'
    }
});

module.exports = mongoose.models.User || mongoose.model('User', UserSchema)

Source: JavaSript – Stack Overflow

October 18, 2021
Category : News
Tags: javascript | next-auth | next.js | permissions | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.