NextReady

Admin Dashboard

NextReady includes a powerful admin dashboard that allows you to manage your application, monitor user activity, and handle administrative tasks. This guide will walk you through setting up and using the admin dashboard.

Key Features

  • Secure admin authentication
  • User management
  • Contact message management
  • Blog post administration
  • Organization oversight
  • Payment and subscription monitoring

Setup and Configuration

Environment Variables

The admin dashboard requires setting up environment variables for authentication. Add the following to your .env.local file:

# Admin authentication
ADMIN_EMAIL=your-admin-email@example.com
ADMIN_PASSWORD=your-secure-password

Security Note: Use a strong, unique password and consider implementing additional security measures for production environments.

Accessing the Admin Dashboard

The admin dashboard is accessible at /admin-login. After successful authentication, you will be redirected to the dashboard.

Authentication Flow

The admin authentication uses a simple email/password system with secure cookie-based sessions. Here's how it works:

  1. Admin enters credentials on the login page
  2. Credentials are verified against environment variables
  3. Upon successful authentication, a secure HTTP-only cookie is set
  4. This cookie is used to maintain the admin session

Authentication Code Example

The admin authentication is handled by a dedicated API route:

// src/app/api/admin-auth/route.ts
import { NextResponse } from 'next/server'

export async function POST(request: Request) {
  try {
    // Get credentials from request
    const { email, password } = await request.json()

    // Verify against environment variables
    const adminEmail = process.env.ADMIN_EMAIL
    const adminPassword = process.env.ADMIN_PASSWORD

    if (email !== adminEmail || password !== adminPassword) {
      return NextResponse.json(
        { error: 'Invalid credentials' },
        { status: 401 }
      )
    }

    // Create response with authentication cookie
    const response = NextResponse.json({ 
      success: true,
      message: 'Authentication successful' 
    })

    // Set secure cookie
    response.cookies.set({
      name: 'admin-auth',
      value: 'authenticated',
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 60 * 60 * 24, // 1 day
      path: '/',
      sameSite: 'lax',
    })
    
    return response
  } catch (error) {
    return NextResponse.json(
      { error: 'Server error' },
      { status: 500 }
    )
  }
}

Protecting Admin Routes

To protect admin routes and ensure only authenticated admins can access them, you can implement middleware to check for the admin authentication cookie.

Middleware Implementation

Create or update your middleware file to include admin route protection:

// src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // Check if the path starts with /admin (excluding /admin-login)
  if (
    request.nextUrl.pathname.startsWith('/admin') && 
    !request.nextUrl.pathname.startsWith('/admin-login')
  ) {
    // Check for admin authentication cookie
    const adminAuth = request.cookies.get('admin-auth')
    
    if (!adminAuth || adminAuth.value !== 'authenticated') {
      // Redirect to admin login if not authenticated
      return NextResponse.redirect(
        new URL('/admin-login', request.url)
      )
    }
  }
  
  return NextResponse.next()
}

Dashboard Components

User Management

The user management section allows you to view, search, and manage user accounts. You can:

  • View user details and registration dates
  • Filter users by various criteria
  • Disable or enable user accounts
  • Reset user passwords (by generating reset links)

Contact Management

The contact management section displays all messages submitted through your contact form. You can:

  • View message details including sender information
  • Mark messages as read or replied
  • Filter messages by status
  • Delete messages when no longer needed

Blog Administration

The blog administration section allows you to manage your blog content:

  • Create, edit, and delete blog posts
  • Manage post categories and tags
  • Schedule posts for future publication
  • View post analytics and engagement metrics

Customizing the Admin Dashboard

You can customize the admin dashboard to suit your specific needs:

Adding New Sections

To add a new section to the admin dashboard:

  1. Create a new page component in the appropriate directory
  2. Add the route to the admin navigation component
  3. Implement the necessary API endpoints for data handling

Example: Adding a Settings Section

Here's how you might add a new settings section to the admin dashboard:

// 1. Create the settings page component
// src/app/admin/settings/page.tsx
'use client'

import { useState } from 'react'
import { toast } from 'react-hot-toast'

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState({
    siteName: 'NextReady',
    contactEmail: 'contact@example.com',
    // Add other settings as needed
  })

  const handleSubmit = async (e) => {
    e.preventDefault()
    // Implement API call to save settings
    toast.success('Settings saved successfully')
  }

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold mb-6">Site Settings</h1>
      
      <form onSubmit={handleSubmit}>
        {/* Form fields for settings */}
        <div className="mb-4">
          <label className="block mb-2">Site Name</label>
          <input 
            type="text"
            value={settings.siteName}
            onChange={(e) => setSettings({...settings, siteName: e.target.value})}
            className="w-full p-2 border rounded"
          />
        </div>
        
        {/* Add more fields as needed */}
        
        <button 
          type="submit" 
          className="px-4 py-2 bg-blue-600 text-white rounded"
        >
          Save Settings
        </button>
      </form>
    </div>
  )
}

Then add the new section to your admin navigation:

// Update your admin navigation component
const adminNavItems = [
  { name: 'Dashboard', href: '/admin' },
  { name: 'Users', href: '/admin/users' },
  { name: 'Messages', href: '/admin/messages' },
  { name: 'Blog', href: '/admin/blog' },
  { name: 'Settings', href: '/admin/settings' }, // New item
]

Security Best Practices

When implementing and using the admin dashboard, follow these security best practices:

  • Use strong, unique passwords for admin accounts
  • Implement rate limiting on the admin login endpoint to prevent brute force attacks
  • Consider adding two-factor authentication for additional security
  • Regularly audit admin actions with logging
  • Implement proper CSRF protection for all admin forms
  • Use HTTPS in production to encrypt all traffic
  • Regularly update dependencies to patch security vulnerabilities