Fix authentication state persistence and admin role display

- Implement complete authentication system with JWT token validation
- Add auth provider with persistent login state across page refreshes
- Create multilingual login/register forms with Material-UI components
- Fix token validation using raw SQL queries to bypass Prisma sync issues
- Add comprehensive error handling for expired/invalid tokens
- Create profile and settings pages with full i18n support
- Add proper user role management (admin/user) with database sync
- Implement secure middleware with CSRF protection and auth checks
- Add debug endpoints for troubleshooting authentication issues
- Fix Zustand store persistence for authentication state

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
andupetcu
2025-09-21 01:06:30 +03:00
parent 62ca73b2ac
commit 196ca00194
174 changed files with 181207 additions and 179 deletions

View File

@@ -0,0 +1,316 @@
'use client'
import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react'
import { useLocale } from 'next-intl'
import { useStore } from '@/lib/store'
import { isTokenExpired, clearExpiredToken } from '@/lib/auth/client'
interface User {
id: string
email: string
name?: string
role: string
theme: string
fontSize: string
createdAt: Date
updatedAt: Date
lastLoginAt?: Date
}
interface AuthContextType {
user: User | null
isAuthenticated: boolean
isLoading: boolean
login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>
register: (email: string, password: string, name?: string) => Promise<{ success: boolean; error?: string }>
logout: () => Promise<void>
refreshUser: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
interface AuthProviderProps {
children: ReactNode
}
export function AuthProvider({ children }: AuthProviderProps) {
const [isLoading, setIsLoading] = useState(true)
const [initialized, setInitialized] = useState(false)
const locale = useLocale()
const { user, setUser } = useStore()
const refreshUser = async (forceRefresh = false) => {
const token = localStorage.getItem('authToken')
if (!token) {
setUser(null)
setIsLoading(false)
return
}
// Check if token is expired before making request
if (isTokenExpired(token)) {
console.log('Token expired in refreshUser, clearing auth state')
localStorage.removeItem('authToken')
setUser(null)
setIsLoading(false)
return
}
// If we already have a user and this isn't a forced refresh, don't re-fetch
if (user && !forceRefresh) {
setIsLoading(false)
return
}
try {
const response = await fetch(`/api/auth/me?locale=${locale}`, {
headers: {
'Authorization': `Bearer ${token}`
}
})
if (response.ok) {
const data = await response.json()
setUser(data.user)
} else {
// Token is invalid or expired, get error details
try {
const errorData = await response.json()
console.log('Server returned 401 error:', errorData)
} catch (e) {
console.log('Server returned 401 without JSON body, status:', response.status)
}
console.log('Token expired or invalid, clearing auth state')
localStorage.removeItem('authToken')
setUser(null)
}
} catch (error) {
console.error('Auth check failed:', error)
// Network error or other issues, clean up auth state
localStorage.removeItem('authToken')
setUser(null)
} finally {
setIsLoading(false)
}
}
// Debug database schema
const debugSchema = async () => {
try {
const response = await fetch('/api/debug/schema')
const debug = await response.json()
console.log('Database schema info:', debug)
} catch (e) {
console.log('Schema debug failed:', e)
}
}
// Debug user lookup
const debugUser = async (userId: string) => {
try {
const response = await fetch('/api/debug/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId })
})
const debug = await response.json()
console.log('User debug info:', debug)
} catch (e) {
console.log('User debug failed:', e)
}
}
// Debug token validation
const debugToken = async (token: string) => {
try {
const response = await fetch('/api/debug/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token })
})
const debug = await response.json()
console.log('Token debug info:', debug)
// Log more details about the token payload
if (debug.payload) {
console.log('Token payload:', debug.payload)
// Debug user lookup
if (debug.payload.userId) {
debugUser(debug.payload.userId)
}
}
if (debug.verificationResult) {
console.log('Verification result:', debug.verificationResult)
}
} catch (e) {
console.log('Token debug failed:', e)
}
}
// Clear expired tokens and sync state immediately on mount
useEffect(() => {
if (typeof window !== 'undefined') {
const token = localStorage.getItem('authToken')
console.log('Auth mount check - token exists:', !!token)
if (token) {
console.log('Token preview:', token.substring(0, 50) + '...')
// Debug the database schema and token on server side
debugSchema()
debugToken(token)
const expired = isTokenExpired(token)
console.log('Token expired:', expired)
if (expired) {
console.log('Clearing expired token and user state on mount')
localStorage.removeItem('authToken')
setUser(null)
}
} else if (user) {
console.log('No token but user exists in store, clearing user state')
setUser(null)
}
clearExpiredToken()
}
}, [])
// Initialize auth state only once on mount
useEffect(() => {
if (!initialized && typeof window !== 'undefined') {
const token = localStorage.getItem('authToken')
console.log('Initialization flow - token exists:', !!token)
if (token) {
// Check if token is expired before making request
if (isTokenExpired(token)) {
console.log('Token expired during initialization, clearing auth state')
localStorage.removeItem('authToken')
setUser(null)
setIsLoading(false)
} else {
console.log('Token is valid, calling refreshUser()')
// Token appears valid, try to refresh user data
// refreshUser will handle server-side validation failures
refreshUser()
}
} else {
console.log('No token found, clearing user state')
// No token, clear any stale user data
setUser(null)
setIsLoading(false)
}
setInitialized(true)
}
}, [initialized])
// Handle hydration issues - ensure we stop loading once initialized
useEffect(() => {
if (initialized && isLoading) {
const token = localStorage.getItem('authToken')
if (!token) {
setIsLoading(false)
}
}
}, [initialized, isLoading])
const login = async (email: string, password: string): Promise<{ success: boolean; error?: string }> => {
try {
const response = await fetch(`/api/auth/login?locale=${locale}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (response.ok) {
localStorage.setItem('authToken', data.token)
setUser(data.user)
return { success: true }
} else {
return { success: false, error: data.error }
}
} catch (error) {
console.error('Login error:', error)
return {
success: false,
error: locale === 'en' ? 'Login failed' : 'Autentificare eșuată'
}
}
}
const register = async (email: string, password: string, name?: string): Promise<{ success: boolean; error?: string }> => {
try {
const response = await fetch(`/api/auth/register?locale=${locale}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password, name }),
})
const data = await response.json()
if (response.ok) {
localStorage.setItem('authToken', data.token)
setUser(data.user)
return { success: true }
} else {
return { success: false, error: data.error }
}
} catch (error) {
console.error('Registration error:', error)
return {
success: false,
error: locale === 'en' ? 'Registration failed' : 'Înregistrare eșuată'
}
}
}
const logout = async () => {
try {
const token = localStorage.getItem('authToken')
if (token) {
await fetch('/api/auth/logout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
}
})
}
} catch (error) {
console.error('Logout error:', error)
} finally {
localStorage.removeItem('authToken')
setUser(null)
}
}
const value: AuthContextType = {
user,
isAuthenticated: !!user,
isLoading,
login,
register,
logout,
refreshUser: () => refreshUser(true)
}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
export function useAuth(): AuthContextType {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}

View File

@@ -1,7 +1,23 @@
'use client'
import { useState } from 'react'
import { useStore } from '@/lib/store'
import { useTranslations } from 'next-intl'
import { useAuth } from './auth-provider'
import {
Box,
TextField,
Button,
Alert,
CircularProgress,
InputAdornment,
IconButton
} from '@mui/material'
import {
Email,
Lock,
Visibility,
VisibilityOff
} from '@mui/icons-material'
interface LoginFormProps {
onSuccess?: () => void
@@ -12,7 +28,9 @@ export function LoginForm({ onSuccess }: LoginFormProps) {
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const { setUser } = useStore()
const [showPassword, setShowPassword] = useState(false)
const { login } = useAuth()
const t = useTranslations('auth')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -20,74 +38,94 @@ export function LoginForm({ onSuccess }: LoginFormProps) {
setError('')
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
})
const result = await login(email, password)
const data = await response.json()
if (!response.ok) {
setError(data.error || 'Eroare la autentificare')
return
}
// Store user and token
setUser(data.user)
localStorage.setItem('authToken', data.token)
if (onSuccess) {
onSuccess()
if (result.success) {
if (onSuccess) {
onSuccess()
}
} else {
setError(result.error || t('loginError'))
}
} catch (error) {
setError('Eroare de conexiune')
setError(t('connectionError'))
} finally {
setLoading(false)
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required
/>
</div>
const handleClickShowPassword = () => {
setShowPassword(!showPassword)
}
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
Parolă
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
required
/>
</div>
return (
<Box component="form" onSubmit={handleSubmit} sx={{ width: '100%' }}>
<TextField
fullWidth
type="email"
label={t('email')}
value={email}
onChange={(e) => setEmail(e.target.value)}
required
margin="normal"
variant="outlined"
disabled={loading}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Email color="action" />
</InputAdornment>
),
}}
/>
<TextField
fullWidth
type={showPassword ? 'text' : 'password'}
label={t('password')}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
margin="normal"
variant="outlined"
disabled={loading}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Lock color="action" />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
edge="end"
disabled={loading}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
{error && (
<div className="text-red-600 text-sm">{error}</div>
<Alert severity="error" sx={{ mt: 2 }}>
{error}
</Alert>
)}
<button
<Button
type="submit"
fullWidth
variant="contained"
disabled={loading}
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
sx={{ mt: 3, mb: 2, py: 1.5 }}
startIcon={loading ? <CircularProgress size={20} color="inherit" /> : undefined}
>
{loading ? 'Se autentifică...' : 'Autentificare'}
</button>
</form>
{loading ? t('logging_in') : t('login')}
</Button>
</Box>
)
}

View File

@@ -0,0 +1,48 @@
'use client'
import { ReactNode, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useLocale } from 'next-intl'
import { useAuth } from './auth-provider'
import { Box, CircularProgress, Typography } from '@mui/material'
interface ProtectedRouteProps {
children: ReactNode
fallback?: ReactNode
}
export function ProtectedRoute({ children, fallback }: ProtectedRouteProps) {
const { isAuthenticated, isLoading } = useAuth()
const router = useRouter()
const locale = useLocale()
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push(`/${locale}/login`)
}
}, [isAuthenticated, isLoading, router, locale])
if (isLoading) {
return fallback || (
<Box
display="flex"
flexDirection="column"
alignItems="center"
justifyContent="center"
minHeight="60vh"
gap={2}
>
<CircularProgress />
<Typography variant="body2" color="text.secondary">
Loading...
</Typography>
</Box>
)
}
if (!isAuthenticated) {
return null
}
return <>{children}</>
}

View File

@@ -0,0 +1,200 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useAuth } from './auth-provider'
import {
Box,
TextField,
Button,
Alert,
CircularProgress,
InputAdornment,
IconButton
} from '@mui/material'
import {
Email,
Lock,
Person,
Visibility,
VisibilityOff
} from '@mui/icons-material'
interface RegisterFormProps {
onSuccess?: () => void
}
export function RegisterForm({ onSuccess }: RegisterFormProps) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [name, setName] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
const { register } = useAuth()
const t = useTranslations('auth')
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
setError('')
if (password !== confirmPassword) {
setError(t('passwordMismatch'))
setLoading(false)
return
}
try {
const result = await register(email, password, name || undefined)
if (result.success) {
if (onSuccess) {
onSuccess()
}
} else {
setError(result.error || t('registerError'))
}
} catch (error) {
setError(t('connectionError'))
} finally {
setLoading(false)
}
}
const handleClickShowPassword = () => {
setShowPassword(!showPassword)
}
const handleClickShowConfirmPassword = () => {
setShowConfirmPassword(!showConfirmPassword)
}
return (
<Box component="form" onSubmit={handleSubmit} sx={{ width: '100%' }}>
<TextField
fullWidth
type="text"
label={`${t('name')} ${t('optional')}`}
value={name}
onChange={(e) => setName(e.target.value)}
margin="normal"
variant="outlined"
disabled={loading}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Person color="action" />
</InputAdornment>
),
}}
/>
<TextField
fullWidth
type="email"
label={t('email')}
value={email}
onChange={(e) => setEmail(e.target.value)}
required
margin="normal"
variant="outlined"
disabled={loading}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Email color="action" />
</InputAdornment>
),
}}
/>
<TextField
fullWidth
type={showPassword ? 'text' : 'password'}
label={t('password')}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
margin="normal"
variant="outlined"
disabled={loading}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Lock color="action" />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
edge="end"
disabled={loading}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<TextField
fullWidth
type={showConfirmPassword ? 'text' : 'password'}
label={t('confirmPassword')}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
margin="normal"
variant="outlined"
disabled={loading}
error={confirmPassword !== '' && password !== confirmPassword}
helperText={
confirmPassword !== '' && password !== confirmPassword
? t('passwordMismatch')
: ''
}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Lock color="action" />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label="toggle confirm password visibility"
onClick={handleClickShowConfirmPassword}
edge="end"
disabled={loading}
>
{showConfirmPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
{error && (
<Alert severity="error" sx={{ mt: 2 }}>
{error}
</Alert>
)}
<Button
type="submit"
fullWidth
variant="contained"
disabled={loading || (password !== confirmPassword && confirmPassword !== '')}
sx={{ mt: 3, mb: 2, py: 1.5 }}
startIcon={loading ? <CircularProgress size={20} color="inherit" /> : undefined}
>
{loading ? t('registering') : t('register')}
</Button>
</Box>
)
}