This commit is contained in:
Mac mini
2026-03-31 10:35:38 +07:00
parent 0ba4d43518
commit 3412ba81cf
10 changed files with 414 additions and 96 deletions

1
.gitignore vendored
View File

@@ -28,6 +28,7 @@ yarn-error.log*
# local env files
.env*.local
.env
# vercel
.vercel

4
api.ts
View File

@@ -2,9 +2,13 @@ export const API_URL_ROOT = process.env.NEXT_PUBLIC_API_URL_ROOT || "";
export const API = {
User : {
CURRENT: `${API_URL_ROOT}/users/current`
},
Auth : {
SIGNUP: `${API_URL_ROOT}/auth/signup`,
SIGNIN: `${API_URL_ROOT}/auth/signin`,
CREATEOTP: `${API_URL_ROOT}/auth/token/create`,
VERIFYOTP: `${API_URL_ROOT}/auth/token/verify`,
REFRESH: `${API_URL_ROOT}/auth/refresh`
}
}

138
package-lock.json generated
View File

@@ -20,6 +20,7 @@
"@tailwindcss/postcss": "^4.1.17",
"apexcharts": "^4.7.0",
"autoprefixer": "^10.4.22",
"axios": "^1.14.1",
"flatpickr": "^4.6.13",
"next": "^16.1.6",
"react": "^19.2.0",
@@ -28,6 +29,7 @@
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^19.2.0",
"react-dropzone": "^14.3.8",
"sonner": "^2.0.7",
"swiper": "^11.2.10",
"tailwind-merge": "^2.6.0"
},
@@ -4110,6 +4112,12 @@
"node": ">= 0.4"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
"node_modules/attr-accept": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
@@ -4178,6 +4186,18 @@
"node": ">=4"
}
},
"node_modules/axios": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.14.1.tgz",
"integrity": "sha512-vF/aB4vrIzLyOb2TB9gpuE8gusNHpZqk2ZZcAqSnRjW5IcY7tFSBEurD2tbakohj0Rw5xMHYwjSqOGSfr0iewA==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.11",
"form-data": "^4.0.5",
"plain-crypto-js": "^4.2.1",
"proxy-from-env": "^2.1.0"
}
},
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -4322,7 +4342,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dev": true,
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
@@ -4431,6 +4450,18 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
@@ -4708,6 +4739,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -4807,7 +4847,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dev": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
@@ -4933,7 +4972,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -4942,7 +4980,6 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -4978,7 +5015,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dev": true,
"dependencies": {
"es-errors": "^1.3.0"
},
@@ -4990,7 +5026,6 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"dev": true,
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
@@ -5582,6 +5617,26 @@
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
"dev": true
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"license": "MIT",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/for-each": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",
@@ -5597,6 +5652,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/form-data": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fraction.js": {
"version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -5613,7 +5684,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@@ -5669,7 +5739,6 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dev": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
@@ -5693,7 +5762,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"dev": true,
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
@@ -5775,7 +5843,6 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"dev": true,
"engines": {
"node": ">= 0.4"
},
@@ -5840,7 +5907,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"dev": true,
"engines": {
"node": ">= 0.4"
},
@@ -5852,7 +5918,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"dev": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@@ -5867,7 +5932,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.2"
},
@@ -6813,7 +6877,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"dev": true,
"engines": {
"node": ">= 0.4"
}
@@ -6846,6 +6909,27 @@
"node": ">=8.6"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mini-svg-data-uri": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz",
@@ -7292,6 +7376,13 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/plain-crypto-js": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/plain-crypto-js/-/plain-crypto-js-4.2.1.tgz",
"integrity": "sha512-Wv41p4/aEMq03JjDqi0JxPYT4aoMbbQMSM8ur4QkjvjGEeuYvI7rGkqLcOZ7K1iThQGvpNvJnxRWcNodCNuEEQ==",
"hasInstallScript": true,
"license": "MIT"
},
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@@ -7361,6 +7452,15 @@
"react-is": "^16.13.1"
}
},
"node_modules/proxy-from-env": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -7924,6 +8024,16 @@
"tslib": "^2.0.3"
}
},
"node_modules/sonner": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",
"integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==",
"license": "MIT",
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",
"react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",

View File

@@ -21,6 +21,7 @@
"@tailwindcss/postcss": "^4.1.17",
"apexcharts": "^4.7.0",
"autoprefixer": "^10.4.22",
"axios": "^1.14.1",
"flatpickr": "^4.6.13",
"next": "^16.1.6",
"react": "^19.2.0",
@@ -29,6 +30,7 @@
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^19.2.0",
"react-dropzone": "^14.3.8",
"sonner": "^2.0.7",
"swiper": "^11.2.10",
"tailwind-merge": "^2.6.0"
},

View File

@@ -3,6 +3,7 @@ import './globals.css';
import "flatpickr/dist/flatpickr.css";
import { SidebarProvider } from '@/context/SidebarContext';
import { ThemeProvider } from '@/context/ThemeContext';
import { Toaster } from 'sonner';
const outfit = Outfit({
subsets: ["latin"],
@@ -17,7 +18,7 @@ export default function RootLayout({
<html lang="en">
<body className={`${outfit.className} dark:bg-gray-900`}>
<ThemeProvider>
<SidebarProvider>{children}</SidebarProvider>
<SidebarProvider>{children} <Toaster closeButton richColors position="top-right" /> </SidebarProvider>
</ThemeProvider>
</body>
</html>

View File

@@ -1,15 +1,84 @@
"use client";
import Checkbox from "@/components/form/input/Checkbox";
import Input from "@/components/form/input/InputField";
import Label from "@/components/form/Label";
import Button from "@/components/ui/button/Button";
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "@/icons";
import { apiGetCurrentUser, apiSignIn } from "@/service/auth";
import Link from "next/link";
import React, { useState } from "react";
import { toast } from 'sonner';
import { API } from "../../../api";
import api from "@/config/config";
export default function SignInForm() {
const [showPassword, setShowPassword] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [isChecked, setIsChecked] = useState(false);
const [errorMsg, setErrorMsg] = useState("");
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
email: "",
password: "",
});
const isFormEmpty = !formData.email.trim() || !formData.password.trim();
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
setErrorMsg("");
};
const isValidEmail = (email: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const isValidPassword = (pass: string) => {
const passwordRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
return passwordRegex.test(pass);
};
const handleSignInClick = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (loading || isFormEmpty) return;
setErrorMsg("");
if (!isValidEmail(formData.email)) {
setErrorMsg("Email không đúng định dạng.");
return;
}
if (!isValidPassword(formData.password)) {
setErrorMsg("Mật khẩu tối thiểu 8 ký tự, 1 in hoa, 1 số và 1 ký tự đặc biệt.");
return;
}
try {
setLoading(true);
const res = await apiSignIn(formData);
console.log("API Sign In Response:", res);
const data = await api.get(API.User.CURRENT);
console.log("Current User:", data);
if (res.status === true) {
toast.success('Đăng nhập thành công!');
}else{
toast.error('Email hoặc mật khẩu không đúng.');
}
} catch (error) {
setErrorMsg("Lỗi khi đăng nhập. Vui lòng thử lại.");
toast.error('Đăng nhập thất bại. Vui lòng kiểm tra lại thông tin.');
} finally {
setLoading(false);
}
}
return (
<div className="flex flex-col flex-1 lg:w-1/2 w-full">
<div className="w-full max-w-md sm:pt-10 mx-auto mb-5">
@@ -84,60 +153,73 @@ export default function SignInForm() {
</span>
</div>
</div>
<form>
<div className="space-y-6">
<div>
<Label>
Email <span className="text-error-500">*</span>{" "}
</Label>
<Input placeholder="info@gmail.com" type="email" />
</div>
<div>
<Label>
Password <span className="text-error-500">*</span>{" "}
</Label>
<div className="relative">
<Input
type={showPassword ? "text" : "password"}
placeholder="Enter your password"
/>
<span
onClick={() => setShowPassword(!showPassword)}
className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2"
>
{showPassword ? (
<span className="fill-gray-500 dark:fill-gray-400">
<EyeIcon />
</span>
) : (
<span className="fill-gray-500 dark:fill-gray-400">
<EyeCloseIcon />
</span>
)}
</span>
</div>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Checkbox checked={isChecked} onChange={setIsChecked} />
<span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
Keep me logged in
</span>
</div>
<Link
href="/reset-password"
className="text-sm text-brand-500 hover:text-brand-600 dark:text-brand-400"
>
Forgot password?
</Link>
</div>
<div>
<Button className="w-full" size="sm">
Sign in
</Button>
<form onSubmit={handleSignInClick}>
<div className="space-y-6">
<div>
<Label>
Email <span className="text-error-500">*</span>
</Label>
<Input
name="email"
placeholder="info@gmail.com"
type="email"
onChange={handleChange}
defaultValue={formData.email}
/>
</div>
<div>
<Label>
Password <span className="text-error-500">*</span>
</Label>
<div className={`relative ${formData.password.length > 0 && !isValidPassword(formData.password) ? 'border border-red-500 ring-1 ring-red-500 rounded-lg' : ''}`}>
<Input
name="password"
type={showPassword ? "text" : "password"}
placeholder="Min. 8 characters"
onChange={handleChange}
defaultValue={formData.password}
/>
<span onClick={() => setShowPassword(!showPassword)} className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2">
{showPassword ? <EyeIcon /> : <EyeCloseIcon />}
</span>
</div>
</div>
</form>
{/* Hiển thị thông báo lỗi nếu có */}
{errorMsg && (
<p className="text-sm text-red-500 font-medium">{errorMsg}</p>
)}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Checkbox checked={isChecked} onChange={setIsChecked} />
<span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
Keep me logged in
</span>
</div>
<Link href="/reset-password" className="text-sm text-brand-500 hover:text-brand-600 dark:text-brand-400">
Forgot password?
</Link>
</div>
<div>
<button
disabled={loading || isFormEmpty}
type="submit"
className={`w-full flex items-center justify-center px-4 py-3 text-sm font-medium text-white transition rounded-lg shadow-theme-xs
${(loading || isFormEmpty) ? 'bg-gray-400 cursor-not-allowed' : 'bg-brand-500 hover:bg-brand-600'}`}
>
{loading ? (
<span className="flex items-center gap-2">
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
Signing in...
</span>
) : "Sign in"}
</button>
</div>
</div>
</form>
<div className="mt-5">
<p className="text-sm font-normal text-center text-gray-700 dark:text-gray-400 sm:text-start">

View File

@@ -6,13 +6,13 @@ import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "@/icons";
import { apiCreateOTP, apiSignUp, apiVerifyOTP } from "@/service/auth";
import Link from "next/link";
import { useState } from "react";
import { toast } from "sonner";
export default function SignUpForm() {
const [showPassword, setShowPassword] = useState(false);
const [isChecked, setIsChecked] = useState(false);
// State quản lý form và luồng
const [step, setStep] = useState(1); // 1: Đăng ký, 2: Nhập OTP
const [step, setStep] = useState(1);
const [formData, setFormData] = useState({
fname: "",
lname: "",
@@ -28,20 +28,16 @@ export default function SignUpForm() {
setErrorMsg("");
};
// Hàm validate email
const isValidEmail = (email:string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
// Hàm validate mật khẩu mới
const isValidPassword = (pass: string) => {
// Tối thiểu 8 ký tự, 1 chữ in hoa, 1 chữ số, 1 ký tự đặc biệt
const passwordRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
return passwordRegex.test(pass);
};
// Xử lý khi bấm nút Sign Up (Step 1)
const handleSignUpClick = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setErrorMsg("");
@@ -65,12 +61,12 @@ export default function SignUpForm() {
setStep(2);
} catch (error) {
setErrorMsg("Lỗi khi tạo OTP. Vui lòng thử lại.");
toast.error('Tạo OTP thất bại. Vui lòng kiểm tra lại thông tin.');
} finally {
setLoading(false);
}
};
// Xử lý khi xác nhận OTP (Step 2)
const handleVerifyOtpSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setErrorMsg("");
@@ -103,7 +99,7 @@ export default function SignUpForm() {
console.log("Đăng ký thành công!", signupRes);
alert("Đăng ký thành công! Đang chuyển hướng...");
window.location.href = '/signin'; // Chuyển hướng người dùng
window.location.href = '/signin';
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Xác thực OTP hoặc đăng ký thất bại.";
@@ -144,10 +140,8 @@ export default function SignUpForm() {
</div>
)}
{/* ----- STEP 1: FORM SIGN UP ----- */}
{step === 1 && (
<>
{/* Các nút đăng ký Social */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-5">
<button className="inline-flex items-center justify-center gap-3 py-3 text-sm font-normal text-gray-700 transition-colors bg-gray-100 rounded-lg px-7 hover:bg-gray-200 hover:text-gray-800 dark:bg-white/5 dark:text-white/90 dark:hover:bg-white/10">
Sign up with Google
@@ -170,7 +164,7 @@ export default function SignUpForm() {
<form onSubmit={handleSignUpClick}>
<div className="space-y-5">
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
{/* First Name */}
<div className="sm:col-span-1">
<Label>
First Name<span className="text-error-500">*</span>
@@ -183,7 +177,7 @@ export default function SignUpForm() {
placeholder="Enter your first name"
/>
</div>
{/* Last Name */}
<div className="sm:col-span-1">
<Label>
Last Name<span className="text-error-500">*</span>
@@ -198,7 +192,6 @@ export default function SignUpForm() {
</div>
</div>
{/* Email */}
<div>
<Label>
Email<span className="text-error-500">*</span>
@@ -212,11 +205,9 @@ export default function SignUpForm() {
/>
</div>
{/* Password */}
<div>
<Label>Password<span className="text-error-500">*</span></Label>
{/* Thêm style báo đỏ ô nhập nếu pass chưa hợp lệ */}
<div className={`relative ${formData.password.length > 0 && !isValidPassword(formData.password) ? 'border border-red-500 ring-1 ring-red-500 rounded-lg' : ''}`}>
<Input
name="password"
@@ -230,19 +221,19 @@ export default function SignUpForm() {
</span>
</div>
{/* Gợi ý trực quan cho người dùng */}
<p className={`mt-2 text-xs ${formData.password.length === 0 ? 'text-gray-400' : isValidPassword(formData.password) ? 'text-green-500' : 'text-red-500'}`}>
Mật khẩu phải chứa tối thiểu 8 tự, 1 chữ cái in hoa, 1 chữ số 1 tự đc biệt.
</p>
</div>
{/* Checkbox */}
<div className="flex items-center gap-3">
<div className={formData.password.length > 0 && !isValidPassword(formData.password) ? "opacity-50 cursor-not-allowed" : ""}>
<Checkbox
className="w-5 h-5"
checked={isChecked}
// Chặn bấm check nếu password chưa hợp lệ
onChange={(val) => {
if (isValidPassword(formData.password)) setIsChecked(val);
}}
@@ -261,7 +252,7 @@ export default function SignUpForm() {
</p>
</div>
{/* Button */}
<div>
<button
type="submit"
@@ -289,7 +280,6 @@ export default function SignUpForm() {
</>
)}
{/* ----- STEP 2: FORM NHẬP OTP ----- */}
{step === 2 && (
<form onSubmit={handleVerifyOtpSubmit}>
<div className="space-y-5">

View File

@@ -0,0 +1,37 @@
import axios from "axios";
import { API } from "../../api";
const axiosInstance = axios.create({
baseURL: "/",
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
});
axiosInstance.interceptors.response.use(
(response) => {
if (response.data && response.data.status === false) {
return handleRefreshToken(response);
}
return response;
},
async (error) => {
return Promise.reject(error);
}
);
async function handleRefreshToken(originalResponse: any) {
try {
const refreshRes = await axios.get(API.Auth.REFRESH, { withCredentials: true });
if (refreshRes.data && refreshRes.data.status !== false) {
return axiosInstance(originalResponse.config);
}
} catch (err) {
console.error("Refresh token failed", err);
}
return originalResponse;
}
export default axiosInstance;

65
src/config/config.ts Normal file
View File

@@ -0,0 +1,65 @@
import axios from "axios"
import { API_URL_ROOT } from "../../api"
const baseURL = API_URL_ROOT || "https://history-api.kain.id.vn"
const api = axios.create({
baseURL,
withCredentials: true
})
let isRefreshing = false
let queue: any[] = []
const processQueue = (error?: any) => {
queue.forEach((p) => {
if (error) p.reject(error)
else p.resolve()
})
queue = []
}
api.interceptors.response.use(
(res) => res,
async (err) => {
const originalRequest = err.config
if (err.response?.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
queue.push({
resolve: () => resolve(api(originalRequest)),
reject
})
})
}
originalRequest._retry = true
isRefreshing = true
try {
await axios.post(
`${baseURL}/auth/refresh`,
{},
{ withCredentials: true }
)
processQueue()
return api(originalRequest)
} catch (refreshErr) {
processQueue(refreshErr)
// window.location.href = "/login"
return Promise.reject(refreshErr)
} finally {
isRefreshing = false
}
}
return Promise.reject(err)
}
)
export default api

View File

@@ -1,8 +1,10 @@
import axiosInstance from "@/config/axiosInstance";
import { API } from "../../api";
import api from "@/config/config";
export const apiCreateOTP = async (email : string) => {
const token_type = 2;
const response = await fetch(API.User.CREATEOTP, {
const response = await fetch(API.Auth.CREATEOTP, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, token_type }),
@@ -12,8 +14,7 @@ export const apiCreateOTP = async (email : string) => {
export const apiVerifyOTP = async (email: string, token: string) => {
const body = { email, token, token_type: 2 };
console.log("Request Body for Verify OTP:", body); // Log body trước khi gửi yêu cầu
const response = await fetch(API.User.VERIFYOTP, {
const response = await fetch(API.Auth.VERIFYOTP, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
@@ -22,10 +23,35 @@ export const apiVerifyOTP = async (email: string, token: string) => {
};
export const apiSignUp = async (payload: any) => {
const response = await fetch(API.User.SIGNUP, {
const response = await fetch(API.Auth.SIGNUP, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
return response.json();
};
export const apiSignIn = async (payload: any) => {
const response = await fetch(API.Auth.SIGNIN, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(payload),
});
return response.json();
};
export const apiGetCurrentUser = async () => {
const response = await fetch(API.User.CURRENT,{
method: "GET",
headers: { "Content-Type": "application/json" },
credentials: "include",
});
return response.json();
};
export interface ApiResponse<T> {
status: boolean
data: T
message?: string
}