feat(web): add i18n locale routes and language switcher component
Add locale-prefixed routes for admin, auth, dashboard, and public pages. Add error, loading, and not-found pages for locale context. Add language switcher UI component for Vietnamese/English toggle. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
199
apps/web/app/[locale]/(auth)/__tests__/login.spec.tsx
Normal file
199
apps/web/app/[locale]/(auth)/__tests__/login.spec.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
/* eslint-disable import-x/order */
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
|
||||
// Mock next-intl with Vietnamese messages
|
||||
const viMessages = await import('@/messages/vi.json');
|
||||
vi.mock('next-intl', () => ({
|
||||
useTranslations: (namespace: string) => {
|
||||
const messages = viMessages.default ?? viMessages;
|
||||
const ns = messages[namespace as keyof typeof messages] as Record<string, unknown> | undefined;
|
||||
return (key: string) => {
|
||||
if (!ns) return key;
|
||||
const parts = key.split('.');
|
||||
let val: unknown = ns;
|
||||
for (const p of parts) {
|
||||
val = (val as Record<string, unknown>)?.[p];
|
||||
}
|
||||
return typeof val === 'string' ? val : key;
|
||||
};
|
||||
},
|
||||
NextIntlClientProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
}));
|
||||
|
||||
// Mock next/navigation
|
||||
const mockPush = vi.fn();
|
||||
const mockSearchParams = new URLSearchParams();
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
useSearchParams: () => mockSearchParams,
|
||||
}));
|
||||
|
||||
// Mock next/link
|
||||
vi.mock('next/link', () => ({
|
||||
default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
|
||||
<a href={href} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock i18n navigation (Link used in login page)
|
||||
vi.mock('@/i18n/navigation', () => ({
|
||||
Link: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
|
||||
<a href={href} {...props}>{children}</a>
|
||||
),
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => '/login',
|
||||
redirect: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock auth store
|
||||
vi.mock('@/lib/auth-store', () => {
|
||||
const store = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
handleOAuthCallback: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refreshToken: vi.fn(),
|
||||
fetchProfile: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
clearError: vi.fn(),
|
||||
};
|
||||
return {
|
||||
useAuthStore: vi.fn((selector) => {
|
||||
if (typeof selector === 'function') return selector(store);
|
||||
return store;
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import LoginPage from '../login/page';
|
||||
|
||||
const mockedUseAuthStore = vi.mocked(useAuthStore);
|
||||
|
||||
describe('LoginPage', () => {
|
||||
let mockStore: {
|
||||
user: null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
login: ReturnType<typeof vi.fn>;
|
||||
register: ReturnType<typeof vi.fn>;
|
||||
handleOAuthCallback: ReturnType<typeof vi.fn>;
|
||||
logout: ReturnType<typeof vi.fn>;
|
||||
refreshToken: ReturnType<typeof vi.fn>;
|
||||
fetchProfile: ReturnType<typeof vi.fn>;
|
||||
initialize: ReturnType<typeof vi.fn>;
|
||||
clearError: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockStore = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
handleOAuthCallback: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refreshToken: vi.fn(),
|
||||
fetchProfile: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
clearError: vi.fn(),
|
||||
};
|
||||
mockedUseAuthStore.mockImplementation((selector) => {
|
||||
if (typeof selector === 'function') return (selector as (s: typeof mockStore) => unknown)(mockStore);
|
||||
return mockStore as ReturnType<typeof useAuthStore>;
|
||||
});
|
||||
});
|
||||
|
||||
it('renders login form with phone and password fields', () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Đăng nhập' })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Số điện thoại')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Mật khẩu')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /đăng nhập/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders OAuth buttons', () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
expect(screen.getByRole('button', { name: /google/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /zalo/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders register link', () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
const registerLink = screen.getByRole('link', { name: /đăng ký/i });
|
||||
expect(registerLink).toHaveAttribute('href', '/register');
|
||||
});
|
||||
|
||||
it('submits form with valid data', async () => {
|
||||
mockStore.login.mockResolvedValue(undefined);
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockStore.login).toHaveBeenCalledWith({
|
||||
phone: '0912345678',
|
||||
password: 'password123',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('shows validation errors for empty fields', async () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
const alerts = screen.getAllByRole('alert');
|
||||
expect(alerts.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('toggles password visibility', async () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
const passwordInput = screen.getByLabelText('Mật khẩu');
|
||||
expect(passwordInput).toHaveAttribute('type', 'password');
|
||||
|
||||
await userEvent.click(screen.getByText('Hiện'));
|
||||
expect(passwordInput).toHaveAttribute('type', 'text');
|
||||
|
||||
await userEvent.click(screen.getByText('Ẩn'));
|
||||
expect(passwordInput).toHaveAttribute('type', 'password');
|
||||
});
|
||||
|
||||
it('displays store error message', () => {
|
||||
mockStore.error = 'Sai mật khẩu';
|
||||
render(<LoginPage />);
|
||||
|
||||
expect(screen.getByText('Sai mật khẩu')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('navigates to home after successful login', async () => {
|
||||
mockStore.login.mockResolvedValue(undefined);
|
||||
render(<LoginPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
});
|
||||
199
apps/web/app/[locale]/(auth)/__tests__/register.spec.tsx
Normal file
199
apps/web/app/[locale]/(auth)/__tests__/register.spec.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
/* eslint-disable import-x/order */
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
|
||||
// Mock next-intl with Vietnamese messages
|
||||
const viMessages = await import('@/messages/vi.json');
|
||||
vi.mock('next-intl', () => ({
|
||||
useTranslations: (namespace: string) => {
|
||||
const messages = viMessages.default ?? viMessages;
|
||||
const ns = messages[namespace as keyof typeof messages] as Record<string, unknown> | undefined;
|
||||
return (key: string) => {
|
||||
if (!ns) return key;
|
||||
const parts = key.split('.');
|
||||
let val: unknown = ns;
|
||||
for (const p of parts) {
|
||||
val = (val as Record<string, unknown>)?.[p];
|
||||
}
|
||||
return typeof val === 'string' ? val : key;
|
||||
};
|
||||
},
|
||||
NextIntlClientProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
}));
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}));
|
||||
|
||||
vi.mock('next/link', () => ({
|
||||
default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
|
||||
<a href={href} {...props}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock i18n navigation (Link used in register page)
|
||||
vi.mock('@/i18n/navigation', () => ({
|
||||
Link: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
|
||||
<a href={href} {...props}>{children}</a>
|
||||
),
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => '/register',
|
||||
redirect: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/auth-store', () => {
|
||||
const store = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
handleOAuthCallback: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refreshToken: vi.fn(),
|
||||
fetchProfile: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
clearError: vi.fn(),
|
||||
};
|
||||
return {
|
||||
useAuthStore: vi.fn((selector) => {
|
||||
if (typeof selector === 'function') return selector(store);
|
||||
return store;
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import RegisterPage from '../register/page';
|
||||
|
||||
const mockedUseAuthStore = vi.mocked(useAuthStore);
|
||||
|
||||
describe('RegisterPage', () => {
|
||||
let mockStore: {
|
||||
user: null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
login: ReturnType<typeof vi.fn>;
|
||||
register: ReturnType<typeof vi.fn>;
|
||||
handleOAuthCallback: ReturnType<typeof vi.fn>;
|
||||
logout: ReturnType<typeof vi.fn>;
|
||||
refreshToken: ReturnType<typeof vi.fn>;
|
||||
fetchProfile: ReturnType<typeof vi.fn>;
|
||||
initialize: ReturnType<typeof vi.fn>;
|
||||
clearError: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockStore = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
handleOAuthCallback: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
refreshToken: vi.fn(),
|
||||
fetchProfile: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
clearError: vi.fn(),
|
||||
};
|
||||
mockedUseAuthStore.mockImplementation((selector) => {
|
||||
if (typeof selector === 'function') return (selector as (s: typeof mockStore) => unknown)(mockStore);
|
||||
return mockStore as ReturnType<typeof useAuthStore>;
|
||||
});
|
||||
});
|
||||
|
||||
it('renders register form with all fields', () => {
|
||||
render(<RegisterPage />);
|
||||
|
||||
expect(screen.getByText('Đăng ký')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Họ và tên')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Số điện thoại')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Mật khẩu')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Xác nhận mật khẩu')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders login link', () => {
|
||||
render(<RegisterPage />);
|
||||
const loginLink = screen.getByRole('link', { name: /đăng nhập/i });
|
||||
expect(loginLink).toHaveAttribute('href', '/login');
|
||||
});
|
||||
|
||||
it('submits form with valid data', async () => {
|
||||
mockStore.register.mockResolvedValue(undefined);
|
||||
render(<RegisterPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
|
||||
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockStore.register).toHaveBeenCalledWith({
|
||||
phone: '0912345678',
|
||||
password: 'password123',
|
||||
fullName: 'Nguyen Van A',
|
||||
email: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('shows validation error for short password', async () => {
|
||||
render(<RegisterPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'short');
|
||||
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'short');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
const alerts = screen.getAllByRole('alert');
|
||||
expect(alerts.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows error when passwords do not match', async () => {
|
||||
render(<RegisterPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
|
||||
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'differentpw');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
const alerts = screen.getAllByRole('alert');
|
||||
expect(alerts.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('displays store error message', () => {
|
||||
mockStore.error = 'Số điện thoại đã tồn tại';
|
||||
render(<RegisterPage />);
|
||||
expect(screen.getByText('Số điện thoại đã tồn tại')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('navigates to home after successful registration', async () => {
|
||||
mockStore.register.mockResolvedValue(undefined);
|
||||
render(<RegisterPage />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
|
||||
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
|
||||
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
|
||||
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
});
|
||||
58
apps/web/app/[locale]/(auth)/error.tsx
Normal file
58
apps/web/app/[locale]/(auth)/error.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function AuthError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
console.error('Auth error:', error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-8 shadow-sm">
|
||||
<div className="text-center">
|
||||
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-destructive/10">
|
||||
<svg
|
||||
className="h-7 w-7 text-destructive"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="mt-4 text-xl font-semibold">Lỗi xác thực</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Đã xảy ra lỗi trong quá trình xác thực. Vui lòng thử lại.
|
||||
</p>
|
||||
{error.digest && (
|
||||
<p className="mt-1 text-xs text-muted-foreground">Mã lỗi: {error.digest}</p>
|
||||
)}
|
||||
<div className="mt-6 flex justify-center gap-3">
|
||||
<button
|
||||
onClick={reset}
|
||||
className="inline-flex h-9 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90"
|
||||
>
|
||||
Thử lại
|
||||
</button>
|
||||
<a
|
||||
href="/login"
|
||||
className="inline-flex h-9 items-center rounded-md border border-input bg-background px-4 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground"
|
||||
>
|
||||
Về trang đăng nhập
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
7
apps/web/app/[locale]/(auth)/layout.tsx
Normal file
7
apps/web/app/[locale]/(auth)/layout.tsx
Normal file
@@ -0,0 +1,7 @@
|
||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<main id="main-content" role="main" className="flex min-h-screen items-center justify-center bg-muted/40 px-4 py-12">
|
||||
<div className="w-full max-w-md">{children}</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
40
apps/web/app/[locale]/(auth)/loading.tsx
Normal file
40
apps/web/app/[locale]/(auth)/loading.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
export default function AuthLoading() {
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-8 shadow-sm">
|
||||
<div className="space-y-6">
|
||||
{/* Logo / title skeleton */}
|
||||
<div className="text-center">
|
||||
<div className="mx-auto h-8 w-24 animate-pulse rounded bg-muted" />
|
||||
<div className="mx-auto mt-3 h-5 w-40 animate-pulse rounded bg-muted" />
|
||||
<div className="mx-auto mt-2 h-4 w-56 animate-pulse rounded bg-muted" />
|
||||
</div>
|
||||
|
||||
{/* Form fields skeleton */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="h-4 w-16 animate-pulse rounded bg-muted" />
|
||||
<div className="mt-2 h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="h-4 w-20 animate-pulse rounded bg-muted" />
|
||||
<div className="mt-2 h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit button skeleton */}
|
||||
<div className="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
|
||||
{/* OAuth buttons skeleton */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
<div className="h-3 w-12 animate-pulse rounded bg-muted" />
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
</div>
|
||||
<div className="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div className="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
apps/web/app/[locale]/(auth)/login/page.tsx
Normal file
138
apps/web/app/[locale]/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { OAuthButtons } from '@/components/auth/oauth-buttons';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Link } from '@/i18n/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { loginSchema, type LoginFormData } from '@/lib/validations/auth';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { login, isLoading, error, clearError } = useAuthStore();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const t = useTranslations('auth');
|
||||
|
||||
const oauthError = searchParams.get('error');
|
||||
const oauthErrorMessage = oauthError
|
||||
? t(`oauthErrors.${oauthError}` as Parameters<typeof t>[0]) ?? t('oauthErrors.default')
|
||||
: null;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<LoginFormData>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
});
|
||||
|
||||
const onSubmit = async (data: LoginFormData) => {
|
||||
try {
|
||||
await login(data);
|
||||
router.push('/');
|
||||
} catch {
|
||||
// Error is handled by the store
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1 text-center">
|
||||
<CardTitle className="text-2xl font-bold">{t('loginTitle')}</CardTitle>
|
||||
<CardDescription>{t('loginDescription')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
|
||||
{oauthErrorMessage && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
|
||||
{oauthErrorMessage}
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
<button type="button" onClick={clearError} className="ml-2 font-medium underline">
|
||||
{t('dismiss')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">{t('phone')}</Label>
|
||||
<Input
|
||||
id="phone"
|
||||
type="tel"
|
||||
placeholder={t('phonePlaceholder')}
|
||||
autoComplete="tel"
|
||||
aria-describedby={errors.phone ? 'phone-error' : undefined}
|
||||
aria-invalid={!!errors.phone}
|
||||
{...register('phone')}
|
||||
/>
|
||||
{errors.phone && (
|
||||
<p id="phone-error" className="text-sm text-destructive" role="alert">{errors.phone.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">{t('password')}</Label>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground hover:text-primary"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
aria-label={showPassword ? t('hidePassword') : t('showPassword')}
|
||||
>
|
||||
{showPassword ? t('hidePassword') : t('showPassword')}
|
||||
</button>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder={t('passwordPlaceholder')}
|
||||
autoComplete="current-password"
|
||||
aria-describedby={errors.password ? 'password-error' : undefined}
|
||||
aria-invalid={!!errors.password}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p id="password-error" className="text-sm text-destructive" role="alert">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
|
||||
{t('loginButton')}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="relative my-4">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">{t('orLoginWith')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OAuthButtons />
|
||||
</CardContent>
|
||||
<CardFooter className="justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('noAccount')}{' '}
|
||||
<Link href="/register" className="font-medium text-primary hover:underline">
|
||||
{t('registerLink')}
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
180
apps/web/app/[locale]/(auth)/register/page.tsx
Normal file
180
apps/web/app/[locale]/(auth)/register/page.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { OAuthButtons } from '@/components/auth/oauth-buttons';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Link } from '@/i18n/navigation';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { registerSchema, type RegisterFormData } from '@/lib/validations/auth';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter();
|
||||
const { register: registerUser, isLoading, error, clearError } = useAuthStore();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const t = useTranslations('auth');
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<RegisterFormData>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
});
|
||||
|
||||
const onSubmit = async (data: RegisterFormData) => {
|
||||
try {
|
||||
await registerUser({
|
||||
phone: data.phone,
|
||||
password: data.password,
|
||||
fullName: data.fullName,
|
||||
email: data.email || undefined,
|
||||
});
|
||||
router.push('/');
|
||||
} catch {
|
||||
// Error is handled by the store
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1 text-center">
|
||||
<CardTitle className="text-2xl font-bold">{t('registerTitle')}</CardTitle>
|
||||
<CardDescription>{t('registerDescription')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
<button type="button" onClick={clearError} className="ml-2 font-medium underline">
|
||||
{t('dismiss')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fullName">{t('fullName')}</Label>
|
||||
<Input
|
||||
id="fullName"
|
||||
type="text"
|
||||
placeholder={t('fullNamePlaceholder')}
|
||||
autoComplete="name"
|
||||
aria-describedby={errors.fullName ? 'fullName-error' : undefined}
|
||||
aria-invalid={!!errors.fullName}
|
||||
{...register('fullName')}
|
||||
/>
|
||||
{errors.fullName && (
|
||||
<p id="fullName-error" className="text-sm text-destructive" role="alert">{errors.fullName.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">{t('phone')}</Label>
|
||||
<Input
|
||||
id="phone"
|
||||
type="tel"
|
||||
placeholder={t('phonePlaceholder')}
|
||||
autoComplete="tel"
|
||||
aria-describedby={errors.phone ? 'phone-error' : undefined}
|
||||
aria-invalid={!!errors.phone}
|
||||
{...register('phone')}
|
||||
/>
|
||||
{errors.phone && (
|
||||
<p id="phone-error" className="text-sm text-destructive" role="alert">{errors.phone.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t('email')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder={t('emailPlaceholder')}
|
||||
autoComplete="email"
|
||||
aria-describedby={errors.email ? 'email-error' : undefined}
|
||||
aria-invalid={!!errors.email}
|
||||
{...register('email')}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p id="email-error" className="text-sm text-destructive" role="alert">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">{t('password')}</Label>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground hover:text-primary"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
aria-label={showPassword ? t('hidePassword') : t('showPassword')}
|
||||
>
|
||||
{showPassword ? t('hidePassword') : t('showPassword')}
|
||||
</button>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder={t('passwordPlaceholder')}
|
||||
autoComplete="new-password"
|
||||
aria-describedby={errors.password ? 'password-error' : undefined}
|
||||
aria-invalid={!!errors.password}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p id="password-error" className="text-sm text-destructive" role="alert">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">{t('confirmPassword')}</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder={t('confirmPasswordPlaceholder')}
|
||||
autoComplete="new-password"
|
||||
aria-describedby={errors.confirmPassword ? 'confirmPassword-error' : undefined}
|
||||
aria-invalid={!!errors.confirmPassword}
|
||||
{...register('confirmPassword')}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<p id="confirmPassword-error" className="text-sm text-destructive" role="alert">{errors.confirmPassword.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
|
||||
{t('registerButton')}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="relative my-4">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">{t('orRegisterWith')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OAuthButtons />
|
||||
</CardContent>
|
||||
<CardFooter className="justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('hasAccount')}{' '}
|
||||
<Link href="/login" className="font-medium text-primary hover:underline">
|
||||
{t('loginLink')}
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user