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:
133
app/[locale]/auth/login/page.tsx
Normal file
133
app/[locale]/auth/login/page.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import {
|
||||
Container,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
Tabs,
|
||||
Tab,
|
||||
Link,
|
||||
Card,
|
||||
CardContent,
|
||||
Divider
|
||||
} from '@mui/material'
|
||||
import {
|
||||
MenuBook,
|
||||
Login as LoginIcon,
|
||||
PersonAdd
|
||||
} from '@mui/icons-material'
|
||||
import { LoginForm } from '@/components/auth/login-form'
|
||||
import { RegisterForm } from '@/components/auth/register-form'
|
||||
|
||||
export default function AuthPage() {
|
||||
const [activeTab, setActiveTab] = useState(0)
|
||||
const router = useRouter()
|
||||
const locale = useLocale()
|
||||
const t = useTranslations('auth')
|
||||
|
||||
const handleAuthSuccess = () => {
|
||||
router.push(`/${locale}`)
|
||||
}
|
||||
|
||||
const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
|
||||
setActiveTab(newValue)
|
||||
}
|
||||
|
||||
const getSubtitle = () => {
|
||||
if (locale === 'en') {
|
||||
return activeTab === 0
|
||||
? 'Sign in to continue exploring Scripture'
|
||||
: 'Create an account to begin your spiritual journey'
|
||||
}
|
||||
return activeTab === 0
|
||||
? 'Conectează-te pentru a continua explorarea Scripturii'
|
||||
: 'Creează un cont pentru a începe călătoria ta spirituală'
|
||||
}
|
||||
|
||||
return (
|
||||
<Container maxWidth="sm" sx={{ py: 4, minHeight: '100vh', display: 'flex', alignItems: 'center' }}>
|
||||
<Card elevation={8} sx={{ width: '100%', borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 4 }}>
|
||||
{/* Header */}
|
||||
<Box textAlign="center" mb={4}>
|
||||
<Box display="flex" justifyContent="center" mb={2}>
|
||||
<MenuBook sx={{ fontSize: 48, color: 'primary.main' }} />
|
||||
</Box>
|
||||
<Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
|
||||
{activeTab === 0 ? t('welcomeBack') : t('joinUs')}
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
{getSubtitle()}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Divider sx={{ mb: 3 }} />
|
||||
|
||||
{/* Tabs */}
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onChange={handleTabChange}
|
||||
centered
|
||||
sx={{
|
||||
mb: 3,
|
||||
'& .MuiTab-root': {
|
||||
minWidth: 120,
|
||||
fontWeight: 600
|
||||
}
|
||||
}}
|
||||
TabIndicatorProps={{
|
||||
style: { height: 3, borderRadius: 3 }
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
icon={<LoginIcon />}
|
||||
iconPosition="start"
|
||||
label={t('login')}
|
||||
/>
|
||||
<Tab
|
||||
icon={<PersonAdd />}
|
||||
iconPosition="start"
|
||||
label={t('register')}
|
||||
/>
|
||||
</Tabs>
|
||||
|
||||
{/* Forms */}
|
||||
<Box sx={{ minHeight: 300 }}>
|
||||
{activeTab === 0 ? (
|
||||
<LoginForm onSuccess={handleAuthSuccess} />
|
||||
) : (
|
||||
<RegisterForm onSuccess={handleAuthSuccess} />
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Divider sx={{ my: 3 }} />
|
||||
|
||||
{/* Switch Form Link */}
|
||||
<Box textAlign="center">
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{activeTab === 0 ? t('noAccount') : t('alreadyHaveAccount')}{' '}
|
||||
<Link
|
||||
component="button"
|
||||
variant="body2"
|
||||
onClick={() => setActiveTab(activeTab === 0 ? 1 : 0)}
|
||||
sx={{
|
||||
textDecoration: 'none',
|
||||
fontWeight: 600,
|
||||
'&:hover': {
|
||||
textDecoration: 'underline'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{activeTab === 0 ? t('createAccount') : t('login')}
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Container>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl'
|
||||
import { getMessages } from 'next-intl/server'
|
||||
import { notFound } from 'next/navigation'
|
||||
import { MuiThemeProvider } from '@/components/providers/theme-provider'
|
||||
import { AuthProvider } from '@/components/auth/auth-provider'
|
||||
import { Navigation } from '@/components/layout/navigation'
|
||||
import FloatingChat from '@/components/chat/floating-chat'
|
||||
import { merriweather, lato } from '@/lib/fonts'
|
||||
@@ -45,9 +46,11 @@ export default async function LocaleLayout({
|
||||
<body className={`${merriweather.variable} ${lato.variable}`}>
|
||||
<NextIntlClientProvider messages={messages} locale={locale}>
|
||||
<MuiThemeProvider>
|
||||
<Navigation />
|
||||
{children}
|
||||
<FloatingChat />
|
||||
<AuthProvider>
|
||||
<Navigation />
|
||||
{children}
|
||||
<FloatingChat />
|
||||
</AuthProvider>
|
||||
</MuiThemeProvider>
|
||||
</NextIntlClientProvider>
|
||||
</body>
|
||||
|
||||
32
app/[locale]/login/page.tsx
Normal file
32
app/[locale]/login/page.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useLocale } from 'next-intl'
|
||||
import { Box, CircularProgress, Typography } from '@mui/material'
|
||||
|
||||
export default function LoginRedirectPage() {
|
||||
const router = useRouter()
|
||||
const locale = useLocale()
|
||||
|
||||
useEffect(() => {
|
||||
// Redirect to the actual login page
|
||||
router.replace(`/${locale}/auth/login`)
|
||||
}, [router, locale])
|
||||
|
||||
return (
|
||||
<Box
|
||||
display="flex"
|
||||
flexDirection="column"
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
minHeight="100vh"
|
||||
gap={2}
|
||||
>
|
||||
<CircularProgress />
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Redirecting to login...
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
220
app/[locale]/profile/page.tsx
Normal file
220
app/[locale]/profile/page.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useAuth } from '@/hooks/use-auth'
|
||||
import { ProtectedRoute } from '@/components/auth/protected-route'
|
||||
import {
|
||||
Container,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
TextField,
|
||||
Button,
|
||||
Avatar,
|
||||
Grid,
|
||||
Card,
|
||||
CardContent,
|
||||
Divider,
|
||||
Alert,
|
||||
CircularProgress
|
||||
} from '@mui/material'
|
||||
import {
|
||||
Person,
|
||||
Email,
|
||||
AdminPanelSettings,
|
||||
Save,
|
||||
Edit
|
||||
} from '@mui/icons-material'
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { user } = useAuth()
|
||||
const t = useTranslations('profile')
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [name, setName] = useState(user?.name || '')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
const handleSave = async () => {
|
||||
setLoading(true)
|
||||
setMessage('')
|
||||
|
||||
try {
|
||||
// TODO: Implement profile update API
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)) // Placeholder
|
||||
setMessage(t('profileUpdated'))
|
||||
setIsEditing(false)
|
||||
} catch (error) {
|
||||
setMessage(t('updateError'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setName(user?.name || '')
|
||||
setIsEditing(false)
|
||||
}
|
||||
|
||||
const getRoleTranslation = (role: string) => {
|
||||
switch (role) {
|
||||
case 'admin':
|
||||
return t('admin')
|
||||
case 'moderator':
|
||||
return t('moderator')
|
||||
default:
|
||||
return t('user')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<Container maxWidth="md" sx={{ py: 4 }}>
|
||||
<Paper elevation={3} sx={{ p: 4 }}>
|
||||
{/* Header */}
|
||||
<Box textAlign="center" mb={4}>
|
||||
<Avatar
|
||||
sx={{
|
||||
width: 100,
|
||||
height: 100,
|
||||
fontSize: 40,
|
||||
mx: 'auto',
|
||||
mb: 2,
|
||||
bgcolor: 'primary.main'
|
||||
}}
|
||||
>
|
||||
{user?.name ? user.name.charAt(0).toUpperCase() : <Person />}
|
||||
</Avatar>
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
{t('title')}
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
{t('subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Divider sx={{ mb: 4 }} />
|
||||
|
||||
{/* Profile Information */}
|
||||
<Grid container spacing={3}>
|
||||
{/* Personal Information Card */}
|
||||
<Grid item xs={12} md={8}>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
|
||||
<Typography variant="h6" component="h2">
|
||||
{t('personalInfo')}
|
||||
</Typography>
|
||||
{!isEditing && (
|
||||
<Button
|
||||
startIcon={<Edit />}
|
||||
onClick={() => setIsEditing(true)}
|
||||
variant="outlined"
|
||||
size="small"
|
||||
>
|
||||
{t('edit')}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('name')}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={!isEditing || loading}
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
InputProps={{
|
||||
startAdornment: <Person sx={{ mr: 1, color: 'action.active' }} />
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label={t('email')}
|
||||
value={user?.email || ''}
|
||||
disabled
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
InputProps={{
|
||||
startAdornment: <Email sx={{ mr: 1, color: 'action.active' }} />
|
||||
}}
|
||||
helperText={t('emailCannotChange')}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{isEditing && (
|
||||
<Box display="flex" gap={2} mt={3}>
|
||||
<Button
|
||||
variant="contained"
|
||||
startIcon={loading ? <CircularProgress size={20} /> : <Save />}
|
||||
onClick={handleSave}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? t('saving') : t('save')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
onClick={handleCancel}
|
||||
disabled={loading}
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
|
||||
{/* Account Details Card */}
|
||||
<Grid item xs={12} md={4}>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Typography variant="h6" component="h2" gutterBottom>
|
||||
{t('accountDetails')}
|
||||
</Typography>
|
||||
|
||||
<Box display="flex" alignItems="center" mb={2}>
|
||||
<AdminPanelSettings sx={{ mr: 1, color: 'action.active' }} />
|
||||
<Box>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{t('role')}
|
||||
</Typography>
|
||||
<Typography variant="body1">
|
||||
{getRoleTranslation(user?.role || 'user')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{t('memberSince')}
|
||||
</Typography>
|
||||
<Typography variant="body1">
|
||||
{new Date().toLocaleDateString()} {/* TODO: Use actual creation date */}
|
||||
</Typography>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Success/Error Message */}
|
||||
{message && (
|
||||
<Alert
|
||||
severity={message.includes(t('updateError')) ? 'error' : 'success'}
|
||||
sx={{ mt: 3 }}
|
||||
onClose={() => setMessage('')}
|
||||
>
|
||||
{message}
|
||||
</Alert>
|
||||
)}
|
||||
</Paper>
|
||||
</Container>
|
||||
</ProtectedRoute>
|
||||
)
|
||||
}
|
||||
230
app/[locale]/settings/page.tsx
Normal file
230
app/[locale]/settings/page.tsx
Normal file
@@ -0,0 +1,230 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import { useAuth } from '@/hooks/use-auth'
|
||||
import { ProtectedRoute } from '@/components/auth/protected-route'
|
||||
import {
|
||||
Container,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
Switch,
|
||||
FormControlLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Grid,
|
||||
Card,
|
||||
CardContent,
|
||||
Divider,
|
||||
Alert,
|
||||
Button
|
||||
} from '@mui/material'
|
||||
import {
|
||||
Settings as SettingsIcon,
|
||||
Palette,
|
||||
TextFields,
|
||||
Language,
|
||||
Notifications,
|
||||
Security,
|
||||
Save
|
||||
} from '@mui/icons-material'
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { user } = useAuth()
|
||||
const locale = useLocale()
|
||||
const t = useTranslations('settings')
|
||||
const [settings, setSettings] = useState({
|
||||
theme: user?.theme || 'light',
|
||||
fontSize: user?.fontSize || 'medium',
|
||||
notifications: true,
|
||||
emailUpdates: false,
|
||||
language: locale
|
||||
})
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
const handleSettingChange = (setting: string, value: any) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
[setting]: value
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
// TODO: Implement settings update API
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)) // Placeholder
|
||||
setMessage(t('settingsSaved'))
|
||||
} catch (error) {
|
||||
setMessage(t('settingsError'))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<Container maxWidth="md" sx={{ py: 4 }}>
|
||||
<Paper elevation={3} sx={{ p: 4 }}>
|
||||
{/* Header */}
|
||||
<Box textAlign="center" mb={4}>
|
||||
<SettingsIcon sx={{ fontSize: 48, color: 'primary.main', mb: 2 }} />
|
||||
<Typography variant="h4" component="h1" gutterBottom>
|
||||
{t('title')}
|
||||
</Typography>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
{t('subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Divider sx={{ mb: 4 }} />
|
||||
|
||||
<Grid container spacing={3}>
|
||||
{/* Appearance Settings */}
|
||||
<Grid item xs={12} md={6}>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box display="flex" alignItems="center" mb={3}>
|
||||
<Palette sx={{ mr: 1, color: 'primary.main' }} />
|
||||
<Typography variant="h6">
|
||||
{t('appearance')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>{t('theme')}</InputLabel>
|
||||
<Select
|
||||
value={settings.theme}
|
||||
label={t('theme')}
|
||||
onChange={(e) => handleSettingChange('theme', e.target.value)}
|
||||
>
|
||||
<MenuItem value="light">{t('themes.light')}</MenuItem>
|
||||
<MenuItem value="dark">{t('themes.dark')}</MenuItem>
|
||||
<MenuItem value="auto">{t('themes.auto')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>{t('fontSize')}</InputLabel>
|
||||
<Select
|
||||
value={settings.fontSize}
|
||||
label={t('fontSize')}
|
||||
onChange={(e) => handleSettingChange('fontSize', e.target.value)}
|
||||
startAdornment={<TextFields sx={{ mr: 1 }} />}
|
||||
>
|
||||
<MenuItem value="small">{t('fontSizes.small')}</MenuItem>
|
||||
<MenuItem value="medium">{t('fontSizes.medium')}</MenuItem>
|
||||
<MenuItem value="large">{t('fontSizes.large')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
|
||||
{/* Language & Notifications */}
|
||||
<Grid item xs={12} md={6}>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box display="flex" alignItems="center" mb={3}>
|
||||
<Language sx={{ mr: 1, color: 'primary.main' }} />
|
||||
<Typography variant="h6">
|
||||
{t('languageAndNotifications')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>{t('language')}</InputLabel>
|
||||
<Select
|
||||
value={settings.language}
|
||||
label={t('language')}
|
||||
onChange={(e) => handleSettingChange('language', e.target.value)}
|
||||
>
|
||||
<MenuItem value="ro">{t('languages.ro')}</MenuItem>
|
||||
<MenuItem value="en">{t('languages.en')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.notifications}
|
||||
onChange={(e) => handleSettingChange('notifications', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={t('notifications')}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.emailUpdates}
|
||||
onChange={(e) => handleSettingChange('emailUpdates', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={t('emailUpdates')}
|
||||
/>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
|
||||
{/* Security Settings */}
|
||||
<Grid item xs={12}>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box display="flex" alignItems="center" mb={3}>
|
||||
<Security sx={{ mr: 1, color: 'primary.main' }} />
|
||||
<Typography variant="h6">
|
||||
{t('security')}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
|
||||
{t('passwordSecurity')}
|
||||
</Typography>
|
||||
|
||||
<Button variant="outlined" disabled>
|
||||
{t('changePasswordSoon')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Save Button */}
|
||||
<Box textAlign="center" mt={4}>
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
onClick={handleSave}
|
||||
sx={{ px: 4 }}
|
||||
>
|
||||
{t('saveSettings')}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{/* Success/Error Message */}
|
||||
{message && (
|
||||
<Alert
|
||||
severity={message.includes(t('settingsError')) ? 'error' : 'success'}
|
||||
sx={{ mt: 3 }}
|
||||
onClose={() => setMessage('')}
|
||||
>
|
||||
{message}
|
||||
</Alert>
|
||||
)}
|
||||
</Paper>
|
||||
</Container>
|
||||
</ProtectedRoute>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +1,50 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateUser, generateToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { createUserLoginSchema } from '@/lib/validation'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
fieldsRequired: 'Email și parola sunt obligatorii',
|
||||
invalidCredentials: 'Email sau parolă incorectă',
|
||||
serverError: 'Eroare de server',
|
||||
invalidInput: 'Date de intrare invalide'
|
||||
},
|
||||
en: {
|
||||
fieldsRequired: 'Email and password are required',
|
||||
invalidCredentials: 'Invalid email or password',
|
||||
serverError: 'Server error',
|
||||
invalidInput: 'Invalid input data'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { email, password } = await request.json()
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
const body = await request.json()
|
||||
const { email, password } = body
|
||||
|
||||
// Validation
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ error: 'Email și parola sunt obligatorii' }, { status: 400 })
|
||||
const loginSchema = createUserLoginSchema(locale)
|
||||
const result = loginSchema.safeParse({ email, password })
|
||||
|
||||
if (!result.success) {
|
||||
const errors = result.error.errors.map(err => err.message).join(', ')
|
||||
return NextResponse.json({ error: errors }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate user
|
||||
const user = await validateUser(email, password)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Email sau parolă incorectă' }, { status: 401 })
|
||||
return NextResponse.json({ error: messages.invalidCredentials }, { status: 401 })
|
||||
}
|
||||
|
||||
// Generate token
|
||||
@@ -38,11 +66,14 @@ export async function POST(request: Request) {
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
user: { id: user.id, email: user.email, name: user.name },
|
||||
user: { id: user.id, email: user.email, name: user.name, role: user.role, theme: user.theme, fontSize: user.fontSize },
|
||||
token
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
return NextResponse.json({ error: messages.serverError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
23
app/api/auth/logout/route.ts
Normal file
23
app/api/auth/logout/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (token) {
|
||||
// Remove the session from database
|
||||
await prisma.session.deleteMany({
|
||||
where: { token }
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error)
|
||||
return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,46 @@ import { getUserFromToken } from '@/lib/auth'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
tokenRequired: 'Token de autentificare necesar',
|
||||
invalidToken: 'Token invalid',
|
||||
serverError: 'Eroare de server'
|
||||
},
|
||||
en: {
|
||||
tokenRequired: 'Authentication token required',
|
||||
invalidToken: 'Invalid token',
|
||||
serverError: 'Server error'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const token = authHeader?.replace('Bearer ', '')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: 'Token de autentificare necesar' }, { status: 401 })
|
||||
return NextResponse.json({ error: messages.tokenRequired }, { status: 401 })
|
||||
}
|
||||
|
||||
const user = await getUserFromToken(token)
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Token invalid' }, { status: 401 })
|
||||
return NextResponse.json({ error: messages.invalidToken }, { status: 401 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ user })
|
||||
} catch (error) {
|
||||
console.error('User validation error:', error)
|
||||
return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
return NextResponse.json({ error: messages.serverError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,38 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createUser, generateToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
import { userRegistrationSchema } from '@/lib/validation'
|
||||
import { createUserRegistrationSchema } from '@/lib/validation'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function getErrorMessages(locale: string = 'ro') {
|
||||
const messages = {
|
||||
ro: {
|
||||
userExists: 'Utilizatorul există deja',
|
||||
serverError: 'Eroare de server',
|
||||
invalidInput: 'Date de intrare invalide'
|
||||
},
|
||||
en: {
|
||||
userExists: 'User already exists',
|
||||
serverError: 'Server error',
|
||||
invalidInput: 'Invalid input data'
|
||||
}
|
||||
}
|
||||
return messages[locale as keyof typeof messages] || messages.ro
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Validate input
|
||||
const result = userRegistrationSchema.safeParse(body)
|
||||
const registrationSchema = createUserRegistrationSchema(locale)
|
||||
const result = registrationSchema.safeParse(body)
|
||||
if (!result.success) {
|
||||
const errors = result.error.errors.map(err => err.message).join(', ')
|
||||
return NextResponse.json({ error: errors }, { status: 400 })
|
||||
@@ -22,7 +43,7 @@ export async function POST(request: Request) {
|
||||
// Check if user exists
|
||||
const existing = await prisma.user.findUnique({ where: { email } })
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'Utilizatorul există deja' }, { status: 409 })
|
||||
return NextResponse.json({ error: messages.userExists }, { status: 409 })
|
||||
}
|
||||
|
||||
// Create user
|
||||
@@ -39,14 +60,18 @@ export async function POST(request: Request) {
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
user: { id: user.id, email: user.email, name: user.name },
|
||||
user: { id: user.id, email: user.email, name: user.name, role: user.role, theme: user.theme, fontSize: user.fontSize },
|
||||
token
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error)
|
||||
const url = new URL(request.url)
|
||||
const locale = url.searchParams.get('locale') || 'ro'
|
||||
const messages = getErrorMessages(locale)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: 'Date de intrare invalide' }, { status: 400 })
|
||||
return NextResponse.json({ error: messages.invalidInput }, { status: 400 })
|
||||
}
|
||||
return NextResponse.json({ error: 'Eroare de server' }, { status: 500 })
|
||||
return NextResponse.json({ error: messages.serverError }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
35
app/api/debug/schema/route.ts
Normal file
35
app/api/debug/schema/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Get table structure for User table
|
||||
const tableInfo = await prisma.$queryRaw`
|
||||
SELECT column_name, data_type, is_nullable, column_default
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'User' AND table_schema = 'public'
|
||||
ORDER BY ordinal_position;
|
||||
`
|
||||
|
||||
// Also try to get one user record to see what fields are actually there
|
||||
let sampleUser = null
|
||||
try {
|
||||
sampleUser = await prisma.$queryRaw`SELECT * FROM "User" LIMIT 1;`
|
||||
} catch (e) {
|
||||
sampleUser = { error: 'Could not fetch sample user: ' + e.message }
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
tableStructure: tableInfo,
|
||||
sampleUser: sampleUser
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Schema debug error:', error)
|
||||
return NextResponse.json({
|
||||
error: 'Schema debug failed',
|
||||
details: error.message
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
53
app/api/debug/token/route.ts
Normal file
53
app/api/debug/token/route.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import jwt from 'jsonwebtoken'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { token } = await request.json()
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: 'Token required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Log environment info
|
||||
const hasSecret = !!process.env.JWT_SECRET
|
||||
const secretPreview = process.env.JWT_SECRET ? process.env.JWT_SECRET.substring(0, 10) + '...' : 'MISSING'
|
||||
|
||||
console.log('Debug: JWT_SECRET exists:', hasSecret)
|
||||
console.log('Debug: JWT_SECRET preview:', secretPreview)
|
||||
|
||||
// Try to decode without verification first
|
||||
let decodedWithoutVerification
|
||||
try {
|
||||
decodedWithoutVerification = jwt.decode(token, { complete: true })
|
||||
console.log('Debug: Token decoded without verification:', !!decodedWithoutVerification)
|
||||
} catch (e) {
|
||||
console.log('Debug: Token decode failed:', e.message)
|
||||
}
|
||||
|
||||
// Try to verify
|
||||
let verificationResult
|
||||
try {
|
||||
verificationResult = jwt.verify(token, process.env.JWT_SECRET!)
|
||||
console.log('Debug: Token verification successful')
|
||||
} catch (e) {
|
||||
console.log('Debug: Token verification failed:', e.message)
|
||||
verificationResult = { error: e.message }
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
hasSecret,
|
||||
secretPreview,
|
||||
decodedWithoutVerification: !!decodedWithoutVerification,
|
||||
payload: decodedWithoutVerification?.payload,
|
||||
verificationResult: typeof verificationResult === 'object' && 'error' in verificationResult
|
||||
? verificationResult
|
||||
: { success: true, payload: verificationResult }
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Debug endpoint error:', error)
|
||||
return NextResponse.json({ error: 'Debug failed' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
43
app/api/debug/user/route.ts
Normal file
43
app/api/debug/user/route.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { userId } = await request.json()
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: 'userId required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Use raw query to avoid Prisma client sync issues
|
||||
const users = await prisma.$queryRaw`
|
||||
SELECT id, email, name, role, theme, "fontSize", "createdAt", "updatedAt", "lastLoginAt"
|
||||
FROM "User"
|
||||
WHERE id = ${userId}
|
||||
`
|
||||
const user = Array.isArray(users) && users.length > 0 ? users[0] : null
|
||||
|
||||
// Also get a count of all users
|
||||
const userCount = await prisma.user.count()
|
||||
|
||||
// Get all user IDs for comparison
|
||||
const allUsers = await prisma.user.findMany({
|
||||
select: { id: true, email: true, createdAt: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 5
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
searchedUserId: userId,
|
||||
userExists: !!user,
|
||||
user: user || null,
|
||||
totalUsers: userCount,
|
||||
recentUsers: allUsers
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('User debug error:', error)
|
||||
return NextResponse.json({ error: 'Debug failed', details: error.message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user