Next.js course ยท Module 7: Authentication and Authorization
User roles and permissions
In this lesson15
In previous modules, we learned the basics of authentication, connecting external providers, and managing sessions and tokens. Now we will deal with another key element of application security - the system of user roles and permissions, i.e. authorization.
While authentication answers the question "Who are you?", authorization answers the question "What can you do?". A solid system of roles and permissions is essential in any application that requires different levels of access for different users.
Basic concepts of roles and permissions
Before we move on to the implementation, let's understand the basic concepts:
- Roles - categories of users with similar access levels (e.g. user, moderator, administrator)
- Permissions - specific actions a user can perform (e.g. creating posts, editing profiles, deleting accounts)
- RBAC (Role-Based Access Control) - access control based on roles, where permissions are assigned to roles, and roles to users
- ABAC (Attribute-Based Access Control) - a more advanced model where access decisions are made based on various attributes (role, time, location, etc.)
Data model for roles and permissions
Let's start by defining an appropriate data model in Prisma:
// prisma/schema.prisma
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
password String?
accounts Account[]
sessions Session[]
role Roles @relation(fields: [roleId], references: [id])
roleId String
permissions UserPermission[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Roles {
id String @id @default(cuid())
name String @unique
description String?
users User[]
permissions RolesPermission[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Permission {
id String @id @default(cuid())
name String @unique
description String?
roles RolesPermission[]
users UserPermission[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model RolesPermission {
id String @id @default(cuid())
role Roles @relation(fields: [roleId], references: [id], onDelete: Cascade)
roleId String
permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
permissionId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([roleId, permissionId])
}
model UserPermission {
id String @id @default(cuid())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String
permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
permissionId String
granted Boolean @default(true) // true = granted, false = revoked
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([userId, permissionId])
}This model supports:
- Hierarchical roles - users are assigned roles
- Role-based permissions - roles have sets of permissions
- Individual permissions - specific users can be granted or revoked specific permissions, regardless of their role
Initialization of basic roles and permissions
Let's create a script that initializes basic roles and permissions in our application:
// prisma/seed.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
// Creating basic roles
const roles = [
{
name: 'admin',
description: 'Administrator with full system access'
},
{
name: 'moderator',
description: 'Moderator with content management access'
},
{
name: 'user',
description: 'Standard user with basic permissions'
},
{
name: 'guest',
description: 'Guest with minimal read-only access'
}
];
for (const role of roles) {
await prisma.role.upsert({
where: { name: role.name },
update: {},
create: role,
});
}
// Creating basic permissions
const permissions = [
// User permissions
{ name: 'user:read', description: 'Can view user profiles' },
{ name: 'user:create', description: 'Can create new users' },
{ name: 'user:update', description: 'Can update user data' },
{ name: 'user:delete', description: 'Can delete users' },
// Content permissions
{ name: 'content:read', description: 'Can read content' },
{ name: 'content:create', description: 'Can create new content' },
{ name: 'content:update', description: 'Can update content' },
{ name: 'content:delete', description: 'Can delete content' },
{ name: 'content:publish', description: 'Can publish content' },
// Administrative permissions
{ name: 'admin:access', description: 'Has access to the admin panel' },
{ name: 'admin:settings', description: 'Can change system settings' },
{ name: 'admin:roles', description: 'Can manage roles and permissions' },
];
for (const permission of permissions) {
await prisma.permission.upsert({
where: { name: permission.name },
update: {},
create: permission,
});
}
// Assigning permissions to roles
const rolePermissions = [
// Administrator permissions
{ roleName: 'admin', permissionNames: permissions.map(p => p.name) },
// Moderator permissions
{
roleName: 'moderator',
permissionNames: [
'user:read',
'content:read', 'content:create', 'content:update', 'content:delete', 'content:publish',
'admin:access',
]
},
// Standard user permissions
{
roleName: 'user',
permissionNames: [
'user:read',
'content:read', 'content:create', 'content:update',
]
},
// Guest permissions
{
roleName: 'guest',
permissionNames: [
'user:read',
'content:read',
]
},
];
for (const { roleName, permissionNames } of rolePermissions) {
const role = await prisma.role.findUnique({ where: { name: roleName } });
if (role) {
for (const permName of permissionNames) {
const permission = await prisma.permission.findUnique({
where: { name: permName }
});
if (permission) {
await prisma.rolePermission.upsert({
where: {
roleId_permissionId: {
roleId: role.id,
permissionId: permission.id
}
},
update: {},
create: {
roleId: role.id,
permissionId: permission.id
}
});
}
}
}
}
// Create an administrative user (if not exists)
const adminRoles = await prisma.role.findUnique({ where: { name: 'admin' } });
if (adminRoles) {
const adminEmail = 'admin@example.com';
const existingAdmin = await prisma.user.findUnique({
where: { email: adminEmail }
});
if (!existingAdmin) {
await prisma.user.create({
data: {
name: 'Administrator',
email: adminEmail,
// In production, the password should be hashed!
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // "secret"
roleId: adminRoles.id,
}
});
console.log('Administrative user created');
}
}
console.log('Roles and permissions initialization completed successfully');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});To run this script, add the following configuration to package.json:
"prisma": {
"seed": "ts-node prisma/seed.ts"
},
"scripts": {
"db:seed": "prisma db seed"
}Extending the NextAuth session type
To have access to user role information in the NextAuth session, let's extend the types:
// types/next-auth.d.ts
import { DefaultSession } from 'next-auth';
declare module 'next-auth' {
interface Session {
user: {
id: string;
role: string;
permissions: string[];
} & DefaultSession['user'];
}
interface User {
role: string;
roleId: string;
permissions: string[];
}
}
declare module 'next-auth/jwt' {
interface JWT {
userId: string;
role: string;
permissions: string[];
}
}Implementing the NextAuth configuration
Now let's modify the NextAuth configuration to include roles and permissions:
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import { authOptions } from '@/lib/auth';
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
// lib/auth.ts
import { NextAuthOptions } from 'next-auth';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from '@/lib/prisma';
import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import { compare } from 'bcrypt';
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
CredentialsProvider({
name: 'Credentials',
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null;
}
const user = await prisma.user.findUnique({
where: { email: credentials.email },
include: {
role: true,
permissions: {
include: {
permission: true,
},
},
},
});
if (!user || !user.password) {
return null;
}
const isPasswordValid = await compare(credentials.password, user.password);
if (!isPasswordValid) {
return null;
}
// Fetch the role permissions
const rolePermissions = await prisma.rolePermission.findMany({
where: { roleId: user.roleId },
include: { permission: true },
});
// Create a list of permissions (role permissions + individual permissions)
const allPermissions = new Set<string>();
// Add the role permissions
rolePermissions.forEach(rp => {
allPermissions.add(rp.permission.name);
});
// Add/remove individual user permissions
user.permissions.forEach(up => {
if (up.granted) {
allPermissions.add(up.permission.name);
} else {
allPermissions.delete(up.permission.name);
}
});
return {
id: user.id,
email: user.email,
name: user.name,
image: user.image,
role: user.role.name,
roleId: user.roleId,
permissions: Array.from(allPermissions),
};
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.userId = user.id;
token.role = user.role;
token.permissions = user.permissions;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.userId;
session.user.role = token.role;
session.user.permissions = token.permissions;
}
return session;
},
},
pages: {
signIn: '/auth/login',
error: '/auth/error',
},
session: {
strategy: 'jwt',
},
};Authorization utilities
Now let's create utilities for easily checking user roles and permissions:
// lib/auth-utils.ts
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { Session } from 'next-auth';
// Helper functions for checking roles and permissions
export function hasRoles(session: Session | null, role: string | string[]): boolean {
if (!session?.user?.role) return false;
if (Array.isArray(role)) {
return role.includes(session.user.role);
}
return session.user.role === role;
}
export function hasPermission(session: Session | null, permission: string | string[]): boolean {
if (!session?.user?.permissions) return false;
if (Array.isArray(permission)) {
return permission.some(p => session.user.permissions.includes(p));
}
return session.user.permissions.includes(permission);
}
// Server function - checks role and redirects if no access
export async function requireRoles(role: string | string[], redirectTo: string = '/auth/unauthorized') {
const session = await getServerSession(authOptions);
if (!session) {
redirect('/auth/login');
}
if (!hasRoles(session, role)) {
redirect(redirectTo);
}
return session;
}
// Server function - checks permission and redirects if no access
export async function requirePermission(permission: string | string[], redirectTo: string = '/auth/unauthorized') {
const session = await getServerSession(authOptions);
if (!session) {
redirect('/auth/login');
}
if (!hasPermission(session, permission)) {
redirect(redirectTo);
}
return session;
}Implementation of access protection components
Now let's create client components that will allow easy access control to parts of the user interface:
// components/RolesGuard.tsx
'use client';
import { useSession } from 'next-auth/react';
import { ReactNode } from 'react';
import { hasRoles } from '@/lib/auth-utils';
interface RolesGuardProps {
children: ReactNode;
role: string | string[];
fallback?: ReactNode;
}
export function RolesGuard({ children, role, fallback = null }: RolesGuardProps) {
const { data: session } = useSession();
if (!hasRoles(session, role)) {
return fallback;
}
return <>{children}</>;
}
// components/PermissionGuard.tsx
'use client';
import { useSession } from 'next-auth/react';
import { ReactNode } from 'react';
import { hasPermission } from '@/lib/auth-utils';
interface PermissionGuardProps {
children: ReactNode;
permission: string | string[];
fallback?: ReactNode;
}
export function PermissionGuard({ children, permission, fallback = null }: PermissionGuardProps) {
const { data: session } = useSession();
if (!hasPermission(session, permission)) {
return fallback;
}
return <>{children}</>;
}
// components/AdminOnly.tsx
'use client';
import { RolesGuard } from '@/components/RolesGuard';
import { ReactNode } from 'react';
export function AdminOnly({ children, fallback = null }: { children: ReactNode, fallback?: ReactNode }) {
return (
<RolesGuard role="admin" fallback={fallback}>
{children}
</RolesGuard>
);
}Implementing middleware
We can also implement middleware for access control to entire paths:
// middleware.ts
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
// Administrative paths
if (request.nextUrl.pathname.startsWith('/admin')) {
if (!token) {
return NextResponse.redirect(new URL('/auth/login?callbackUrl=/admin', request.url));
}
// Check if the user has the administrator role
if (token.role !== 'admin') {
return NextResponse.redirect(new URL('/auth/unauthorized', request.url));
}
}
// Moderator paths
if (request.nextUrl.pathname.startsWith('/moderator')) {
if (!token) {
return NextResponse.redirect(new URL('/auth/login?callbackUrl=/moderator', request.url));
}
// Check if the user has the administrator or moderator role
if (token.role !== 'admin' && token.role !== 'moderator') {
return NextResponse.redirect(new URL('/auth/unauthorized', request.url));
}
}
// Protected paths - accessible only to logged-in users
if (
request.nextUrl.pathname.startsWith('/dashboard') ||
request.nextUrl.pathname.startsWith('/profile') ||
request.nextUrl.pathname.startsWith('/settings')
) {
if (!token) {
const callbackUrl = encodeURIComponent(request.nextUrl.pathname);
return NextResponse.redirect(new URL(`/auth/login?callbackUrl=${callbackUrl}`, request.url));
}
}
// Securing API endpoints
if (request.nextUrl.pathname.startsWith('/api/protected')) {
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Additional permission checks can be added depending on the API path
if (request.nextUrl.pathname.startsWith('/api/protected/admin') && token.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
}
return NextResponse.next();
}
export const config = {
matcher: [
'/admin/:path*',
'/moderator/:path*',
'/dashboard/:path*',
'/profile/:path*',
'/settings/:path*',
'/api/protected/:path*',
],
};Examples of use in the application
1. Route protection using server functions
// app/admin/dashboard/page.tsx
import { requireRoles } from '@/lib/auth-utils';
export default async function AdminDashboardPage() {
// Redirects if the user is not an administrator
const session = await requireRoles('admin');
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-4">Administration panel</h1>
<p>Hello, {session.user.name}! You have full administrative access.</p>
{/* Content available only to administrators */}
</div>
);
}
// app/content/edit/[id]/page.tsx
import { requirePermission } from '@/lib/auth-utils';
export default async function EditContentPage({ params }: { params: Promise<{ id: string }> }) {
// Redirects if the user does not have permission to edit content
const session = await requirePermission('content:update');
// Fetch content for editing
const content = await fetchContent((await params).id);
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-4">Content editing</h1>
{/* Edit form */}
</div>
);
}2. UI component protection
// components/NavBar.tsx
'use client';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import { AdminOnly } from '@/components/AdminOnly';
import { RolesGuard } from '@/components/RolesGuard';
import { PermissionGuard } from '@/components/PermissionGuard';
export function NavBar() {
const { data: session } = useSession();
return (
<nav className="bg-white shadow-sm">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
<div className="flex space-x-8 items-center">
<Link href="/" className="font-bold text-xl">MyApplication</Link>
<Link href="/dashboard">Dashboard</Link>
{/* Link visible only to moderators and administrators */}
<RolesGuard role={['admin', 'moderator']}>
<Link href="/moderator/content" className="text-blue-600">
Content management
</Link>
</RolesGuard>
{/* Link only for administrators */}
<AdminOnly>
<Link href="/admin/dashboard" className="text-red-600">
Administrator panel
</Link>
</AdminOnly>
{/* Link for users with content creation permission */}
<PermissionGuard permission="content:create">
<Link href="/content/new" className="text-green-600">
Create content
</Link>
</PermissionGuard>
</div>
<div className="flex items-center">
{session ? (
<div className="flex items-center space-x-4">
<span>{session.user.name}</span>
<span className="px-2 py-1 bg-gray-200 rounded-full text-xs">
{session.user.role}
</span>
</div>
) : (
<Link href="/auth/login">Log in</Link>
)}
</div>
</div>
</div>
</nav>
);
}3. Implementing Route Handlers with authorization
// app/api/protected/users/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { hasPermission } from '@/lib/auth-utils';
import { prisma } from '@/lib/prisma';
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check if the user has permission to read users
if (!hasPermission(session, 'user:read')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
try {
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
image: true,
role: {
select: {
name: true,
},
},
createdAt: true,
}
});
return NextResponse.json(users);
} catch (error) {
console.error('Error fetching users:', error);
return NextResponse.json(
{ error: 'Failed to fetch users' },
{ status: 500 }
);
}
}
// app/api/protected/users/[id]/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { hasPermission } from '@/lib/auth-utils';
import { prisma } from '@/lib/prisma';
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Check if the user has permission to delete users
if (!hasPermission(session, 'user:delete')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
try {
// Check that the user is not trying to delete themselves
if ((await params).id === session.user.id) {
return NextResponse.json(
{ error: 'Cannot delete your own account' },
{ status: 400 }
);
}
// Check that the user is not trying to delete an administrator (if they themselves are not an administrator)
if (session.user.role !== 'admin') {
const userToDelete = await prisma.user.findUnique({
where: { id: (await params).id },
include: { role: true },
});
if (userToDelete?.role.name === 'admin') {
return NextResponse.json(
{ error: 'Cannot delete admin accounts' },
{ status: 403 }
);
}
}
// Delete user
await prisma.user.delete({
where: { id: (await params).id },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting user:', error);
return NextResponse.json(
{ error: 'Failed to delete user' },
{ status: 500 }
);
}
}Admin panel for managing roles and permissions
Fragment of the admin panel implementation for managing roles and permissions:
// app/admin/roles/page.tsx
import { requirePermission } from '@/lib/auth-utils';
import Link from 'next/link';
import { prisma } from '@/lib/prisma';
export default async function RolessAdminPage() {
await requirePermission('admin:roles');
const roles = await prisma.role.findMany({
include: {
_count: {
select: {
users: true,
permissions: true,
},
},
},
orderBy: {
name: 'asc',
},
});
return (
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold">Role management</h1>
<Link
href="/admin/roles/new"
className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
>
Add new role
</Link>
</div>
<div className="bg-white shadow overflow-hidden rounded-md">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Description
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Users
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Permissions
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{roles.map((role) => (
<tr key={role.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{role.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{role.description}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{role._count.users}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{role._count.permissions}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
<Link
href={`/admin/roles/${role.id}`}
className="text-blue-600 hover:text-blue-900 mr-4"
>
Edit
</Link>
<Link
href={`/admin/roles/${role.id}/permissions`}
className="text-green-600 hover:text-green-900"
>
Permissions
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}Debugging and permission diagnostics
It can be useful to create a diagnostic component that shows the current roles and permissions of the logged-in user:
// components/PermissionDebugger.tsx
'use client';
import { useSession } from 'next-auth/react';
import { useState } from 'react';
export function PermissionDebugger() {
const { data: session, status } = useSession();
const [showDetails, setShowDetails] = useState(false);
if (status !== 'authenticated') {
return null;
}
return (
<div className="fixed bottom-4 right-4 p-4 bg-white border border-gray-300 rounded-lg shadow-lg max-w-md z-50">
<div className="flex justify-between items-center mb-2">
<h3 className="font-bold text-lg">Permission diagnostics</h3>
<button
onClick={() => setShowDetails(!showDetails)}
className="text-blue-600 hover:text-blue-800"
>
{showDetails ? 'Hide details' : 'Show details'}
</button>
</div>
<div className="mb-2">
<span className="font-semibold">User:</span> {session.user.name}
</div>
<div className="mb-2">
<span className="font-semibold">Role:</span>
<span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-xs">
{session.user.role}
</span>
</div>
{showDetails && (
<div>
<div className="font-semibold mb-1">Permissions:</div>
<div className="max-h-40 overflow-y-auto">
{session.user.permissions.length > 0 ? (
<ul className="list-disc pl-5 space-y-1">
{session.user.permissions.sort().map((permission) => (
<li key={permission} className="text-sm">
{permission}
</li>
))}
</ul>
) : (
<p className="text-sm text-red-600">No permissions</p>
)}
</div>
</div>
)}
</div>
);
}This component can be used during the development phase or for administrators in the production environment.
Extending RBAC with additional conditions (ABAC)
We can extend our authorization system with additional conditions, implementing elements of attribute-based access control (ABAC):
// lib/auth-conditions.ts
import { Session } from 'next-auth';
interface AccessConditions {
isOwner?: (userId: string, resourceId: string) => Promise<boolean>;
isInSameTeam?: (userId: string, resourceId: string) => Promise<boolean>;
isWithinBusinessHours?: () => boolean;
isFromAllowedIP?: (ipAddress: string) => boolean;
// More conditions can be added as needed
}
export async function checkAccessConditions(
session: Session | null,
permission: string,
resourceId: string,
conditions: AccessConditions,
ipAddress?: string
): Promise<boolean> {
// First check the basic permission
if (!session?.user?.permissions?.includes(permission)) {
return false;
}
// If it's an administrator, always allow access
if (session.user.role === 'admin') {
return true;
}
// Check additional conditions
if (conditions.isOwner && resourceId) {
const isOwner = await conditions.isOwner(session.user.id, resourceId);
if (!isOwner) {
return false;
}
}
if (conditions.isInSameTeam && resourceId) {
const isInSameTeam = await conditions.isInSameTeam(session.user.id, resourceId);
if (!isInSameTeam) {
return false;
}
}
if (conditions.isWithinBusinessHours) {
const isWithinBusinessHours = conditions.isWithinBusinessHours();
if (!isWithinBusinessHours) {
return false;
}
}
if (conditions.isFromAllowedIP && ipAddress) {
const isFromAllowedIP = conditions.isFromAllowedIP(ipAddress);
if (!isFromAllowedIP) {
return false;
}
}
// All conditions met
return true;
}
// Example condition implementations
export async function isContentOwner(userId: string, contentId: string): Promise<boolean> {
const content = await prisma.content.findUnique({
where: { id: contentId },
select: { authorId: true },
});
return content?.authorId === userId;
}
export function isWithinBusinessHours(): boolean {
const now = new Date();
const hours = now.getHours();
const day = now.getDay(); // 0 = Sunday, 6 = Saturday
// Working hours: 9:00 - 17:00, Monday to Friday
return day >= 1 && day <= 5 && hours >= 9 && hours < 17;
}Example usage:
// app/api/protected/content/[id]/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { checkAccessConditions, isContentOwner } from '@/lib/auth-conditions';
import { headers } from 'next/headers';
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getServerSession(authOptions);
const headersList = await headers();
const ipAddress = headersList.get('x-forwarded-for') || 'unknown';
// We check the 'content:update' permission and additional conditions
const hasAccess = await checkAccessConditions(
session,
'content:update',
(await params).id,
{ isOwner: isContentOwner },
ipAddress as string
);
if (!hasAccess) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Continue with content update
//
}Testing the roles and permissions system
Example unit test for permission checking function:
// __tests__/auth-utils.test.ts
import { hasPermission, hasRoles } from '@/lib/auth-utils';
describe('Auth Utils', () => {
describe('hasRoles', () => {
it('should return false for null session', () => {
expect(hasRoles(null, 'admin')).toBe(false);
});
it('should return false if user has no role', () => {
const session = { user: {} } as any;
expect(hasRoles(session, 'admin')).toBe(false);
});
it('should return true if user has the specified role', () => {
const session = { user: { role: 'admin' } } as any;
expect(hasRoles(session, 'admin')).toBe(true);
});
it('should return false if user does not have the specified role', () => {
const session = { user: { role: 'user' } } as any;
expect(hasRoles(session, 'admin')).toBe(false);
});
it('should return true if user has one of the specified roles', () => {
const session = { user: { role: 'moderator' } } as any;
expect(hasRoles(session, ['admin', 'moderator'])).toBe(true);
});
});
describe('hasPermission', () => {
it('should return false for null session', () => {
expect(hasPermission(null, 'user:read')).toBe(false);
});
it('should return false if user has no permissions', () => {
const session = { user: {} } as any;
expect(hasPermission(session, 'user:read')).toBe(false);
});
it('should return true if user has the specified permission', () => {
const session = { user: { permissions: ['user:read', 'user:create'] } } as any;
expect(hasPermission(session, 'user:read')).toBe(true);
});
it('should return false if user does not have the specified permission', () => {
const session = { user: { permissions: ['user:read'] } } as any;
expect(hasPermission(session, 'user:delete')).toBe(false);
});
it('should return true if user has one of the specified permissions', () => {
const session = { user: { permissions: ['user:read', 'content:read'] } } as any;
expect(hasPermission(session, ['user:delete', 'content:read'])).toBe(true);
});
});
});Best practices and recommendations
Minimal permissions - grant users only the necessary permissions (principle of least privilege)
Hierarchical roles - design roles hierarchically, where higher roles contain all permissions of lower roles plus additional ones
Separation of authentication and authorization - treat them as separate security layers
Detailed logs - log all attempts to access protected resources, especially unsuccessful ones
Regular audits - periodically review and verify assigned roles and permissions
Removing unused permissions - systematically remove unused roles and permissions
Emergency access - provide an emergency access mechanism for administrators in case of role system problems
Penetration testing - regularly test the system for security vulnerabilities
Summary
In this module, we implemented an advanced role and permission system for Next.js applications. We learned:
- Data model for RBAC - how to design a database structure supporting roles and permissions
- Integration with NextAuth.js - how to extend the session with role and permission information
- Authorization utilities - implementation of helper functions for checking roles and permissions
- Securing different application elements:
- Route protection using middleware
- Component protection using Guards
- Securing API endpoints
- ABAC extension - adding conditional authorization based on various attributes
A solid role and permission system is the foundation of application security, especially those with many user types and complex access requirements. Thanks to the solutions presented in this module, you can build a flexible and secure authorization system tailored to your application's needs.
In the next module, we will discuss how to create middleware for route protection, which constitutes an additional security layer in Next.js applications.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Demo: User roles and permissions (RBAC)
type Role = 'admin' | 'editor' | 'viewer' | 'moderator';
interface Permission { id: string; name: string; description: string; }
const allPermissions: Permission[] = [
{ id: 'read', name: 'Read', description: 'Viewing content' },
{ id: 'write', name: 'Write', description: 'Creating new content' },
{ id: 'edit', name: 'Edit', description: 'Modifying content' },
{ id: 'delete', name: 'Delete', description: 'Deleting content' },
{ id: 'publish', name: 'Publish', description: 'Publishing content' },
{ id: 'manage_users', name: 'Management', description: 'Managing users' },
{ id: 'settings', name: 'Settings', description: 'System settings' },
{ id: 'moderate', name: 'Moderation', description: 'Moderating comments' },
];
const rolePermissions: Record<Role, string[]> = {
admin: ['read', 'write', 'edit', 'delete', 'publish', 'manage_users', 'settings', 'moderate'],
editor: ['read', 'write', 'edit', 'publish'],
moderator: ['read', 'edit', 'moderate', 'delete'],
viewer: ['read'],
};
const roleColors: Record<Role, string> = { admin: '#ef4444', editor: '#f59e0b', moderator: '#8b5cf6', viewer: '#64748b' };
const users = [
{ id: '1', name: 'Anna Nowak', role: 'admin' as Role },
{ id: '2', name: 'Piotr Wisniewski', role: 'editor' as Role },
{ id: '3', name: 'Maria Kowalczyk', role: 'moderator' as Role },
{ id: '4', name: 'Jan Lewandowski', role: 'viewer' as Role },
];
function RBACDemo() {
const [userList, setUserList] = useState(users);
const [selected, setSelected] = useState(users[0]);
const [testResult, setTestResult] = useState('');
const hasPermission = (role: Role, permId: string) => rolePermissions[role].includes(permId);
const changeRole = (userId: string, newRole: Role) => {
setUserList(prev => prev.map(u => u.id === userId ? { ...u, role: newRole } : u));
if (selected.id === userId) setSelected(prev => ({ ...prev, role: newRole }));
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
<h1 style={{ color: '#64ffda', marginBottom: '8px' }}>RBAC - Roles and Permissions</h1>
<p style={{ color: '#8892b0', marginBottom: '24px' }}>User roles and permissions system</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<h3 style={{ color: '#64ffda' }}>Users</h3>
{userList.map(user => (
<div key={user.id} onClick={() => setSelected(user)} style={{
padding: '12px', marginBottom: '8px', borderRadius: '8px', cursor: 'pointer',
background: selected.id === user.id ? '#1a2a3e' : '#1a1a2e',
border: selected.id === user.id ? '1px solid #64ffda' : '1px solid #333',
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<strong>{user.name}</strong>
<select value={user.role} onChange={e => changeRole(user.id, e.target.value as Role)} onClick={e => e.stopPropagation()}
style={{ padding: '4px 8px', borderRadius: '4px', background: roleColors[user.role] + '30', color: roleColors[user.role], border: '1px solid ' + roleColors[user.role], fontSize: '12px' }}>
{(Object.keys(rolePermissions) as Role[]).map(r => <option key={r} value={r}>{r}</option>)}
</select>
</div>
</div>
))}
</div>
<div>
<h3 style={{ color: '#64ffda' }}>Permissions: {selected.name}</h3>
{allPermissions.map(perm => {
const allowed = hasPermission(selected.role, perm.id);
return (
<div key={perm.id} onClick={() => setTestResult(allowed ? selected.name + ' HAS: ' + perm.name : selected.name + ' DOES NOT HAVE: ' + perm.name)} style={{
padding: '10px 14px', borderRadius: '6px', cursor: 'pointer', marginBottom: '6px',
background: allowed ? '#10b98120' : '#ef444420', border: allowed ? '1px solid #10b981' : '1px solid #ef4444',
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
}}>
<div>
<strong style={{ color: allowed ? '#10b981' : '#ef4444' }}>{perm.name}</strong>
<div style={{ fontSize: '12px', color: '#8892b0' }}>{perm.description}</div>
</div>
<span>{allowed ? 'V' : 'X'}</span>
</div>
);
})}
</div>
</div>
{testResult && <div style={{ marginTop: '16px', padding: '12px', borderRadius: '8px', background: '#1a1a2e', border: '1px solid #333' }}>{testResult}</div>}
</div>
);
}
export default RBACDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Middleware in Next.js for auth can be used to:
2. RBAC (Role-Based Access Control) means:
Hands-on tasks in the game
- Code editor
Implement a dashboard with access control and user roles
- Code editor
Create middleware.ts that protects specific routes and redirects unauthorized users
- Vertical ordering
Arrange the elements in the correct order: import { notFound } โ from 'next/navigat
- Click in order
Arrange the OAuth provider configuration syntax in NextAuth
- Code editor
Create a role system (admin, user, moderator) with permissions checking and conditional rendering
Tasks after this lesson
- QuestionMiddleware in Next.js for auth can be used to:
- QuestionRBAC (Role-Based Access Control) means:
- Coding taskPractice: Dashboard with Access Control
- Coding taskPractice: Create middleware.ts protecting specific routes and
- Put in orderOrder: import { notFound } โ from 'next/navigation'
- Click in orderOAuth Provider Configuration
- Coding taskPractice: Create a role system (admin, user, moderator) with