Add authentication
This commit is contained in:
61
middleware.ts
Normal file
61
middleware.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||||
|
||||
// Define protected routes
|
||||
const protectedRoutes = ['/modules'];
|
||||
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// Check if the current path is a protected route
|
||||
const isProtectedRoute = protectedRoutes.some(route =>
|
||||
pathname.startsWith(route)
|
||||
);
|
||||
|
||||
|
||||
|
||||
// Get token from cookies
|
||||
const token = request.cookies.get('auth-token')?.value;
|
||||
|
||||
// If accessing a protected route without a token, redirect to login
|
||||
if (isProtectedRoute && !token) {
|
||||
return NextResponse.redirect(new URL('/auth/login', request.url));
|
||||
}
|
||||
|
||||
// Verify token if it exists
|
||||
if (token) {
|
||||
try {
|
||||
jwt.verify(token, JWT_SECRET);
|
||||
|
||||
// If user is authenticated and trying to access login page, redirect to modules
|
||||
if (pathname === '/auth/login') {
|
||||
return NextResponse.redirect(new URL('/modules/user', request.url));
|
||||
}
|
||||
} catch {
|
||||
// Invalid token - remove it and redirect to login if accessing protected route
|
||||
const response = NextResponse.redirect(new URL('/auth/login', request.url));
|
||||
response.cookies.delete('auth-token');
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow the request to continue
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - api (API routes)
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
*/
|
||||
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
};
|
||||
159
package-lock.json
generated
159
package-lock.json
generated
@@ -22,10 +22,14 @@
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"axios": "^1.10.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"lowdb": "^7.0.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next": "15.3.5",
|
||||
@@ -2297,6 +2301,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/js-cookie": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-3.0.6.tgz",
|
||||
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
@@ -2311,6 +2321,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
"integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/ms": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/lodash": {
|
||||
"version": "4.17.20",
|
||||
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.20.tgz",
|
||||
@@ -2328,11 +2348,16 @@
|
||||
"@types/lodash": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.19.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.4.tgz",
|
||||
"integrity": "sha512-OP+We5WV8Xnbuvw0zC2m4qfB/BJvjyCwtNjhHdJxV1639SGSKrLmJkc3fMnp2Qy8nJyHp8RO6umxELN/dS1/EA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
@@ -3260,6 +3285,12 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/busboy": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||
@@ -3680,6 +3711,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "9.2.2",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
||||
@@ -5269,6 +5309,15 @@
|
||||
"jiti": "lib/jiti-cli.mjs"
|
||||
}
|
||||
},
|
||||
"node_modules/js-cookie": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.5.tgz",
|
||||
"integrity": "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
@@ -5323,6 +5372,28 @@
|
||||
"json5": "lib/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.2",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
|
||||
"integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^3.2.2",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsx-ast-utils": {
|
||||
"version": "3.3.5",
|
||||
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
|
||||
@@ -5339,6 +5410,27 @@
|
||||
"node": ">=4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz",
|
||||
"integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
|
||||
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^1.4.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/keyv": {
|
||||
"version": "4.5.4",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
||||
@@ -5638,6 +5730,42 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||
@@ -5645,6 +5773,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/loose-envify": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
@@ -5812,7 +5946,6 @@
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
@@ -6570,6 +6703,26 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safe-push-apply": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
|
||||
@@ -6615,7 +6768,6 @@
|
||||
"version": "7.7.2",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
|
||||
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
|
||||
"devOptional": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
@@ -7342,7 +7494,6 @@
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unrs-resolver": {
|
||||
|
||||
@@ -23,10 +23,14 @@
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"axios": "^1.10.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"lowdb": "^7.0.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next": "15.3.5",
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
43
src/app/api/auth/verify/route.ts
Normal file
43
src/app/api/auth/verify/route.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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'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'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 "Add Dependant" 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 "Add Dependant" 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>
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
125
src/app/page.tsx
125
src/app/page.tsx
@@ -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;
|
||||
}
|
||||
|
||||
34
src/components/common/ProtectedRoute.tsx
Normal file
34
src/components/common/ProtectedRoute.tsx
Normal 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}</>;
|
||||
};
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
101
src/contexts/AuthContext.tsx
Normal file
101
src/contexts/AuthContext.tsx
Normal 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>;
|
||||
};
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user