localgreenchain/lib/auth/withRole.ts
Claude 39b6081baa
Implement comprehensive authentication system (Agent 1)
Add complete user authentication with NextAuth.js supporting:
- Email/password credentials authentication
- OAuth providers (GitHub, Google) with optional configuration
- JWT-based session management with 30-day expiry
- Role-based access control (USER, GROWER, FARM_MANAGER, ADMIN)
- Permission system with granular access control
- Secure password hashing with bcrypt (12 rounds)
- Rate limiting on auth endpoints
- Password reset flow with secure tokens
- Email verification system

Files added:
- lib/auth/: Core auth library (types, permissions, context, hooks, middleware)
- pages/api/auth/: Auth API routes (NextAuth, register, forgot-password, verify-email)
- pages/auth/: Auth pages (signin, signup, forgot-password, reset-password, verify-email)
- components/auth/: Reusable auth components (LoginForm, RegisterForm, AuthGuard, etc.)

Updated _app.tsx to include SessionProvider for auth state management.
2025-11-23 03:52:09 +00:00

51 lines
1.4 KiB
TypeScript

import { NextApiHandler } from 'next'
import { UserRole } from './types'
import { withAuth, AuthenticatedHandler } from './withAuth'
/**
* Protect an API route requiring a specific role or higher
*
* @example
* // Only admins can access
* export default requireRole(handler, UserRole.ADMIN)
*
* // Growers and above can access
* export default requireRole(handler, UserRole.GROWER)
*/
export function requireRole(
handler: AuthenticatedHandler,
role: UserRole
): NextApiHandler {
return withAuth(handler, { requiredRole: role })
}
/**
* Protect an API route requiring admin role
*/
export function requireAdmin(handler: AuthenticatedHandler): NextApiHandler {
return requireRole(handler, UserRole.ADMIN)
}
/**
* Protect an API route requiring farm manager role or higher
*/
export function requireFarmManager(handler: AuthenticatedHandler): NextApiHandler {
return requireRole(handler, UserRole.FARM_MANAGER)
}
/**
* Protect an API route requiring grower role or higher
*/
export function requireGrower(handler: AuthenticatedHandler): NextApiHandler {
return requireRole(handler, UserRole.GROWER)
}
/**
* Protect an API route requiring any authenticated user
*/
export function requireUser(handler: AuthenticatedHandler): NextApiHandler {
return withAuth(handler)
}
// Re-export for convenience
export { withAuth, withPermission, withAnyPermission, withAllPermissions } from './withAuth'