1
0
Code Issues Pull Requests Actions Packages Projects Releases Wiki Activity Security Code Quality

Add authentication

This commit is contained in:
2025-07-08 14:04:53 +07:00
parent b35066835b
commit adbe09d074
16 changed files with 992 additions and 460 deletions

View File

@@ -1,5 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { db, initDB, resetDB } from '@/database/database';
import { db, initDB } from '@/database/database';
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
export async function POST(req: NextRequest) {
await initDB();
@@ -8,8 +11,30 @@ export async function POST(req: NextRequest) {
(u) => u.username === username && u.password === password && !u.isDeleted
);
if (user) {
// In a real app, return a JWT or session token
return NextResponse.json({ success: true, user: { id: user.id, username: user.username, email: user.email, firstName: user.firstName, lastName: user.lastName } });
// Create JWT token
const token = jwt.sign(
{
id: user.id.toString(),
username: user.username,
email: user.email
},
JWT_SECRET,
{ expiresIn: '7d' }
);
const userData = {
id: user.id.toString(),
username: user.username,
email: user.email,
firstName: user.firstName,
lastName: user.lastName
};
return NextResponse.json({
success: true,
token,
user: userData
});
} else {
return NextResponse.json({ success: false, message: 'Invalid credentials' }, { status: 401 });
}

View File

@@ -0,0 +1,43 @@
import { NextRequest, NextResponse } from 'next/server';
import { db, initDB } from '@/database/database';
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
export async function POST(req: NextRequest) {
try {
await initDB();
const { token } = await req.json();
if (!token) {
return NextResponse.json({ success: false, message: 'No token provided' }, { status: 401 });
}
// Verify the token
const decoded = jwt.verify(token, JWT_SECRET) as { id: string; username: string; email: string };
// Find the user in the database
const user = db.data?.users.find(
(u) => u.id.toString() === decoded.id && !u.isDeleted
);
if (!user) {
return NextResponse.json({ success: false, message: 'User not found' }, { status: 401 });
}
const userData = {
id: user.id.toString(),
username: user.username,
email: user.email,
firstName: user.firstName,
lastName: user.lastName
};
return NextResponse.json({
success: true,
user: userData
});
} catch {
return NextResponse.json({ success: false, message: 'Invalid token' }, { status: 401 });
}
}

View File

@@ -13,10 +13,11 @@ function writeDB() {
// GET /api/user/[id]/permissions - Get all permissions for a user
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = parseInt(params.id);
const { id } = await params;
const userId = parseInt(id);
if (isNaN(userId)) {
return NextResponse.json({ error: "Invalid user ID" }, { status: 400 });
@@ -51,10 +52,11 @@ export async function GET(
// POST /api/user/[id]/permissions - Add permissions to a user
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = parseInt(params.id);
const { id } = await params;
const userId = parseInt(id);
if (isNaN(userId)) {
return NextResponse.json({ error: "Invalid user ID" }, { status: 400 });
@@ -126,10 +128,11 @@ export async function POST(
// PUT /api/user/[id]/permissions - Update permissions for a user
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = parseInt(params.id);
const { id } = await params;
const userId = parseInt(id);
if (isNaN(userId)) {
return NextResponse.json({ error: "Invalid user ID" }, { status: 400 });
@@ -201,10 +204,11 @@ export async function PUT(
// DELETE /api/user/[id]/permissions - Remove all permissions from a user
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = parseInt(params.id);
const { id } = await params;
const userId = parseInt(id);
if (isNaN(userId)) {
return NextResponse.json({ error: "Invalid user ID" }, { status: 400 });

View File

@@ -4,8 +4,10 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import axios from "axios";
import { useState } from "react";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { loginSchema } from "@/schemas/auth.schema";
import { useAuth } from "@/contexts/AuthContext";
import { Form } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -19,6 +21,15 @@ export default function LoginPage() {
});
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const { login, isAuthenticated } = useAuth();
const router = useRouter();
// Redirect if already authenticated
useEffect(() => {
if (isAuthenticated) {
router.push('/modules/user');
}
}, [isAuthenticated, router]);
const onSubmit = async (data: LoginForm) => {
setError("");
@@ -26,13 +37,15 @@ export default function LoginPage() {
try {
const res = await axios.post("/api/auth", data);
if (res.data.success) {
// You can redirect or set session here
window.location.href = "/modules/user"; // Redirect to user page on successful login
// Use the authentication context to login
login(res.data.token, res.data.user);
router.push("/modules/user");
} else {
setError(res.data.message || "Login failed");
}
} catch (e: any) {
setError(e.response?.data?.message || "Login failed");
} catch (e: unknown) {
const error = e as { response?: { data?: { message?: string } } };
setError(error.response?.data?.message || "Login failed");
} finally {
setLoading(false);
}

View File

@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Toaster } from "@/components/ui/sonner";
import { AuthProvider } from "@/contexts/AuthContext";
import "./globals.css";
const geistSans = Geist({
@@ -28,8 +29,10 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<Toaster />
<AuthProvider>
{children}
<Toaster />
</AuthProvider>
</body>
</html>
);

View File

@@ -6,7 +6,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useParams, useRouter } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Card, CardContent, CardDescription, CardHeader } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -246,6 +246,65 @@ export default function CustomerEditPage() {
toast.success("Dependant removed successfully!");
};
const handleNextTab = async () => {
if (activeTab === "info") {
// Validate customer info fields before proceeding
const isValid = await form.trigger([
"customerInfo.firstNameEn",
"customerInfo.lastNameEn",
"customerInfo.originAdd1",
"customerInfo.localAdd1",
]);
if (isValid) {
setActiveTab("contact");
} else {
toast.error("Please fill in all required fields in Customer Info tab.");
}
} else if (activeTab === "contact") {
// Validate customer contact fields before proceeding
const isValid = await form.trigger(["customerContact.email", "customerContact.mobile"]);
if (isValid) {
setActiveTab("dependants");
} else {
toast.error("Please fill in all required fields in Customer Contact tab.");
}
}
};
const handlePreviousTab = () => {
if (activeTab === "contact") {
setActiveTab("info");
} else if (activeTab === "dependants") {
setActiveTab("contact");
}
};
const isTabValid = (tabName: string) => {
const values = form.getValues();
const errors = form.formState.errors;
if (tabName === "info") {
return (
values.customerInfo?.firstNameEn?.trim() !== "" &&
values.customerInfo?.lastNameEn?.trim() !== "" &&
values.customerInfo?.originAdd1?.trim() !== "" &&
values.customerInfo?.localAdd1?.trim() !== "" &&
!errors.customerInfo?.firstNameEn &&
!errors.customerInfo?.lastNameEn &&
!errors.customerInfo?.originAdd1 &&
!errors.customerInfo?.localAdd1
);
} else if (tabName === "contact") {
return (
values.customerContact?.email?.trim() !== "" &&
values.customerContact?.mobile?.trim() !== "" &&
!errors.customerContact?.email &&
!errors.customerContact?.mobile
);
}
return true;
};
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
@@ -263,10 +322,9 @@ export default function CustomerEditPage() {
breadcrumbs={[
{ title: "Home", href: "/" },
{ title: "Customer Management", href: "/modules/customer" },
{ title: "Edit Customer", isCurrentPage: true }
{ title: "Edit Customer", isCurrentPage: true },
]}
/>
<div className="container mx-auto p-6 space-y-6">
/> <div className="container mx-auto p-6 space-y-6">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center space-x-4">
<Button
@@ -279,352 +337,394 @@ export default function CustomerEditPage() {
</Button>
<h1 className="text-2xl font-bold">Edit Customer</h1>
</div>
<Button
type="submit"
form="customer-edit-form"
disabled={isSaving}
className="flex items-center space-x-2"
>
{isSaving ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</>
) : (
<>
<Save className="h-4 w-4" />
<span>Save Changes</span>
</>
)}
</Button>
</div>
</div> <Card>
<CardHeader>
<CardDescription>
Edit the customer information across the three tabs below.
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<Tabs value={activeTab} className="w-full">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger
value="info"
className={!isTabValid("info") ? "text-red-500" : ""}
>
Customer Info
</TabsTrigger>
<TabsTrigger
value="contact"
className={!isTabValid("contact") ? "text-red-500" : ""}
disabled={!isTabValid("info")}
>
Customer Contact
</TabsTrigger>
<TabsTrigger
value="dependants"
disabled={!isTabValid("info") || !isTabValid("contact")}
>
Customer Dependants
</TabsTrigger>
</TabsList> <TabsContent value="info" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter first name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter last name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input placeholder="Enter origin address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input placeholder="Enter local address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end">
<Button type="button" onClick={handleNextTab}>
Next
</Button>
</div>
</TabsContent> <TabsContent value="contact" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" placeholder="Enter email address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile Number</FormLabel>
<FormControl>
<Input placeholder="Enter mobile number" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-between">
<Button type="button" variant="outline" onClick={handlePreviousTab}>
Previous
</Button>
<Button type="button" onClick={handleNextTab}>
Next
</Button>
</div>
</TabsContent> <TabsContent value="dependants" className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-semibold">Customer Dependants</h3>
<Dialog open={dependantDialogOpen} onOpenChange={setDependantDialogOpen}>
<DialogTrigger asChild>
<Button type="button" onClick={handleAddDependant} className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Add Dependant
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>
{editingDependant ? "Edit Dependant" : "Add New Dependant"}
</DialogTitle>
</DialogHeader>
<Form {...dependantForm}>
<form className="space-y-4">
<Tabs value={dependantDialogTab} onValueChange={setDependantDialogTab} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="info">Dependant Info</TabsTrigger>
<TabsTrigger value="contact">Dependant Contact</TabsTrigger>
</TabsList>
<Form {...form}>
<form id="customer-edit-form" className="space-y-6" onSubmit={form.handleSubmit(onSubmit)}>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="info">Customer Info</TabsTrigger>
<TabsTrigger value="contact">Contact Details</TabsTrigger>
<TabsTrigger value="dependants">Dependants</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Customer Information</CardTitle>
<CardDescription>Edit the customer&apos;s basic information</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="customerInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="contact" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Contact Details</CardTitle>
<CardDescription>Edit the customer&apos;s contact information</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<FormField
control={form.control}
name="customerContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="dependants" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Customer Dependants</CardTitle>
<CardDescription>Manage customer dependants</CardDescription>
</CardHeader>
<CardContent>
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold">
Dependants ({watchedDependants.length})
</h3>
<Dialog open={dependantDialogOpen} onOpenChange={setDependantDialogOpen}>
<DialogTrigger asChild>
<Button onClick={handleAddDependant} className="flex items-center space-x-2">
<Plus className="h-4 w-4" />
<span>Add Dependant</span>
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>
{editingDependant ? "Edit Dependant" : "Add New Dependant"}
</DialogTitle>
</DialogHeader>
<Form {...dependantForm}>
<form>
<Tabs value={dependantDialogTab} onValueChange={setDependantDialogTab}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="info">Personal Info</TabsTrigger>
<TabsTrigger value="contact">Contact Details</TabsTrigger>
</TabsList>
<TabsContent value="info" className="space-y-4 mt-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</TabsContent>
<TabsContent value="contact" className="space-y-4 mt-4">
<FormField
control={dependantForm.control}
name="dependantContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
</Tabs>
<div className="flex justify-end space-x-2 mt-6">
<Button
type="button"
variant="outline"
onClick={() => {
setDependantDialogOpen(false);
setEditingDependant(null);
dependantForm.reset();
}}
>
Cancel
</Button>
<TabsContent value="info" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.firstNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>First Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter first name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.lastNameEn"
render={({ field }) => (
<FormItem>
<FormLabel>Last Name (English)</FormLabel>
<FormControl>
<Input placeholder="Enter last name" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantInfo.originAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Origin Address</FormLabel>
<FormControl>
<Input placeholder="Enter origin address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantInfo.localAdd1"
render={({ field }) => (
<FormItem>
<FormLabel>Local Address</FormLabel>
<FormControl>
<Input placeholder="Enter local address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end">
<Button
type="button"
onClick={async () => {
const isValid = await dependantForm.trigger();
const isValid = await dependantForm.trigger([
"dependantInfo.firstNameEn",
"dependantInfo.lastNameEn",
"dependantInfo.originAdd1",
"dependantInfo.localAdd1"
]);
if (isValid) {
const formData = dependantForm.getValues();
onDependantSubmit(formData);
setDependantDialogTab("contact");
} else {
toast.error("Please fill in all required fields.");
toast.error("Please fill in all required fields in Dependant Info tab.");
}
}}
>
{editingDependant ? "Update Dependant" : "Add Dependant"}
Next
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
</TabsContent>
{watchedDependants.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Mobile</TableHead>
<TableHead>Origin Address</TableHead>
<TableHead>Local Address</TableHead>
<TableHead>Actions</TableHead>
<TabsContent value="contact" className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={dependantForm.control}
name="dependantContact.email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type="email" placeholder="Enter email address" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={dependantForm.control}
name="dependantContact.mobile"
render={({ field }) => (
<FormItem>
<FormLabel>Mobile Number</FormLabel>
<FormControl>
<Input placeholder="Enter mobile number" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-start">
<Button
type="button"
variant="outline"
onClick={() => setDependantDialogTab("info")}
>
Previous
</Button>
</div>
</TabsContent>
</Tabs>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={() => {
setDependantDialogOpen(false);
setEditingDependant(null);
dependantForm.reset();
}}
>
Cancel
</Button>
<Button
type="button"
onClick={async () => {
const isValid = await dependantForm.trigger();
if (isValid) {
const formData = dependantForm.getValues();
onDependantSubmit(formData);
} else {
toast.error("Please fill in all required fields.");
}
}}
>
{editingDependant ? "Update Dependant" : "Add Dependant"}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
{watchedDependants.length > 0 ? (
<div className="border rounded-lg">
<Table>
<TableHeader>
<TableRow>
<TableHead>First Name</TableHead>
<TableHead>Last Name</TableHead>
<TableHead>Email</TableHead>
<TableHead>Mobile</TableHead>
<TableHead>Origin Address</TableHead>
<TableHead>Local Address</TableHead>
<TableHead className="w-[100px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{watchedDependants.map((dependant) => (
<TableRow key={dependant.id}>
<TableCell>{dependant.dependantInfo.firstNameEn}</TableCell>
<TableCell>{dependant.dependantInfo.lastNameEn}</TableCell>
<TableCell>{dependant.dependantContact.email}</TableCell>
<TableCell>{dependant.dependantContact.mobile}</TableCell>
<TableCell>{dependant.dependantInfo.originAdd1}</TableCell>
<TableCell>{dependant.dependantInfo.localAdd1}</TableCell>
<TableCell>
<div className="flex space-x-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => handleEditDependant(dependant)}
>
Edit
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeDependant(dependant.id)}
className="text-red-500 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
</TableHeader>
<TableBody>
{watchedDependants.map((dependant) => (
<TableRow key={dependant.id}>
<TableCell>
{dependant.dependantInfo.firstNameEn} {dependant.dependantInfo.lastNameEn}
</TableCell>
<TableCell>{dependant.dependantContact.email}</TableCell>
<TableCell>{dependant.dependantContact.mobile}</TableCell>
<TableCell>{dependant.dependantInfo.originAdd1}</TableCell>
<TableCell>{dependant.dependantInfo.localAdd1}</TableCell>
<TableCell>
<div className="flex space-x-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => handleEditDependant(dependant)}
>
Edit
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => removeDependant(dependant.id)}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
))}
</TableBody>
</Table>
</div>
) : (
<div className="text-center text-muted-foreground py-8">
No dependants added yet. Click &quot;Add Dependant&quot; to add one.
</div>
)}
<div className="flex justify-between">
<Button type="button" variant="outline" onClick={handlePreviousTab}>
Previous
</Button>
<Button
type="submit"
disabled={isSaving}
className="flex items-center space-x-2"
>
{isSaving ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</>
) : (
<div className="text-center py-8 text-gray-500">
No dependants added yet. Click &quot;Add Dependant&quot; to get started.
</div>
<>
<Save className="h-4 w-4" />
<span>Save Customer</span>
</>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</form>
</Form>
</Button>
</div>
</TabsContent> </Tabs>
</form>
</Form>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
);
}

View File

@@ -1,4 +1,5 @@
import { AppSidebar } from "@/components/sidebar/app-sidebar";
import { ProtectedRoute } from "@/components/common/ProtectedRoute";
import {
SidebarInset,
SidebarProvider,
@@ -10,6 +11,7 @@ export default function ModulesLayout({
children: React.ReactNode;
}>) {
return (
<ProtectedRoute>
<main>
<SidebarProvider>
<AppSidebar />
@@ -18,5 +20,6 @@ export default function ModulesLayout({
</SidebarInset>
</SidebarProvider>
</main>
</ProtectedRoute>
);
}

View File

@@ -1,103 +1,30 @@
import Image from "next/image";
"use client";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
src/app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
const { isAuthenticated, isLoading } = useAuth();
const router = useRouter();
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
</div>
);
useEffect(() => {
if (!isLoading) {
if (isAuthenticated) {
router.push('/modules/user');
} else {
router.push('/auth/login');
}
}
}, [isAuthenticated, isLoading, router]);
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
</div>
);
}
return null;
}

View File

@@ -0,0 +1,34 @@
"use client";
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
interface ProtectedRouteProps {
children: React.ReactNode;
}
export const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
const { isAuthenticated, isLoading } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push('/auth/login');
}
}, [isAuthenticated, isLoading, router]);
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
</div>
);
}
if (!isAuthenticated) {
return null;
}
return <>{children}</>;
};

View File

@@ -1,6 +1,12 @@
"use client";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { Separator } from "@radix-ui/react-select";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useAuth } from "@/contexts/AuthContext";
import { LogOut, User } from "lucide-react";
interface BreadcrumbItemData {
title: string;
@@ -23,6 +29,8 @@ export function Header({
showParent = true,
breadcrumbs
}: HeaderProps) {
const { user, logout } = useAuth();
// Use breadcrumbs prop if provided, otherwise fall back to legacy props
const breadcrumbItems = breadcrumbs || [
...(showParent ? [{ title: parentTitle, href: parentHref }] : []),
@@ -55,6 +63,36 @@ export function Header({
))}
</BreadcrumbList>
</Breadcrumb>
{/* User Dropdown */}
<div className="ml-auto">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-8 w-8 rounded-full">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-200">
<User className="h-4 w-4" />
</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="end" forceMount>
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">
{user?.firstName} {user?.lastName}
</p>
<p className="text-xs leading-none text-muted-foreground">
{user?.email}
</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={logout} className="cursor-pointer">
<LogOut className="mr-2 h-4 w-4" />
<span>Log out</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</header>
);
}

View File

@@ -1,5 +1,5 @@
import { Button } from "@/components/ui/button";
import { Key, ArrowUpDown } from "lucide-react";
import { Key, ArrowUpDown, Trash2 } from "lucide-react";
import { Column } from "@tanstack/react-table";
export interface User {
@@ -102,7 +102,13 @@ export function createUserColumns({ onEdit, onDelete, onPermissions }: {
</Button>
)}
{onDelete && (
<Button size="sm" variant="destructive" onClick={() => onDelete(row.row.original.id)}>
<Button
size="sm"
variant="outline"
onClick={() => onDelete(row.row.original.id)}
className="text-red-600 hover:text-red-800 hover:bg-red-50"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
)}

View File

@@ -0,0 +1,101 @@
"use client";
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import Cookies from 'js-cookie';
import { useRouter } from 'next/navigation';
interface User {
id: string;
username: string;
email: string;
firstName: string;
lastName: string;
}
interface AuthContextType {
user: User | null;
login: (token: string, userData: User) => void;
logout: () => void;
isAuthenticated: boolean;
isLoading: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
interface AuthProviderProps {
children: ReactNode;
}
export const AuthProvider = ({ children }: AuthProviderProps) => {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const login = (token: string, userData: User) => {
Cookies.set('auth-token', token, { expires: 7 }); // 7 days
setUser(userData);
};
const logout = () => {
Cookies.remove('auth-token');
setUser(null);
router.push('/auth/login');
};
const verifyToken = async (token: string) => {
try {
const response = await fetch('/api/auth/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
});
if (response.ok) {
const data = await response.json();
if (data.success) {
setUser(data.user);
return true;
}
}
return false;
} catch (error) {
console.error('Token verification failed:', error);
return false;
}
};
useEffect(() => {
const initAuth = async () => {
const token = Cookies.get('auth-token');
if (token) {
const isValid = await verifyToken(token);
if (!isValid) {
Cookies.remove('auth-token');
}
}
setIsLoading(false);
};
initAuth();
}, []);
const value = {
user,
login,
logout,
isAuthenticated: !!user,
isLoading,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

View File

@@ -44,6 +44,15 @@
"mobile": "+1-416-555-0199",
"originAdd1": "100 Queen Street West, Toronto, ON M5H 2N2, Canada",
"localAdd1": "987 Ginza District, Tokyo, Japan 104-0061"
},
{
"id": 6,
"firstNameEn": "Đỗ",
"lastNameEn": "Thanh Tùng",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491",
"originAdd1": "123",
"localAdd1": "sdfgsdfg"
}
],
"users": [
@@ -621,6 +630,16 @@
"mobile": "+1-416-555-0191",
"originAdd1": "100 Queen Street West, Toronto, ON M5H 2N2, Canada",
"localAdd1": "987 Ginza District, Tokyo, Japan 104-0061"
},
{
"id": 10,
"custId": 6,
"firstNameEn": "Đỗ",
"lastNameEn": "Thanh Tùng",
"email": "dothanhtung196@gmail.com",
"mobile": "0987417491",
"originAdd1": "123",
"localAdd1": "sdfgsdfg"
}
]
}