Spaces:
Running
Running
File size: 8,090 Bytes
7e79d39 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | 'use client';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { BRAND_NAME, BRAND_TAGLINE, ROUTES } from '@/shared/constants';
import { setToken } from '@/shared/lib/httpClient';
import { useToast } from '@/shared/hooks/useToast';
import { BrandLogoMark } from '@/shared/components/BrandGlyphs';
import { Button } from '@/shared/components/Button';
import { Input } from '@/shared/components/Input';
import { Lock, Mail, ShieldAlert, Sparkles, User as UserIcon, X } from 'lucide-react';
import { validateLoginInput, validateRegisterInput } from '../schemas/authSchema';
import { authService } from '../services/authService';
import { useAuthSession } from '../hooks/useAuthSession';
import { AuthModalMode } from '../types/authTypes';
export function AuthDialog({
standaloneOpen = false,
onStandaloneClose,
}: {
standaloneOpen?: boolean;
onStandaloneClose?: () => void;
}) {
const router = useRouter();
const { pushToast } = useToast();
const {
publicConfig,
authModalOpen,
authModalMode,
closeAuthModal,
setSessionUser,
} = useAuthSession();
const isOpen = standaloneOpen || authModalOpen;
const registrationDisabled = !!publicConfig.disable_registration;
const [mode, setMode] = useState<AuthModalMode>('login');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (isOpen) {
setMode(registrationDisabled ? 'login' : authModalMode);
setError('');
}
}, [isOpen, authModalMode, registrationDisabled]);
useEffect(() => {
if (!isOpen) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
if (onStandaloneClose) onStandaloneClose();
else closeAuthModal();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [isOpen, onStandaloneClose, closeAuthModal]);
if (!isOpen) return null;
const handleDismiss = () => {
if (onStandaloneClose) onStandaloneClose();
else closeAuthModal();
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setSubmitting(true);
try {
let res;
if (mode === 'login') {
const check = validateLoginInput(username, password);
if (!check.ok || !check.data) {
setError(check.error || 'Dữ liệu chưa hợp lệ');
setSubmitting(false);
return;
}
res = await authService.login(check.data.username, check.data.password);
} else {
const check = validateRegisterInput(username, email, password);
if (!check.ok || !check.data) {
setError(check.error || 'Dữ liệu chưa hợp lệ');
setSubmitting(false);
return;
}
res = await authService.register(check.data.username, check.data.email, check.data.password);
}
setToken(res.token);
setSessionUser(res.user);
closeAuthModal();
pushToast(`Xin chào ${res.user.username}!`, 'success');
if (!standaloneOpen) {
router.push(ROUTES.PANEL_FILES);
}
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Không thể kết nối máy chủ');
} finally {
setSubmitting(false);
}
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={`Đăng nhập ${BRAND_NAME}`}
onClick={handleDismiss}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm p-4"
>
<section
onClick={(e) => e.stopPropagation()}
className="relative w-full max-w-md rounded-2xl bg-surface-1 border border-line shadow-2xl p-6 sm:p-8"
>
<button
type="button"
onClick={handleDismiss}
aria-label="Đóng hộp thoại đăng nhập"
className="absolute right-4 top-4 p-2 min-h-[40px] min-w-[40px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<X className="w-4 h-4" aria-hidden="true" />
</button>
<header className="text-center mb-6 space-y-2">
<div className="w-12 h-12 mx-auto rounded-xl bg-accent/15 border border-accent/35 text-accent flex items-center justify-center">
<BrandLogoMark className="w-6 h-6" />
</div>
<h2 className="text-xl font-bold tracking-tight text-ink-1">{BRAND_NAME}</h2>
<p className="text-xs text-ink-2">{BRAND_TAGLINE}</p>
</header>
<div className="flex bg-surface-2 border border-line p-1 rounded-xl mb-5">
<button
type="button"
onClick={() => {
setMode('login');
setError('');
}}
className={`flex-1 min-h-[38px] text-xs font-semibold rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
mode === 'login' ? 'bg-accent text-on-accent shadow-sm' : 'text-ink-2 hover:text-ink-1'
}`}
>
Đăng nhập
</button>
{!registrationDisabled && (
<button
type="button"
onClick={() => {
setMode('register');
setError('');
}}
className={`flex-1 min-h-[38px] text-xs font-semibold rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
mode === 'register'
? 'bg-accent text-on-accent shadow-sm'
: 'text-ink-2 hover:text-ink-1'
}`}
>
Đăng ký
</button>
)}
</div>
{error && (
<div
role="alert"
className="mb-4 flex items-center gap-2 p-3 text-xs text-rose-500 bg-rose-500/10 border border-rose-500/30 rounded-xl"
>
<ShieldAlert className="w-4 h-4 flex-shrink-0" aria-hidden="true" />
<span>{error}</span>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-3.5">
<Input
label="Tài khoản"
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder={
mode === 'login'
? 'Username hoặc Email'
: 'Username (chữ thường, tối thiểu 3 ký tự)'
}
leftIcon={<UserIcon className="w-4 h-4" />}
/>
{mode === 'register' && (
<Input
label="Email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="name@example.com (tùy chọn)"
leftIcon={<Mail className="w-4 h-4" />}
/>
)}
<Input
label="Mật khẩu"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={mode === 'register' ? 'Tối thiểu 6 ký tự' : 'Mật khẩu'}
leftIcon={<Lock className="w-4 h-4" />}
/>
<Button type="submit" loading={submitting} className="w-full mt-2">
{submitting ? 'Đang xử lý...' : mode === 'login' ? 'Đăng nhập' : 'Tạo tài khoản'}
</Button>
</form>
<footer className="mt-5 text-center flex items-center justify-center gap-1.5 text-[11px] text-accent">
<Sparkles className="w-3.5 h-3.5" aria-hidden="true" />
<span>Hệ thống Standalone — Tài khoản đầu tiên tự động làm Admin</span>
</footer>
</section>
</div>
);
}
|