feat: Add Auth Service with JWT authentication
This commit is contained in:
163
apps/web/src/app/(auth)/login/page.tsx
Normal file
163
apps/web/src/app/(auth)/login/page.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Mail, Lock, Loader2, Sparkles, AlertCircle } from 'lucide-react'
|
||||
import { useAuth } from '@/context/AuthContext'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter()
|
||||
const { login, isAuthenticated } = useAuth()
|
||||
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
// Redirect if already authenticated
|
||||
if (isAuthenticated) {
|
||||
router.push('/')
|
||||
return null
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await login(email, password)
|
||||
router.push('/')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center px-4 py-12">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Logo */}
|
||||
<div className="text-center mb-8">
|
||||
<Link href="/" className="inline-flex items-center gap-2">
|
||||
<Sparkles className="w-10 h-10 text-cyan-400" />
|
||||
<span className="text-2xl font-bold bg-gradient-to-r from-cyan-400 to-blue-500 bg-clip-text text-transparent">
|
||||
DAARION
|
||||
</span>
|
||||
</Link>
|
||||
<h1 className="mt-6 text-2xl font-bold text-white">Вхід в акаунт</h1>
|
||||
<p className="mt-2 text-slate-400">
|
||||
Увійдіть, щоб продовжити у DAARION.city
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="glass-panel p-8">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 rounded-xl text-red-400 text-sm">
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Email
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="your@email.com"
|
||||
required
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20',
|
||||
'transition-all'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Пароль
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minLength={8}
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20',
|
||||
'transition-all'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className={cn(
|
||||
'w-full py-3 rounded-xl font-medium transition-all',
|
||||
'bg-gradient-to-r from-cyan-500 to-blue-600 text-white',
|
||||
'hover:from-cyan-400 hover:to-blue-500',
|
||||
'shadow-lg shadow-cyan-500/20 hover:shadow-cyan-500/40',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="w-5 h-5 mx-auto animate-spin" />
|
||||
) : (
|
||||
'Увійти'
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="my-6 flex items-center gap-4">
|
||||
<div className="flex-1 h-px bg-white/10" />
|
||||
<span className="text-sm text-slate-500">або</span>
|
||||
<div className="flex-1 h-px bg-white/10" />
|
||||
</div>
|
||||
|
||||
{/* Register link */}
|
||||
<p className="text-center text-slate-400">
|
||||
Немає акаунту?{' '}
|
||||
<Link href="/register" className="text-cyan-400 hover:text-cyan-300 font-medium">
|
||||
Зареєструватися
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Back to home */}
|
||||
<p className="mt-6 text-center">
|
||||
<Link href="/" className="text-slate-500 hover:text-slate-400 text-sm">
|
||||
← Повернутися на головну
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
256
apps/web/src/app/(auth)/register/page.tsx
Normal file
256
apps/web/src/app/(auth)/register/page.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Mail, Lock, User, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react'
|
||||
import { useAuth } from '@/context/AuthContext'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter()
|
||||
const { register, isAuthenticated } = useAuth()
|
||||
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [displayName, setDisplayName] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
// Redirect if already authenticated
|
||||
if (isAuthenticated) {
|
||||
router.push('/')
|
||||
return null
|
||||
}
|
||||
|
||||
const passwordRequirements = [
|
||||
{ met: password.length >= 8, text: 'Мінімум 8 символів' },
|
||||
{ met: /[A-Z]/.test(password), text: 'Одна велика літера' },
|
||||
{ met: /[a-z]/.test(password), text: 'Одна мала літера' },
|
||||
{ met: /[0-9]/.test(password), text: 'Одна цифра' },
|
||||
]
|
||||
|
||||
const isPasswordValid = passwordRequirements.every(r => r.met)
|
||||
const doPasswordsMatch = password === confirmPassword && password.length > 0
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
|
||||
if (!isPasswordValid) {
|
||||
setError('Пароль не відповідає вимогам')
|
||||
return
|
||||
}
|
||||
|
||||
if (!doPasswordsMatch) {
|
||||
setError('Паролі не співпадають')
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await register(email, password, displayName || undefined)
|
||||
router.push('/')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Registration failed')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center px-4 py-12">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Logo */}
|
||||
<div className="text-center mb-8">
|
||||
<Link href="/" className="inline-flex items-center gap-2">
|
||||
<Sparkles className="w-10 h-10 text-cyan-400" />
|
||||
<span className="text-2xl font-bold bg-gradient-to-r from-cyan-400 to-blue-500 bg-clip-text text-transparent">
|
||||
DAARION
|
||||
</span>
|
||||
</Link>
|
||||
<h1 className="mt-6 text-2xl font-bold text-white">Створити акаунт</h1>
|
||||
<p className="mt-2 text-slate-400">
|
||||
Приєднуйтесь до DAARION.city
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="glass-panel p-8">
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/20 rounded-xl text-red-400 text-sm">
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Display Name */}
|
||||
<div>
|
||||
<label htmlFor="displayName" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Ім'я (опційно)
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="displayName"
|
||||
type="text"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
placeholder="Ваше ім'я"
|
||||
maxLength={100}
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20',
|
||||
'transition-all'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Email *
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="your@email.com"
|
||||
required
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20',
|
||||
'transition-all'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Пароль *
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20',
|
||||
'transition-all'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Password requirements */}
|
||||
{password.length > 0 && (
|
||||
<div className="mt-2 space-y-1">
|
||||
{passwordRequirements.map((req, i) => (
|
||||
<div key={i} className={cn(
|
||||
'flex items-center gap-2 text-xs',
|
||||
req.met ? 'text-emerald-400' : 'text-slate-500'
|
||||
)}>
|
||||
<CheckCircle2 className={cn('w-3 h-3', !req.met && 'opacity-50')} />
|
||||
{req.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-slate-300 mb-2">
|
||||
Підтвердіть пароль *
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
|
||||
<input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
className={cn(
|
||||
'w-full pl-10 pr-4 py-3 bg-slate-800/50 border border-white/10 rounded-xl',
|
||||
'text-white placeholder-slate-500',
|
||||
'focus:outline-none focus:ring-1 transition-all',
|
||||
confirmPassword.length > 0 && (
|
||||
doPasswordsMatch
|
||||
? 'border-emerald-500/50 focus:border-emerald-500/50 focus:ring-emerald-500/20'
|
||||
: 'border-red-500/50 focus:border-red-500/50 focus:ring-red-500/20'
|
||||
),
|
||||
confirmPassword.length === 0 && 'border-white/10 focus:border-cyan-500/50 focus:ring-cyan-500/20'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{confirmPassword.length > 0 && !doPasswordsMatch && (
|
||||
<p className="mt-1 text-xs text-red-400">Паролі не співпадають</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !isPasswordValid || !doPasswordsMatch}
|
||||
className={cn(
|
||||
'w-full py-3 rounded-xl font-medium transition-all',
|
||||
'bg-gradient-to-r from-cyan-500 to-blue-600 text-white',
|
||||
'hover:from-cyan-400 hover:to-blue-500',
|
||||
'shadow-lg shadow-cyan-500/20 hover:shadow-cyan-500/40',
|
||||
'disabled:opacity-50 disabled:cursor-not-allowed'
|
||||
)}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="w-5 h-5 mx-auto animate-spin" />
|
||||
) : (
|
||||
'Зареєструватися'
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="my-6 flex items-center gap-4">
|
||||
<div className="flex-1 h-px bg-white/10" />
|
||||
<span className="text-sm text-slate-500">або</span>
|
||||
<div className="flex-1 h-px bg-white/10" />
|
||||
</div>
|
||||
|
||||
{/* Login link */}
|
||||
<p className="text-center text-slate-400">
|
||||
Вже маєте акаунт?{' '}
|
||||
<Link href="/login" className="text-cyan-400 hover:text-cyan-300 font-medium">
|
||||
Увійти
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Back to home */}
|
||||
<p className="mt-6 text-center">
|
||||
<Link href="/" className="text-slate-500 hover:text-slate-400 text-sm">
|
||||
← Повернутися на головну
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Metadata, Viewport } from 'next'
|
||||
import { Inter } from 'next/font/google'
|
||||
import './globals.css'
|
||||
import { Navigation } from '@/components/Navigation'
|
||||
import { AuthProvider } from '@/context/AuthContext'
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ['latin', 'cyrillic'],
|
||||
@@ -31,16 +32,18 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="uk" className={inter.variable}>
|
||||
<body className={`${inter.className} antialiased`}>
|
||||
{/* Ambient background effect */}
|
||||
<div className="ambient-bg" />
|
||||
|
||||
{/* Navigation */}
|
||||
<Navigation />
|
||||
|
||||
{/* Main content */}
|
||||
<main className="min-h-screen pt-16">
|
||||
{children}
|
||||
</main>
|
||||
<AuthProvider>
|
||||
{/* Ambient background effect */}
|
||||
<div className="ambient-bg" />
|
||||
|
||||
{/* Navigation */}
|
||||
<Navigation />
|
||||
|
||||
{/* Main content */}
|
||||
<main className="min-h-screen pt-16">
|
||||
{children}
|
||||
</main>
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { Menu, X, Home, Building2, User, Sparkles, Bot, Wallet } from 'lucide-react'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { Menu, X, Home, Building2, User, Sparkles, Bot, Wallet, LogOut, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useAuth } from '@/context/AuthContext'
|
||||
|
||||
const navItems = [
|
||||
{ href: '/', label: 'Головна', icon: Home },
|
||||
@@ -17,6 +18,19 @@ const navItems = [
|
||||
export function Navigation() {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const { user, isAuthenticated, isLoading, logout } = useAuth()
|
||||
|
||||
const handleLogout = async () => {
|
||||
await logout()
|
||||
router.push('/')
|
||||
setIsOpen(false)
|
||||
}
|
||||
|
||||
// Don't show navigation on auth pages
|
||||
if (pathname.startsWith('/login') || pathname.startsWith('/register')) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="fixed top-0 left-0 right-0 z-50">
|
||||
@@ -64,12 +78,44 @@ export function Navigation() {
|
||||
|
||||
{/* Auth buttons (desktop) */}
|
||||
<div className="hidden md:flex items-center gap-3">
|
||||
<button className="px-4 py-2 text-sm text-slate-300 hover:text-white transition-colors">
|
||||
Увійти
|
||||
</button>
|
||||
<button className="px-4 py-2 text-sm font-medium bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl hover:from-cyan-400 hover:to-blue-500 transition-all duration-200 shadow-lg shadow-cyan-500/20">
|
||||
Приєднатися
|
||||
</button>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-5 h-5 text-slate-400 animate-spin" />
|
||||
) : isAuthenticated && user ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-cyan-500/30 to-blue-600/30 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-cyan-400">
|
||||
{user.display_name?.[0]?.toUpperCase() || user.email[0].toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-sm text-slate-300 max-w-[120px] truncate">
|
||||
{user.display_name || user.email}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="p-2 text-slate-400 hover:text-white transition-colors"
|
||||
title="Вийти"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Link
|
||||
href="/login"
|
||||
className="px-4 py-2 text-sm text-slate-300 hover:text-white transition-colors"
|
||||
>
|
||||
Увійти
|
||||
</Link>
|
||||
<Link
|
||||
href="/register"
|
||||
className="px-4 py-2 text-sm font-medium bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl hover:from-cyan-400 hover:to-blue-500 transition-all duration-200 shadow-lg shadow-cyan-500/20"
|
||||
>
|
||||
Приєднатися
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Mobile menu button */}
|
||||
@@ -108,13 +154,48 @@ export function Navigation() {
|
||||
)
|
||||
})}
|
||||
|
||||
<div className="flex gap-3 mt-4 pt-4 border-t border-white/10">
|
||||
<button className="flex-1 py-3 text-sm text-slate-300 hover:text-white transition-colors rounded-xl hover:bg-white/5">
|
||||
Увійти
|
||||
</button>
|
||||
<button className="flex-1 py-3 text-sm font-medium bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl">
|
||||
Приєднатися
|
||||
</button>
|
||||
<div className="mt-4 pt-4 border-t border-white/10">
|
||||
{isAuthenticated && user ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3 px-4">
|
||||
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-cyan-500/30 to-blue-600/30 flex items-center justify-center">
|
||||
<span className="font-medium text-cyan-400">
|
||||
{user.display_name?.[0]?.toUpperCase() || user.email[0].toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-white truncate">
|
||||
{user.display_name || 'User'}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400 truncate">{user.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="w-full flex items-center justify-center gap-2 py-3 text-sm text-red-400 hover:bg-red-500/10 rounded-xl transition-colors"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
Вийти
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-3">
|
||||
<Link
|
||||
href="/login"
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="flex-1 py-3 text-sm text-center text-slate-300 hover:text-white transition-colors rounded-xl hover:bg-white/5"
|
||||
>
|
||||
Увійти
|
||||
</Link>
|
||||
<Link
|
||||
href="/register"
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="flex-1 py-3 text-sm text-center font-medium bg-gradient-to-r from-cyan-500 to-blue-600 rounded-xl"
|
||||
>
|
||||
Приєднатися
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -123,4 +204,3 @@ export function Navigation() {
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
86
apps/web/src/context/AuthContext.tsx
Normal file
86
apps/web/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react'
|
||||
import { User, getStoredUser, getMe, login as authLogin, logout as authLogout, register as authRegister, isAuthenticated } from '@/lib/auth'
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
isLoading: boolean
|
||||
isAuthenticated: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
register: (email: string, password: string, displayName?: string) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
refreshUser: () => Promise<void>
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const refreshUser = useCallback(async () => {
|
||||
try {
|
||||
const userData = await getMe()
|
||||
setUser(userData)
|
||||
} catch {
|
||||
setUser(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
// Check for stored user on mount
|
||||
const storedUser = getStoredUser()
|
||||
if (storedUser) {
|
||||
setUser(storedUser)
|
||||
}
|
||||
|
||||
// Verify token and refresh user data
|
||||
if (isAuthenticated()) {
|
||||
refreshUser().finally(() => setIsLoading(false))
|
||||
} else {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [refreshUser])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const response = await authLogin(email, password)
|
||||
setUser(response.user)
|
||||
}
|
||||
|
||||
const register = async (email: string, password: string, displayName?: string) => {
|
||||
await authRegister(email, password, displayName)
|
||||
// Auto-login after registration
|
||||
await login(email, password)
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await authLogout()
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
refreshUser
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext)
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
228
apps/web/src/lib/auth.ts
Normal file
228
apps/web/src/lib/auth.ts
Normal file
@@ -0,0 +1,228 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Auth utilities for DAARION Frontend
|
||||
*/
|
||||
|
||||
export interface User {
|
||||
id: string
|
||||
email: string
|
||||
display_name: string | null
|
||||
avatar_url: string | null
|
||||
roles: string[]
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface AuthTokens {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
token_type: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export interface LoginResponse extends AuthTokens {
|
||||
user: User
|
||||
}
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || ''
|
||||
|
||||
// Token storage keys
|
||||
const ACCESS_TOKEN_KEY = 'daarion_access_token'
|
||||
const REFRESH_TOKEN_KEY = 'daarion_refresh_token'
|
||||
const USER_KEY = 'daarion_user'
|
||||
|
||||
// Token management
|
||||
export function getAccessToken(): string | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function getStoredUser(): User | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
const stored = localStorage.getItem(USER_KEY)
|
||||
if (!stored) return null
|
||||
try {
|
||||
return JSON.parse(stored)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setTokens(tokens: AuthTokens, user?: User): void {
|
||||
if (typeof window === 'undefined') return
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.access_token)
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refresh_token)
|
||||
if (user) {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
}
|
||||
}
|
||||
|
||||
export function clearTokens(): void {
|
||||
if (typeof window === 'undefined') return
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
localStorage.removeItem(USER_KEY)
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return !!getAccessToken()
|
||||
}
|
||||
|
||||
// API calls
|
||||
export async function register(
|
||||
email: string,
|
||||
password: string,
|
||||
displayName?: string
|
||||
): Promise<{ user_id: string; email: string }> {
|
||||
const response = await fetch(`${API_BASE}/api/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
password,
|
||||
display_name: displayName
|
||||
})
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
throw new Error(error.detail || 'Registration failed')
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export async function login(email: string, password: string): Promise<LoginResponse> {
|
||||
const response = await fetch(`${API_BASE}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
throw new Error(error.detail || 'Login failed')
|
||||
}
|
||||
|
||||
const data: LoginResponse = await response.json()
|
||||
setTokens(data, data.user)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function refreshTokens(): Promise<AuthTokens | null> {
|
||||
const refreshToken = getRefreshToken()
|
||||
if (!refreshToken) return null
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: refreshToken })
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
clearTokens()
|
||||
return null
|
||||
}
|
||||
|
||||
const data: AuthTokens = await response.json()
|
||||
setTokens(data)
|
||||
return data
|
||||
} catch {
|
||||
clearTokens()
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
const refreshToken = getRefreshToken()
|
||||
|
||||
if (refreshToken) {
|
||||
try {
|
||||
await fetch(`${API_BASE}/api/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: refreshToken })
|
||||
})
|
||||
} catch {
|
||||
// Ignore errors during logout
|
||||
}
|
||||
}
|
||||
|
||||
clearTokens()
|
||||
}
|
||||
|
||||
export async function getMe(): Promise<User | null> {
|
||||
const token = getAccessToken()
|
||||
if (!token) return null
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/api/auth/me`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
// Try to refresh
|
||||
const refreshed = await refreshTokens()
|
||||
if (refreshed) {
|
||||
return getMe()
|
||||
}
|
||||
clearTokens()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const user: User = await response.json()
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
return user
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Auth header for API requests
|
||||
export function getAuthHeader(): Record<string, string> {
|
||||
const token = getAccessToken()
|
||||
if (!token) return {}
|
||||
return { 'Authorization': `Bearer ${token}` }
|
||||
}
|
||||
|
||||
// Fetch with auth
|
||||
export async function authFetch(
|
||||
url: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<Response> {
|
||||
const token = getAccessToken()
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers as Record<string, string> || {})
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
let response = await fetch(url, { ...options, headers })
|
||||
|
||||
// If 401, try to refresh and retry
|
||||
if (response.status === 401 && token) {
|
||||
const refreshed = await refreshTokens()
|
||||
if (refreshed) {
|
||||
headers['Authorization'] = `Bearer ${refreshed.access_token}`
|
||||
response = await fetch(url, { ...options, headers })
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user