feat: Implement user management functionality with CRUD operations; add user edit page, API routes for user actions, and enhance authentication middleware
This commit is contained in:
336
src/app/admin/users/[id]/edit/page.js
Normal file
336
src/app/admin/users/[id]/edit/page.js
Normal file
@@ -0,0 +1,336 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter, useParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/Card";
|
||||
import Button from "@/components/ui/Button";
|
||||
import { Input } from "@/components/ui/Input";
|
||||
import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
import { LoadingState } from "@/components/ui/States";
|
||||
|
||||
export default function EditUserPage() {
|
||||
const [user, setUser] = useState(null);
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
role: "user",
|
||||
is_active: true,
|
||||
password: ""
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
|
||||
const { data: session, status } = useSession();
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
|
||||
// Check if user is admin
|
||||
useEffect(() => {
|
||||
if (status === "loading") return;
|
||||
if (!session || session.user.role !== "admin") {
|
||||
router.push("/");
|
||||
return;
|
||||
}
|
||||
}, [session, status, router]);
|
||||
|
||||
// Fetch user data
|
||||
useEffect(() => {
|
||||
if (session?.user?.role === "admin" && params.id) {
|
||||
fetchUser();
|
||||
}
|
||||
}, [session, params.id]);
|
||||
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/admin/users/${params.id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
setError("User not found");
|
||||
return;
|
||||
}
|
||||
throw new Error("Failed to fetch user");
|
||||
}
|
||||
|
||||
const userData = await response.json();
|
||||
setUser(userData);
|
||||
setFormData({
|
||||
name: userData.name,
|
||||
email: userData.email,
|
||||
role: userData.role,
|
||||
is_active: userData.is_active,
|
||||
password: "" // Never populate password field
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
|
||||
try {
|
||||
// Prepare update data (exclude empty password)
|
||||
const updateData = {
|
||||
name: formData.name,
|
||||
email: formData.email,
|
||||
role: formData.role,
|
||||
is_active: formData.is_active
|
||||
};
|
||||
|
||||
// Only include password if it's provided
|
||||
if (formData.password.trim()) {
|
||||
if (formData.password.length < 6) {
|
||||
throw new Error("Password must be at least 6 characters long");
|
||||
}
|
||||
updateData.password = formData.password;
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/admin/users/${params.id}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(updateData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to update user");
|
||||
}
|
||||
|
||||
const updatedUser = await response.json();
|
||||
setUser(updatedUser);
|
||||
setSuccess("User updated successfully");
|
||||
|
||||
// Clear password field after successful update
|
||||
setFormData(prev => ({ ...prev, password: "" }));
|
||||
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (status === "loading" || !session) {
|
||||
return <LoadingState />;
|
||||
}
|
||||
|
||||
if (session.user.role !== "admin") {
|
||||
return (
|
||||
<PageContainer>
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-6">You need admin privileges to access this page.</p>
|
||||
<Link href="/">
|
||||
<Button>Go Home</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <LoadingState />;
|
||||
}
|
||||
|
||||
if (error && !user) {
|
||||
return (
|
||||
<PageContainer>
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Error</h2>
|
||||
<p className="text-gray-600 mb-6">{error}</p>
|
||||
<Link href="/admin/users">
|
||||
<Button>Back to Users</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title={`Edit User: ${user?.name}`}
|
||||
description="Update user information and permissions"
|
||||
>
|
||||
<Link href="/admin/users">
|
||||
<Button variant="outline">
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
||||
</svg>
|
||||
Back to Users
|
||||
</Button>
|
||||
</Link>
|
||||
</PageHeader>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-md">
|
||||
<p className="text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-md">
|
||||
<p className="text-green-600">{success}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="text-lg font-semibold">User Information</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Name *
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Email *
|
||||
</label>
|
||||
<Input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Role *
|
||||
</label>
|
||||
<select
|
||||
value={formData.role}
|
||||
onChange={(e) => setFormData({ ...formData, role: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
required
|
||||
>
|
||||
<option value="read_only">Read Only</option>
|
||||
<option value="user">User</option>
|
||||
<option value="project_manager">Project Manager</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
New Password
|
||||
</label>
|
||||
<Input
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
placeholder="Leave blank to keep current password"
|
||||
minLength={6}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Leave blank to keep the current password
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="is_active"
|
||||
checked={formData.is_active}
|
||||
onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
|
||||
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
|
||||
disabled={user?.id === session?.user?.id}
|
||||
/>
|
||||
<label htmlFor="is_active" className="ml-2 block text-sm text-gray-900">
|
||||
Active User
|
||||
{user?.id === session?.user?.id && (
|
||||
<span className="text-gray-500 ml-1">(Cannot deactivate your own account)</span>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-4 pt-6 border-t border-gray-200">
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? "Saving..." : "Save Changes"}
|
||||
</Button>
|
||||
<Link href="/admin/users">
|
||||
<Button type="button" variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* User Details Card */}
|
||||
{user && (
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<h3 className="text-lg font-semibold">Account Details</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Created</p>
|
||||
<p className="text-sm text-gray-900">{new Date(user.created_at).toLocaleDateString()}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Last Updated</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{user.updated_at ? new Date(user.updated_at).toLocaleDateString() : "Never"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Last Login</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{user.last_login ? new Date(user.last_login).toLocaleDateString() : "Never"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Failed Login Attempts</p>
|
||||
<p className="text-sm text-gray-900">{user.failed_login_attempts || 0}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Account Status</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{user.is_active ? "Active" : "Inactive"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Account Locked</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{user.locked_until && new Date(user.locked_until) > new Date()
|
||||
? `Until ${new Date(user.locked_until).toLocaleDateString()}`
|
||||
: "No"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
418
src/app/admin/users/page.js
Normal file
418
src/app/admin/users/page.js
Normal file
@@ -0,0 +1,418 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Card, CardHeader, CardContent } from "@/components/ui/Card";
|
||||
import Button from "@/components/ui/Button";
|
||||
import Badge from "@/components/ui/Badge";
|
||||
import { Input } from "@/components/ui/Input";
|
||||
import PageContainer from "@/components/ui/PageContainer";
|
||||
import PageHeader from "@/components/ui/PageHeader";
|
||||
import { LoadingState } from "@/components/ui/States";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
|
||||
export default function UserManagementPage() {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const { data: session, status } = useSession();
|
||||
const router = useRouter();
|
||||
|
||||
// Check if user is admin
|
||||
useEffect(() => {
|
||||
if (status === "loading") return;
|
||||
if (!session || session.user.role !== "admin") {
|
||||
router.push("/");
|
||||
return;
|
||||
}
|
||||
}, [session, status, router]);
|
||||
|
||||
// Fetch users
|
||||
useEffect(() => {
|
||||
if (session?.user?.role === "admin") {
|
||||
fetchUsers();
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch("/api/admin/users");
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch users");
|
||||
}
|
||||
const data = await response.json();
|
||||
setUsers(data);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async (userId) => {
|
||||
if (!confirm("Are you sure you want to delete this user?")) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${userId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete user");
|
||||
}
|
||||
|
||||
setUsers(users.filter(user => user.id !== userId));
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleUser = async (userId, isActive) => {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/users/${userId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ is_active: !isActive }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to update user");
|
||||
}
|
||||
|
||||
setUsers(users.map(user =>
|
||||
user.id === userId
|
||||
? { ...user, is_active: !isActive }
|
||||
: user
|
||||
));
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const getRoleColor = (role) => {
|
||||
switch (role) {
|
||||
case "admin":
|
||||
return "red";
|
||||
case "project_manager":
|
||||
return "blue";
|
||||
case "user":
|
||||
return "green";
|
||||
case "read_only":
|
||||
return "gray";
|
||||
default:
|
||||
return "gray";
|
||||
}
|
||||
};
|
||||
|
||||
const getRoleDisplay = (role) => {
|
||||
switch (role) {
|
||||
case "project_manager":
|
||||
return "Project Manager";
|
||||
case "read_only":
|
||||
return "Read Only";
|
||||
default:
|
||||
return role.charAt(0).toUpperCase() + role.slice(1);
|
||||
}
|
||||
};
|
||||
|
||||
if (status === "loading" || !session) {
|
||||
return <LoadingState />;
|
||||
}
|
||||
|
||||
if (session.user.role !== "admin") {
|
||||
return (
|
||||
<PageContainer>
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-6">You need admin privileges to access this page.</p>
|
||||
<Link href="/">
|
||||
<Button>Go Home</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader title="User Management" description="Manage system users and permissions">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
Add User
|
||||
</Button>
|
||||
</PageHeader>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-md">
|
||||
<p className="text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<LoadingState />
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Users List */}
|
||||
<div className="grid gap-6">
|
||||
{users.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<div className="text-center py-12">
|
||||
<svg className="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
|
||||
</svg>
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-2">No Users Found</h3>
|
||||
<p className="text-gray-500">Start by creating your first user.</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
users.map((user) => (
|
||||
<Card key={user.id}>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-gray-900">{user.name}</h3>
|
||||
<p className="text-sm text-gray-500">{user.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Badge color={getRoleColor(user.role)}>
|
||||
{getRoleDisplay(user.role)}
|
||||
</Badge>
|
||||
<Badge color={user.is_active ? "green" : "red"}>
|
||||
{user.is_active ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Created</p>
|
||||
<p className="text-sm text-gray-900">{formatDate(user.created_at)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Last Login</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{user.last_login ? formatDate(user.last_login) : "Never"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">Failed Attempts</p>
|
||||
<p className="text-sm text-gray-900">{user.failed_login_attempts || 0}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{user.locked_until && new Date(user.locked_until) > new Date() && (
|
||||
<div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
|
||||
<p className="text-sm text-yellow-800">
|
||||
Account locked until {formatDate(user.locked_until)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleToggleUser(user.id, user.is_active)}
|
||||
>
|
||||
{user.is_active ? "Deactivate" : "Activate"}
|
||||
</Button>
|
||||
<Link href={`/admin/users/${user.id}/edit`}>
|
||||
<Button variant="outline" size="sm">
|
||||
Edit
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteUser(user.id)}
|
||||
disabled={user.id === session?.user?.id}
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create User Modal/Form */}
|
||||
{showCreateForm && (
|
||||
<CreateUserModal
|
||||
onClose={() => setShowCreateForm(false)}
|
||||
onUserCreated={(newUser) => {
|
||||
setUsers([...users, newUser]);
|
||||
setShowCreateForm(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
// Create User Modal Component
|
||||
function CreateUserModal({ onClose, onUserCreated }) {
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
role: "user",
|
||||
is_active: true
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/users", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to create user");
|
||||
}
|
||||
|
||||
const newUser = await response.json();
|
||||
onUserCreated(newUser);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-semibold">Create New User</h3>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-600">
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md">
|
||||
<p className="text-red-600 text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Name
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Email
|
||||
</label>
|
||||
<Input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<Input
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
required
|
||||
minLength={6}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Role
|
||||
</label>
|
||||
<select
|
||||
value={formData.role}
|
||||
onChange={(e) => setFormData({ ...formData, role: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="read_only">Read Only</option>
|
||||
<option value="user">User</option>
|
||||
<option value="project_manager">Project Manager</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="is_active"
|
||||
checked={formData.is_active}
|
||||
onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
|
||||
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
|
||||
/>
|
||||
<label htmlFor="is_active" className="ml-2 block text-sm text-gray-900">
|
||||
Active User
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-3 pt-4">
|
||||
<Button type="submit" disabled={loading} className="flex-1">
|
||||
{loading ? "Creating..." : "Create User"}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={onClose} className="flex-1">
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
129
src/app/api/admin/users/[id]/route.js
Normal file
129
src/app/api/admin/users/[id]/route.js
Normal file
@@ -0,0 +1,129 @@
|
||||
import { getUserById, updateUser, deleteUser } from "@/lib/userManagement.js";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAdminAuth } from "@/lib/middleware/auth";
|
||||
|
||||
// GET: Get user by ID (admin only)
|
||||
async function getUserHandler(req, { params }) {
|
||||
try {
|
||||
const user = getUserById(params.id);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{ error: "User not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Remove password hash from response
|
||||
const { password_hash, ...safeUser } = user;
|
||||
return NextResponse.json(safeUser);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error fetching user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// PUT: Update user (admin only)
|
||||
async function updateUserHandler(req, { params }) {
|
||||
try {
|
||||
const data = await req.json();
|
||||
const userId = params.id;
|
||||
|
||||
// Prevent admin from deactivating themselves
|
||||
if (data.is_active === false && userId === req.user.id) {
|
||||
return NextResponse.json(
|
||||
{ error: "You cannot deactivate your own account" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate role if provided
|
||||
if (data.role) {
|
||||
const validRoles = ["read_only", "user", "project_manager", "admin"];
|
||||
if (!validRoles.includes(data.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid role specified" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate password length if provided
|
||||
if (data.password && data.password.length < 6) {
|
||||
return NextResponse.json(
|
||||
{ error: "Password must be at least 6 characters long" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const updatedUser = await updateUser(userId, data);
|
||||
|
||||
if (!updatedUser) {
|
||||
return NextResponse.json(
|
||||
{ error: "User not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Remove password hash from response
|
||||
const { password_hash, ...safeUser } = updatedUser;
|
||||
return NextResponse.json(safeUser);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error updating user:", error);
|
||||
|
||||
if (error.message.includes("already exists")) {
|
||||
return NextResponse.json(
|
||||
{ error: "A user with this email already exists" },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to update user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: Delete user (admin only)
|
||||
async function deleteUserHandler(req, { params }) {
|
||||
try {
|
||||
const userId = params.id;
|
||||
|
||||
// Prevent admin from deleting themselves
|
||||
if (userId === req.user.id) {
|
||||
return NextResponse.json(
|
||||
{ error: "You cannot delete your own account" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const success = await deleteUser(userId);
|
||||
|
||||
if (!success) {
|
||||
return NextResponse.json(
|
||||
{ error: "User not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "User deleted successfully" });
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error deleting user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to delete user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected routes - require admin authentication
|
||||
export const GET = withAdminAuth(getUserHandler);
|
||||
export const PUT = withAdminAuth(updateUserHandler);
|
||||
export const DELETE = withAdminAuth(deleteUserHandler);
|
||||
85
src/app/api/admin/users/route.js
Normal file
85
src/app/api/admin/users/route.js
Normal file
@@ -0,0 +1,85 @@
|
||||
import { getAllUsers, createUser } from "@/lib/userManagement.js";
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAdminAuth } from "@/lib/middleware/auth";
|
||||
|
||||
// GET: Get all users (admin only)
|
||||
async function getUsersHandler(req) {
|
||||
try {
|
||||
const users = getAllUsers();
|
||||
// Remove password hashes from response
|
||||
const safeUsers = users.map(user => {
|
||||
const { password_hash, ...safeUser } = user;
|
||||
return safeUser;
|
||||
});
|
||||
return NextResponse.json(safeUsers);
|
||||
} catch (error) {
|
||||
console.error("Error fetching users:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch users" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST: Create new user (admin only)
|
||||
async function createUserHandler(req) {
|
||||
try {
|
||||
const data = await req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!data.name || !data.email || !data.password) {
|
||||
return NextResponse.json(
|
||||
{ error: "Name, email, and password are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate password length
|
||||
if (data.password.length < 6) {
|
||||
return NextResponse.json(
|
||||
{ error: "Password must be at least 6 characters long" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ["read_only", "user", "project_manager", "admin"];
|
||||
if (data.role && !validRoles.includes(data.role)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid role specified" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const newUser = await createUser({
|
||||
name: data.name,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
role: data.role || "user",
|
||||
is_active: data.is_active !== undefined ? data.is_active : true
|
||||
});
|
||||
|
||||
// Remove password hash from response
|
||||
const { password_hash, ...safeUser } = newUser;
|
||||
return NextResponse.json(safeUser, { status: 201 });
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error creating user:", error);
|
||||
|
||||
if (error.message.includes("already exists")) {
|
||||
return NextResponse.json(
|
||||
{ error: "A user with this email already exists" },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to create user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Protected routes - require admin authentication
|
||||
export const GET = withAdminAuth(getUsersHandler);
|
||||
export const POST = withAdminAuth(createUserHandler);
|
||||
Reference in New Issue
Block a user