Compare commits
6 Commits
70121982a0
...
a8962247fb
| Author | SHA1 | Date | |
|---|---|---|---|
| a8962247fb | |||
| 0bb293e101 | |||
| 2ebda95207 | |||
| d4a5232e71 | |||
| 895ceba55f | |||
| 211ed50503 |
@@ -41,7 +41,7 @@
|
||||
- **Property 5: Password length validation**
|
||||
- **Validates: Requirements 1.5**
|
||||
|
||||
- [ ] 4. Implement authentication functionality
|
||||
- [x] 4. Implement authentication functionality
|
||||
- Create login server action with credential validation
|
||||
- Implement password verification with bcrypt
|
||||
- Create session on successful login
|
||||
@@ -56,7 +56,7 @@
|
||||
- **Property 7: Invalid credentials rejection**
|
||||
- **Validates: Requirements 2.2**
|
||||
|
||||
- [ ] 5. Implement session management
|
||||
- [x] 5. Implement session management
|
||||
- Configure JWT session strategy in NextAuth
|
||||
- Implement session validation middleware
|
||||
- Create logout functionality
|
||||
@@ -83,20 +83,20 @@
|
||||
- **Property 12: Session duration persistence**
|
||||
- **Validates: Requirements 3.4**
|
||||
|
||||
- [ ] 6. Create authentication UI components
|
||||
- [x] 6. Create authentication UI components
|
||||
- Build LoginForm component with email/password inputs
|
||||
- Build RegisterForm component with validation
|
||||
- Create authentication error display page
|
||||
- Add loading states and error handling
|
||||
- _Requirements: 1.1, 2.1_
|
||||
|
||||
- [ ] 7. Implement route protection middleware
|
||||
- [x] 7. Implement route protection middleware
|
||||
- Create Next.js middleware for authentication checks
|
||||
- Protect main routes (/, /list/*, /profile/*)
|
||||
- Redirect unauthenticated users to login
|
||||
- _Requirements: 3.3, 3.5_
|
||||
|
||||
- [ ] 8. Update list operations for ownership
|
||||
- [x] 8. Update list operations for ownership
|
||||
- Modify createList to assign ownerId
|
||||
- Update getLists to filter by user access
|
||||
- Add ownership checks to updateList and deleteList
|
||||
@@ -119,7 +119,7 @@
|
||||
- **Property 16: Account deletion cascades to lists**
|
||||
- **Validates: Requirements 4.5**
|
||||
|
||||
- [ ] 9. Implement permission utilities
|
||||
- [x] 9. Implement permission utilities
|
||||
- Create canAccessList function
|
||||
- Create canEditList function
|
||||
- Create canDeleteList function
|
||||
|
||||
109
app/auth/error/page.tsx
Normal file
109
app/auth/error/page.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
'use client'
|
||||
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { Suspense } from 'react'
|
||||
|
||||
function ErrorContent() {
|
||||
const searchParams = useSearchParams()
|
||||
const error = searchParams.get('error')
|
||||
|
||||
const getErrorMessage = (errorCode: string | null) => {
|
||||
switch (errorCode) {
|
||||
case 'Configuration':
|
||||
return 'There is a problem with the server configuration.'
|
||||
case 'AccessDenied':
|
||||
return 'You do not have permission to sign in.'
|
||||
case 'Verification':
|
||||
return 'The verification token has expired or has already been used.'
|
||||
case 'OAuthSignin':
|
||||
return 'Error in constructing an authorization URL.'
|
||||
case 'OAuthCallback':
|
||||
return 'Error in handling the response from an OAuth provider.'
|
||||
case 'OAuthCreateAccount':
|
||||
return 'Could not create OAuth provider user in the database.'
|
||||
case 'EmailCreateAccount':
|
||||
return 'Could not create email provider user in the database.'
|
||||
case 'Callback':
|
||||
return 'Error in the OAuth callback handler route.'
|
||||
case 'OAuthAccountNotLinked':
|
||||
return 'Email on the account is already linked, but not with this OAuth account.'
|
||||
case 'EmailSignin':
|
||||
return 'Sending the email with the verification token failed.'
|
||||
case 'CredentialsSignin':
|
||||
return 'Invalid email or password. Please check your credentials and try again.'
|
||||
case 'SessionRequired':
|
||||
return 'Please sign in to access this page.'
|
||||
default:
|
||||
return 'An authentication error occurred. Please try again.'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div className="text-center">
|
||||
<div className="mx-auto h-16 w-16 flex items-center justify-center rounded-full bg-red-100 mb-4">
|
||||
<svg
|
||||
className="h-8 w-8 text-red-600"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
|
||||
Authentication Error
|
||||
</h1>
|
||||
<p className="text-sm sm:text-base text-gray-600 mb-8">
|
||||
{getErrorMessage(error)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
|
||||
<div className="space-y-4">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="block w-full px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors text-center font-medium text-sm sm:text-base"
|
||||
>
|
||||
Try Logging In Again
|
||||
</Link>
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="block w-full px-4 py-3 bg-gray-100 hover:bg-gray-200 active:bg-gray-300 text-gray-700 rounded-lg transition-colors text-center font-medium text-sm sm:text-base"
|
||||
>
|
||||
Create New Account
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-6 p-4 bg-gray-50 rounded-lg">
|
||||
<p className="text-xs text-gray-500">
|
||||
Error code: <code className="font-mono">{error}</code>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function AuthErrorPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-gray-600">Loading...</div>
|
||||
</div>
|
||||
}>
|
||||
<ErrorContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
53
app/auth/login/page.tsx
Normal file
53
app/auth/login/page.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import Link from 'next/link'
|
||||
import LoginForm from '@/components/LoginForm'
|
||||
import { Suspense } from 'react'
|
||||
|
||||
export const metadata = {
|
||||
title: 'Login - Ultimate Lists',
|
||||
description: 'Log in to your Ultimate Lists account',
|
||||
}
|
||||
|
||||
function LoginContent() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div className="text-center">
|
||||
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
|
||||
Welcome Back
|
||||
</h1>
|
||||
<p className="text-sm sm:text-base text-gray-600">
|
||||
Log in to access your lists
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
|
||||
<LoginForm />
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-sm text-gray-600">
|
||||
Don't have an account?{' '}
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 transition-colors"
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-gray-600">Loading...</div>
|
||||
</div>
|
||||
}>
|
||||
<LoginContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
53
app/auth/register/page.tsx
Normal file
53
app/auth/register/page.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import Link from 'next/link'
|
||||
import RegisterForm from '@/components/RegisterForm'
|
||||
import { Suspense } from 'react'
|
||||
|
||||
export const metadata = {
|
||||
title: 'Register - Ultimate Lists',
|
||||
description: 'Create your Ultimate Lists account',
|
||||
}
|
||||
|
||||
function RegisterContent() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div className="text-center">
|
||||
<h1 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-2">
|
||||
Create Account
|
||||
</h1>
|
||||
<p className="text-sm sm:text-base text-gray-600">
|
||||
Sign up to start organizing your tasks
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl shadow-md p-6 sm:p-8">
|
||||
<RegisterForm />
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-sm text-gray-600">
|
||||
Already have an account?{' '}
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 transition-colors"
|
||||
>
|
||||
Log in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function RegisterPage() {
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-gray-600">Loading...</div>
|
||||
</div>
|
||||
}>
|
||||
<RegisterContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import ItemForm from '@/components/ItemForm'
|
||||
import Link from 'next/link'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
|
||||
@@ -6,6 +6,8 @@ import { ArrowLeft, Edit } from 'lucide-react'
|
||||
import DeleteItemButton from '@/components/DeleteItemButton'
|
||||
import ToggleItemButton from '@/components/ToggleItemButton'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
|
||||
@@ -5,6 +5,8 @@ import { ArrowLeft } from 'lucide-react'
|
||||
import InlineItemCreate from '@/components/InlineItemCreate'
|
||||
import ListDetailView from '@/components/ListDetailView'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export default async function ListDetailPage({ params }: { params: { id: string } }) {
|
||||
const list = await getListWithItems(params.id)
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import NewListButton from '@/components/NewListButton'
|
||||
import GlobalSearch from '@/components/GlobalSearch'
|
||||
import EmptyState from '@/components/EmptyState'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export default async function Home() {
|
||||
const lists = await getLists()
|
||||
|
||||
|
||||
15
auth.ts
15
auth.ts
@@ -13,6 +13,8 @@ const loginSchema = z.object({
|
||||
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
|
||||
updateAge: 24 * 60 * 60, // Update session every 24 hours
|
||||
},
|
||||
providers: [
|
||||
Credentials({
|
||||
@@ -57,18 +59,27 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
async jwt({ token, user, trigger }) {
|
||||
// Add user ID to token on sign in
|
||||
if (user) {
|
||||
token.id = user.id
|
||||
}
|
||||
|
||||
// Handle session expiration
|
||||
// Token will be automatically invalidated by NextAuth when it expires
|
||||
// based on the maxAge setting in session config
|
||||
|
||||
return token
|
||||
},
|
||||
async session({ session, token }) {
|
||||
// Add user ID to session from token
|
||||
if (session.user) {
|
||||
if (session.user && token.id) {
|
||||
session.user.id = token.id as string
|
||||
}
|
||||
|
||||
// Session validation happens automatically via JWT expiration
|
||||
// If token is expired, this callback won't be called and user will be redirected
|
||||
|
||||
return session
|
||||
},
|
||||
},
|
||||
|
||||
179
components/LoginForm.tsx
Normal file
179
components/LoginForm.tsx
Normal file
@@ -0,0 +1,179 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { signIn } from 'next-auth/react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { validateEmail, validatePassword } from '@/lib/validation'
|
||||
import { useToast } from './ToastContainer'
|
||||
|
||||
interface LoginFormProps {
|
||||
callbackUrl?: string
|
||||
}
|
||||
|
||||
export default function LoginForm({ callbackUrl = '/' }: LoginFormProps) {
|
||||
const router = useRouter()
|
||||
const { showToast } = useToast()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [errors, setErrors] = useState<{ email?: string; password?: string }>({})
|
||||
const [touched, setTouched] = useState<{ email: boolean; password: boolean }>({
|
||||
email: false,
|
||||
password: false,
|
||||
})
|
||||
|
||||
// Inline validation when fields change
|
||||
useEffect(() => {
|
||||
if (touched.email) {
|
||||
const result = validateEmail(email)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
email: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
}, [email, touched.email])
|
||||
|
||||
useEffect(() => {
|
||||
if (touched.password) {
|
||||
const result = validatePassword(password)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
password: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
}, [password, touched.password])
|
||||
|
||||
const handleEmailBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, email: true }))
|
||||
const result = validateEmail(email)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
email: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
|
||||
const handlePasswordBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, password: true }))
|
||||
const result = validatePassword(password)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
password: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
// Validate all fields before submission
|
||||
const emailResult = validateEmail(email)
|
||||
const passwordResult = validatePassword(password)
|
||||
|
||||
const newErrors: { email?: string; password?: string } = {}
|
||||
if (!emailResult.isValid) {
|
||||
newErrors.email = emailResult.error
|
||||
}
|
||||
if (!passwordResult.isValid) {
|
||||
newErrors.password = passwordResult.error
|
||||
}
|
||||
|
||||
if (Object.keys(newErrors).length > 0) {
|
||||
setErrors(newErrors)
|
||||
setTouched({ email: true, password: true })
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
setErrors({})
|
||||
|
||||
try {
|
||||
const result = await signIn('credentials', {
|
||||
email: email.trim(),
|
||||
password,
|
||||
redirect: false,
|
||||
})
|
||||
|
||||
if (result?.error) {
|
||||
showToast('Invalid email or password', 'error')
|
||||
setErrors({ email: 'Invalid credentials', password: 'Invalid credentials' })
|
||||
} else if (result?.ok) {
|
||||
showToast('Login successful', 'success')
|
||||
router.push(callbackUrl)
|
||||
router.refresh()
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login error:', err)
|
||||
showToast('An error occurred. Please try again.', 'error')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Email *
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
onBlur={handleEmailBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.email && touched.email
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="Enter your email"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="email"
|
||||
autoFocus
|
||||
aria-invalid={errors.email && touched.email ? 'true' : 'false'}
|
||||
aria-describedby={errors.email && touched.email ? 'email-error' : undefined}
|
||||
/>
|
||||
{errors.email && touched.email && (
|
||||
<p id="email-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Password *
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onBlur={handlePasswordBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.password && touched.password
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="Enter your password"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="current-password"
|
||||
aria-invalid={errors.password && touched.password ? 'true' : 'false'}
|
||||
aria-describedby={errors.password && touched.password ? 'password-error' : undefined}
|
||||
/>
|
||||
{errors.password && touched.password && (
|
||||
<p id="password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.password}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="w-full px-4 sm:px-5 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
|
||||
>
|
||||
{isSubmitting ? 'Logging in...' : 'Log In'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
300
components/RegisterForm.tsx
Normal file
300
components/RegisterForm.tsx
Normal file
@@ -0,0 +1,300 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { validateEmail, validatePassword, sanitizeString } from '@/lib/validation'
|
||||
import { registerUser } from '@/lib/auth-actions'
|
||||
import { useToast } from './ToastContainer'
|
||||
|
||||
interface RegisterFormProps {
|
||||
callbackUrl?: string
|
||||
}
|
||||
|
||||
export default function RegisterForm({ callbackUrl = '/' }: RegisterFormProps) {
|
||||
const router = useRouter()
|
||||
const { showToast } = useToast()
|
||||
const [name, setName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [errors, setErrors] = useState<{
|
||||
name?: string
|
||||
email?: string
|
||||
password?: string
|
||||
confirmPassword?: string
|
||||
}>({})
|
||||
const [touched, setTouched] = useState<{
|
||||
name: boolean
|
||||
email: boolean
|
||||
password: boolean
|
||||
confirmPassword: boolean
|
||||
}>({
|
||||
name: false,
|
||||
email: false,
|
||||
password: false,
|
||||
confirmPassword: false,
|
||||
})
|
||||
|
||||
// Inline validation when fields change
|
||||
useEffect(() => {
|
||||
if (touched.name) {
|
||||
const sanitized = sanitizeString(name)
|
||||
if (!sanitized) {
|
||||
setErrors((prev) => ({ ...prev, name: 'Name is required' }))
|
||||
} else if (sanitized.length > 100) {
|
||||
setErrors((prev) => ({ ...prev, name: 'Name must be less than 100 characters' }))
|
||||
} else {
|
||||
setErrors((prev) => ({ ...prev, name: undefined }))
|
||||
}
|
||||
}
|
||||
}, [name, touched.name])
|
||||
|
||||
useEffect(() => {
|
||||
if (touched.email) {
|
||||
const result = validateEmail(email)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
email: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
}, [email, touched.email])
|
||||
|
||||
useEffect(() => {
|
||||
if (touched.password) {
|
||||
const result = validatePassword(password)
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
password: result.isValid ? undefined : result.error,
|
||||
}))
|
||||
}
|
||||
}, [password, touched.password])
|
||||
|
||||
useEffect(() => {
|
||||
if (touched.confirmPassword) {
|
||||
if (!confirmPassword) {
|
||||
setErrors((prev) => ({ ...prev, confirmPassword: 'Please confirm your password' }))
|
||||
} else if (password !== confirmPassword) {
|
||||
setErrors((prev) => ({ ...prev, confirmPassword: 'Passwords do not match' }))
|
||||
} else {
|
||||
setErrors((prev) => ({ ...prev, confirmPassword: undefined }))
|
||||
}
|
||||
}
|
||||
}, [confirmPassword, password, touched.confirmPassword])
|
||||
|
||||
const handleNameBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, name: true }))
|
||||
}
|
||||
|
||||
const handleEmailBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, email: true }))
|
||||
}
|
||||
|
||||
const handlePasswordBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, password: true }))
|
||||
}
|
||||
|
||||
const handleConfirmPasswordBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, confirmPassword: true }))
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
// Validate all fields before submission
|
||||
const sanitizedName = sanitizeString(name)
|
||||
const emailResult = validateEmail(email)
|
||||
const passwordResult = validatePassword(password)
|
||||
|
||||
const newErrors: {
|
||||
name?: string
|
||||
email?: string
|
||||
password?: string
|
||||
confirmPassword?: string
|
||||
} = {}
|
||||
|
||||
if (!sanitizedName) {
|
||||
newErrors.name = 'Name is required'
|
||||
} else if (sanitizedName.length > 100) {
|
||||
newErrors.name = 'Name must be less than 100 characters'
|
||||
}
|
||||
|
||||
if (!emailResult.isValid) {
|
||||
newErrors.email = emailResult.error
|
||||
}
|
||||
|
||||
if (!passwordResult.isValid) {
|
||||
newErrors.password = passwordResult.error
|
||||
}
|
||||
|
||||
if (!confirmPassword) {
|
||||
newErrors.confirmPassword = 'Please confirm your password'
|
||||
} else if (password !== confirmPassword) {
|
||||
newErrors.confirmPassword = 'Passwords do not match'
|
||||
}
|
||||
|
||||
if (Object.keys(newErrors).length > 0) {
|
||||
setErrors(newErrors)
|
||||
setTouched({ name: true, email: true, password: true, confirmPassword: true })
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
setErrors({})
|
||||
|
||||
try {
|
||||
const result = await registerUser(email.trim(), password, sanitizedName)
|
||||
|
||||
if (!result.success) {
|
||||
if (result.error === 'Email already exists') {
|
||||
setErrors({ email: 'This email is already registered' })
|
||||
showToast('Email already exists', 'error')
|
||||
} else {
|
||||
showToast(result.error || 'Registration failed', 'error')
|
||||
}
|
||||
} else {
|
||||
showToast('Registration successful! Logging you in...', 'success')
|
||||
router.push(callbackUrl)
|
||||
router.refresh()
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Registration error:', err)
|
||||
showToast('An error occurred. Please try again.', 'error')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Name *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleNameBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.name && touched.name
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="Enter your name"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="name"
|
||||
autoFocus
|
||||
maxLength={100}
|
||||
aria-invalid={errors.name && touched.name ? 'true' : 'false'}
|
||||
aria-describedby={errors.name && touched.name ? 'name-error' : undefined}
|
||||
/>
|
||||
{errors.name && touched.name && (
|
||||
<p id="name-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Email *
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
onBlur={handleEmailBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.email && touched.email
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="Enter your email"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="email"
|
||||
aria-invalid={errors.email && touched.email ? 'true' : 'false'}
|
||||
aria-describedby={errors.email && touched.email ? 'email-error' : undefined}
|
||||
/>
|
||||
{errors.email && touched.email && (
|
||||
<p id="email-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Password *
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onBlur={handlePasswordBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.password && touched.password
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="At least 8 characters"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="new-password"
|
||||
aria-invalid={errors.password && touched.password ? 'true' : 'false'}
|
||||
aria-describedby={errors.password && touched.password ? 'password-error' : undefined}
|
||||
/>
|
||||
{errors.password && touched.password && (
|
||||
<p id="password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.password}
|
||||
</p>
|
||||
)}
|
||||
{!errors.password && touched.password && (
|
||||
<p className="mt-1.5 text-xs sm:text-sm text-gray-500">
|
||||
Password must be at least 8 characters
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Confirm Password *
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
id="confirmPassword"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
onBlur={handleConfirmPasswordBlur}
|
||||
className={`w-full px-3 sm:px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 text-sm sm:text-base ${
|
||||
errors.confirmPassword && touched.confirmPassword
|
||||
? 'border-red-500 focus:ring-red-500'
|
||||
: 'border-gray-300 focus:ring-blue-500'
|
||||
}`}
|
||||
placeholder="Re-enter your password"
|
||||
disabled={isSubmitting}
|
||||
autoComplete="new-password"
|
||||
aria-invalid={errors.confirmPassword && touched.confirmPassword ? 'true' : 'false'}
|
||||
aria-describedby={
|
||||
errors.confirmPassword && touched.confirmPassword ? 'confirm-password-error' : undefined
|
||||
}
|
||||
/>
|
||||
{errors.confirmPassword && touched.confirmPassword && (
|
||||
<p id="confirm-password-error" className="mt-1.5 text-xs sm:text-sm text-red-600">
|
||||
{errors.confirmPassword}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="w-full px-4 sm:px-5 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 tap-target font-medium text-sm sm:text-base"
|
||||
>
|
||||
{isSubmitting ? 'Creating account...' : 'Create Account'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -14,7 +14,8 @@ vi.mock('@/auth', () => ({
|
||||
}))
|
||||
|
||||
// Import after mocking
|
||||
import { registerUser } from '../auth-actions'
|
||||
import { registerUser, loginUser } from '../auth-actions'
|
||||
import { signIn } from '@/auth'
|
||||
|
||||
describe('registerUser', () => {
|
||||
// Clean up test users after each test
|
||||
@@ -125,3 +126,97 @@ describe('registerUser', () => {
|
||||
expect(user?.name).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('loginUser', () => {
|
||||
// Clean up test users after each test
|
||||
afterEach(async () => {
|
||||
await prisma.user.deleteMany({
|
||||
where: {
|
||||
email: {
|
||||
contains: 'test-login-',
|
||||
},
|
||||
},
|
||||
})
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should successfully login with valid credentials', async () => {
|
||||
const email = `test-login-${Date.now()}@example.com`
|
||||
const password = 'password123'
|
||||
|
||||
// Create a test user first
|
||||
await registerUser(email, password, 'Test User')
|
||||
|
||||
// Mock signIn to succeed
|
||||
vi.mocked(signIn).mockResolvedValueOnce(undefined as any)
|
||||
|
||||
// Attempt login
|
||||
const result = await loginUser(email, password)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(signIn).toHaveBeenCalledWith('credentials', {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('should reject login with invalid credentials', async () => {
|
||||
const email = `test-login-${Date.now()}@example.com`
|
||||
const password = 'password123'
|
||||
|
||||
// Create a test user first
|
||||
await registerUser(email, password, 'Test User')
|
||||
|
||||
// Mock signIn to throw error (invalid credentials)
|
||||
vi.mocked(signIn).mockRejectedValueOnce(new Error('Invalid credentials'))
|
||||
|
||||
// Attempt login with wrong password
|
||||
const result = await loginUser(email, 'wrongpassword')
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Invalid email or password')
|
||||
}
|
||||
})
|
||||
|
||||
it('should reject login with non-existent email', async () => {
|
||||
const email = `test-login-nonexistent-${Date.now()}@example.com`
|
||||
const password = 'password123'
|
||||
|
||||
// Mock signIn to throw error (user not found)
|
||||
vi.mocked(signIn).mockRejectedValueOnce(new Error('User not found'))
|
||||
|
||||
// Attempt login with non-existent email
|
||||
const result = await loginUser(email, password)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Invalid email or password')
|
||||
}
|
||||
})
|
||||
|
||||
it('should reject login with invalid email format', async () => {
|
||||
const email = 'invalid-email'
|
||||
const password = 'password123'
|
||||
|
||||
const result = await loginUser(email, password)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Invalid email')
|
||||
}
|
||||
})
|
||||
|
||||
it('should reject login with empty password', async () => {
|
||||
const email = `test-login-${Date.now()}@example.com`
|
||||
const password = ''
|
||||
|
||||
const result = await loginUser(email, password)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Password is required')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
121
lib/__tests__/middleware.test.ts
Normal file
121
lib/__tests__/middleware.test.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
/**
|
||||
* Middleware Route Protection Tests
|
||||
*
|
||||
* These tests verify the route protection logic defined in middleware.ts
|
||||
* Testing the actual middleware requires mocking NextAuth which is complex,
|
||||
* so we test the route matching logic here.
|
||||
*/
|
||||
|
||||
describe('Middleware Route Protection Logic', () => {
|
||||
// Helper to check if a path is a protected route
|
||||
const isProtectedRoute = (pathname: string): boolean => {
|
||||
return (
|
||||
pathname === "/" ||
|
||||
pathname.startsWith("/list") ||
|
||||
pathname.startsWith("/profile") ||
|
||||
pathname.startsWith("/invitations")
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to check if a path is an auth page
|
||||
const isAuthPage = (pathname: string): boolean => {
|
||||
return pathname.startsWith("/auth")
|
||||
}
|
||||
|
||||
describe('Protected Routes', () => {
|
||||
it('should identify root path as protected', () => {
|
||||
expect(isProtectedRoute("/")).toBe(true)
|
||||
})
|
||||
|
||||
it('should identify list routes as protected', () => {
|
||||
expect(isProtectedRoute("/list")).toBe(true)
|
||||
expect(isProtectedRoute("/list/123")).toBe(true)
|
||||
expect(isProtectedRoute("/list/123/item/456")).toBe(true)
|
||||
})
|
||||
|
||||
it('should identify profile routes as protected', () => {
|
||||
expect(isProtectedRoute("/profile")).toBe(true)
|
||||
expect(isProtectedRoute("/profile/settings")).toBe(true)
|
||||
})
|
||||
|
||||
it('should identify invitations routes as protected', () => {
|
||||
expect(isProtectedRoute("/invitations")).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Auth Pages', () => {
|
||||
it('should identify login page as auth page', () => {
|
||||
expect(isAuthPage("/auth/login")).toBe(true)
|
||||
})
|
||||
|
||||
it('should identify register page as auth page', () => {
|
||||
expect(isAuthPage("/auth/register")).toBe(true)
|
||||
})
|
||||
|
||||
it('should identify error page as auth page', () => {
|
||||
expect(isAuthPage("/auth/error")).toBe(true)
|
||||
})
|
||||
|
||||
it('should not identify non-auth pages as auth pages', () => {
|
||||
expect(isAuthPage("/")).toBe(false)
|
||||
expect(isAuthPage("/list/123")).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Route Classification', () => {
|
||||
it('should correctly classify various routes', () => {
|
||||
// Protected routes
|
||||
expect(isProtectedRoute("/")).toBe(true)
|
||||
expect(isProtectedRoute("/list/abc123")).toBe(true)
|
||||
expect(isProtectedRoute("/profile")).toBe(true)
|
||||
|
||||
// Auth pages (not protected, but special handling)
|
||||
expect(isAuthPage("/auth/login")).toBe(true)
|
||||
expect(isAuthPage("/auth/register")).toBe(true)
|
||||
|
||||
// Public routes (not protected)
|
||||
expect(isProtectedRoute("/api/auth/signin")).toBe(false)
|
||||
expect(isProtectedRoute("/offline")).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Middleware Matcher Pattern', () => {
|
||||
// Test that the matcher pattern would correctly exclude certain paths
|
||||
const shouldBeExcludedByMatcher = (pathname: string): boolean => {
|
||||
// Based on the matcher config in middleware.ts
|
||||
return (
|
||||
pathname.startsWith("/api") ||
|
||||
pathname.startsWith("/_next/static") ||
|
||||
pathname.startsWith("/_next/image") ||
|
||||
pathname === "/favicon.ico" ||
|
||||
/\.(svg|png|jpg|jpeg|gif|webp|ico|json|js)$/.test(pathname)
|
||||
)
|
||||
}
|
||||
|
||||
it('should exclude API routes from middleware', () => {
|
||||
expect(shouldBeExcludedByMatcher("/api/lists")).toBe(true)
|
||||
expect(shouldBeExcludedByMatcher("/api/auth/signin")).toBe(true)
|
||||
})
|
||||
|
||||
it('should exclude static files from middleware', () => {
|
||||
expect(shouldBeExcludedByMatcher("/_next/static/chunks/main.js")).toBe(true)
|
||||
expect(shouldBeExcludedByMatcher("/_next/image/logo.png")).toBe(true)
|
||||
})
|
||||
|
||||
it('should exclude public assets from middleware', () => {
|
||||
expect(shouldBeExcludedByMatcher("/favicon.ico")).toBe(true)
|
||||
expect(shouldBeExcludedByMatcher("/icon-192.png")).toBe(true)
|
||||
expect(shouldBeExcludedByMatcher("/manifest.json")).toBe(true)
|
||||
expect(shouldBeExcludedByMatcher("/sw.js")).toBe(true)
|
||||
})
|
||||
|
||||
it('should not exclude regular pages from middleware', () => {
|
||||
expect(shouldBeExcludedByMatcher("/")).toBe(false)
|
||||
expect(shouldBeExcludedByMatcher("/list/123")).toBe(false)
|
||||
expect(shouldBeExcludedByMatcher("/auth/login")).toBe(false)
|
||||
expect(shouldBeExcludedByMatcher("/profile")).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
268
lib/__tests__/permissions.test.ts
Normal file
268
lib/__tests__/permissions.test.ts
Normal file
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* Tests for permission utility functions
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '../db'
|
||||
import {
|
||||
canAccessList,
|
||||
canEditList,
|
||||
canDeleteList,
|
||||
getPermission,
|
||||
} from '../permissions'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
describe('Permission Utilities', () => {
|
||||
let testUser1Id: string
|
||||
let testUser2Id: string
|
||||
let testListId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
// Create test users
|
||||
const passwordHash = await bcrypt.hash('password123', 10)
|
||||
|
||||
const user1 = await prisma.user.create({
|
||||
data: {
|
||||
email: `test-perm-user1-${Date.now()}@example.com`,
|
||||
passwordHash,
|
||||
name: 'Test User 1',
|
||||
},
|
||||
})
|
||||
testUser1Id = user1.id
|
||||
|
||||
const user2 = await prisma.user.create({
|
||||
data: {
|
||||
email: `test-perm-user2-${Date.now()}@example.com`,
|
||||
passwordHash,
|
||||
name: 'Test User 2',
|
||||
},
|
||||
})
|
||||
testUser2Id = user2.id
|
||||
|
||||
// Create a test list owned by user1
|
||||
const list = await prisma.list.create({
|
||||
data: {
|
||||
title: 'Test List',
|
||||
color: '#3B82F6',
|
||||
ownerId: testUser1Id,
|
||||
},
|
||||
})
|
||||
testListId = list.id
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up test data
|
||||
await prisma.list.deleteMany({
|
||||
where: {
|
||||
id: testListId,
|
||||
},
|
||||
})
|
||||
await prisma.user.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: [testUser1Id, testUser2Id],
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('canAccessList', () => {
|
||||
it('should return true for list owner', async () => {
|
||||
const result = await canAccessList(testUser1Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false for non-owner without collaboration', async () => {
|
||||
const result = await canAccessList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return true for editor collaborator', async () => {
|
||||
// Add user2 as editor
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canAccessList(testUser2Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return true for viewer collaborator', async () => {
|
||||
// Add user2 as viewer
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'viewer',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canAccessList(testUser2Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false for invalid user ID', async () => {
|
||||
const result = await canAccessList('', testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for invalid list ID', async () => {
|
||||
const result = await canAccessList(testUser1Id, '')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canEditList', () => {
|
||||
it('should return true for list owner', async () => {
|
||||
const result = await canEditList(testUser1Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false for non-owner without collaboration', async () => {
|
||||
const result = await canEditList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return true for editor collaborator', async () => {
|
||||
// Add user2 as editor
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canEditList(testUser2Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false for viewer collaborator', async () => {
|
||||
// Add user2 as viewer
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'viewer',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canEditList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for invalid user ID', async () => {
|
||||
const result = await canEditList('', testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for invalid list ID', async () => {
|
||||
const result = await canEditList(testUser1Id, '')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canDeleteList', () => {
|
||||
it('should return true for list owner', async () => {
|
||||
const result = await canDeleteList(testUser1Id, testListId)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false for non-owner', async () => {
|
||||
const result = await canDeleteList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for editor collaborator', async () => {
|
||||
// Add user2 as editor
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canDeleteList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for viewer collaborator', async () => {
|
||||
// Add user2 as viewer
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'viewer',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await canDeleteList(testUser2Id, testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for invalid user ID', async () => {
|
||||
const result = await canDeleteList('', testListId)
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false for invalid list ID', async () => {
|
||||
const result = await canDeleteList(testUser1Id, '')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPermission', () => {
|
||||
it('should return "owner" for list owner', async () => {
|
||||
const result = await getPermission(testUser1Id, testListId)
|
||||
expect(result).toBe('owner')
|
||||
})
|
||||
|
||||
it('should return null for non-owner without collaboration', async () => {
|
||||
const result = await getPermission(testUser2Id, testListId)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return "editor" for editor collaborator', async () => {
|
||||
// Add user2 as editor
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await getPermission(testUser2Id, testListId)
|
||||
expect(result).toBe('editor')
|
||||
})
|
||||
|
||||
it('should return "viewer" for viewer collaborator', async () => {
|
||||
// Add user2 as viewer
|
||||
await prisma.collaborator.create({
|
||||
data: {
|
||||
userId: testUser2Id,
|
||||
listId: testListId,
|
||||
permission: 'viewer',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await getPermission(testUser2Id, testListId)
|
||||
expect(result).toBe('viewer')
|
||||
})
|
||||
|
||||
it('should return null for invalid user ID', async () => {
|
||||
const result = await getPermission('', testListId)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null for invalid list ID', async () => {
|
||||
const result = await getPermission(testUser1Id, '')
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
427
lib/actions.ts
427
lib/actions.ts
@@ -2,6 +2,7 @@
|
||||
|
||||
import { prisma } from './db'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { auth } from '@/auth'
|
||||
import {
|
||||
validateListTitle,
|
||||
validateItemTitle,
|
||||
@@ -47,10 +48,49 @@ async function retryOperation<T>(
|
||||
|
||||
export async function getLists() {
|
||||
try {
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to view lists')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Get lists where user is owner or collaborator
|
||||
return await retryOperation(() =>
|
||||
prisma.list.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
items: true,
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
collaborators: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
updatedAt: 'desc',
|
||||
@@ -59,12 +99,23 @@ export async function getLists() {
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Error fetching lists:', error)
|
||||
if (error instanceof Error && error.message.includes('Unauthorized')) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to load lists. Please check your connection and try again.')
|
||||
}
|
||||
}
|
||||
|
||||
export async function createList(title: string, color: string = '#3B82F6') {
|
||||
try {
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to create lists')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Validate and sanitize input
|
||||
const titleResult = validateListTitle(title)
|
||||
if (!titleResult.isValid) {
|
||||
@@ -83,6 +134,7 @@ export async function createList(title: string, color: string = '#3B82F6') {
|
||||
data: {
|
||||
title: sanitizedTitle,
|
||||
color,
|
||||
ownerId: userId,
|
||||
},
|
||||
})
|
||||
)
|
||||
@@ -91,7 +143,7 @@ export async function createList(title: string, color: string = '#3B82F6') {
|
||||
return list
|
||||
} catch (error) {
|
||||
console.error('Error creating list:', error)
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be'))) {
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be') || error.message.includes('Unauthorized'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to create list. Please try again.')
|
||||
@@ -104,27 +156,65 @@ export async function getListWithItems(listId: string) {
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to view lists')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
const list = await retryOperation(() =>
|
||||
prisma.list.findUnique({
|
||||
where: { id: listId },
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
items: {
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
},
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
collaborators: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!list) {
|
||||
throw new Error('List not found')
|
||||
throw new Error('List not found or access denied')
|
||||
}
|
||||
|
||||
return list
|
||||
} catch (error) {
|
||||
console.error('Error fetching list:', error)
|
||||
if (error instanceof Error && error.message === 'List not found') {
|
||||
if (error instanceof Error && (error.message === 'List not found or access denied' || error.message.includes('Unauthorized'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to load list. Please try again.')
|
||||
@@ -137,11 +227,40 @@ export async function getItem(itemId: string) {
|
||||
throw new Error('Item ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to view items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
prisma.item.findUnique({
|
||||
where: { id: itemId },
|
||||
include: {
|
||||
list: true,
|
||||
list: {
|
||||
include: {
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
collaborators: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
@@ -150,10 +269,18 @@ export async function getItem(itemId: string) {
|
||||
throw new Error('Item not found')
|
||||
}
|
||||
|
||||
// Check if user has access to the parent list
|
||||
const hasAccess = item.list.ownerId === userId ||
|
||||
item.list.collaborators.some(c => c.userId === userId)
|
||||
|
||||
if (!hasAccess) {
|
||||
throw new Error('You do not have permission to view this item')
|
||||
}
|
||||
|
||||
return item
|
||||
} catch (error) {
|
||||
console.error('Error fetching item:', error)
|
||||
if (error instanceof Error && error.message === 'Item not found') {
|
||||
if (error instanceof Error && (error.message === 'Item not found' || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to load item. Please try again.')
|
||||
@@ -177,6 +304,38 @@ export async function createItem(
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to create items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Check if user has access to the list (owner or editor)
|
||||
const list = await retryOperation(() =>
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!list) {
|
||||
throw new Error('List not found or you do not have permission to add items')
|
||||
}
|
||||
|
||||
const titleResult = validateItemTitle(title)
|
||||
if (!titleResult.isValid) {
|
||||
throw new Error(titleResult.error)
|
||||
@@ -214,7 +373,7 @@ export async function createItem(
|
||||
return item
|
||||
} catch (error) {
|
||||
console.error('Error creating item:', error)
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be') || error.message.includes('Invalid'))) {
|
||||
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be') || error.message.includes('Invalid') || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to create item. Please try again.')
|
||||
@@ -227,14 +386,49 @@ export async function toggleItem(itemId: string) {
|
||||
throw new Error('Item ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to update items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
prisma.item.findUnique({ where: { id: itemId } })
|
||||
prisma.item.findUnique({
|
||||
where: { id: itemId },
|
||||
include: { list: true },
|
||||
})
|
||||
)
|
||||
|
||||
if (!item) {
|
||||
throw new Error('Item not found')
|
||||
}
|
||||
|
||||
// Check if user has access to the parent list (owner or editor)
|
||||
const hasAccess = await retryOperation(() =>
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: item.listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!hasAccess) {
|
||||
throw new Error('You do not have permission to update this item')
|
||||
}
|
||||
|
||||
const updated = await retryOperation(() =>
|
||||
prisma.item.update({
|
||||
where: { id: itemId },
|
||||
@@ -246,7 +440,7 @@ export async function toggleItem(itemId: string) {
|
||||
return updated
|
||||
} catch (error) {
|
||||
console.error('Error toggling item:', error)
|
||||
if (error instanceof Error && error.message === 'Item not found') {
|
||||
if (error instanceof Error && (error.message === 'Item not found' || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to update item. Please try again.')
|
||||
@@ -270,6 +464,14 @@ export async function updateItem(
|
||||
throw new Error('Item ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to update items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Validate and sanitize title if provided
|
||||
if (data.title !== undefined) {
|
||||
const titleResult = validateItemTitle(data.title)
|
||||
@@ -299,12 +501,39 @@ export async function updateItem(
|
||||
}
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
prisma.item.findUnique({ where: { id: itemId } })
|
||||
prisma.item.findUnique({
|
||||
where: { id: itemId },
|
||||
include: { list: true },
|
||||
})
|
||||
)
|
||||
|
||||
if (!item) {
|
||||
throw new Error('Item not found')
|
||||
}
|
||||
|
||||
// Check if user has access to the parent list (owner or editor)
|
||||
const hasAccess = await retryOperation(() =>
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: item.listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!hasAccess) {
|
||||
throw new Error('You do not have permission to update this item')
|
||||
}
|
||||
|
||||
const updated = await retryOperation(() =>
|
||||
prisma.item.update({
|
||||
@@ -317,7 +546,7 @@ export async function updateItem(
|
||||
return updated
|
||||
} catch (error) {
|
||||
console.error('Error updating item:', error)
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid'))) {
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid') || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to update item. Please try again.')
|
||||
@@ -330,13 +559,48 @@ export async function deleteItem(itemId: string) {
|
||||
throw new Error('Item ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to delete items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
const item = await retryOperation(() =>
|
||||
prisma.item.findUnique({ where: { id: itemId } })
|
||||
prisma.item.findUnique({
|
||||
where: { id: itemId },
|
||||
include: { list: true },
|
||||
})
|
||||
)
|
||||
|
||||
if (!item) {
|
||||
throw new Error('Item not found')
|
||||
}
|
||||
|
||||
// Check if user has access to the parent list (owner or editor)
|
||||
const hasAccess = await retryOperation(() =>
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: item.listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!hasAccess) {
|
||||
throw new Error('You do not have permission to delete this item')
|
||||
}
|
||||
|
||||
await retryOperation(() =>
|
||||
prisma.item.delete({
|
||||
@@ -348,7 +612,7 @@ export async function deleteItem(itemId: string) {
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Error deleting item:', error)
|
||||
if (error instanceof Error && error.message === 'Item not found') {
|
||||
if (error instanceof Error && (error.message === 'Item not found' || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to delete item. Please try again.')
|
||||
@@ -361,13 +625,26 @@ export async function deleteList(listId: string) {
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
// Check if list exists
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to delete lists')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Check if list exists and user is the owner (only owners can delete)
|
||||
const list = await retryOperation(() =>
|
||||
prisma.list.findUnique({ where: { id: listId } })
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
ownerId: userId,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!list) {
|
||||
throw new Error('List not found')
|
||||
throw new Error('List not found or you do not have permission to delete it')
|
||||
}
|
||||
|
||||
await retryOperation(() =>
|
||||
@@ -380,7 +657,7 @@ export async function deleteList(listId: string) {
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Error deleting list:', error)
|
||||
if (error instanceof Error && error.message === 'List not found') {
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to delete list. Please try again.')
|
||||
@@ -399,6 +676,38 @@ export async function updateList(
|
||||
throw new Error('List ID is required')
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to update lists')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Check if user has access to the list (owner or editor)
|
||||
const list = await retryOperation(() =>
|
||||
prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
if (!list) {
|
||||
throw new Error('List not found or you do not have permission to update it')
|
||||
}
|
||||
|
||||
// Validate and sanitize title if provided
|
||||
if (data.title !== undefined) {
|
||||
const titleResult = validateListTitle(data.title)
|
||||
@@ -428,7 +737,7 @@ export async function updateList(
|
||||
return updated
|
||||
} catch (error) {
|
||||
console.error('Error updating list:', error)
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid'))) {
|
||||
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be') || error.message.includes('Invalid') || error.message.includes('Unauthorized') || error.message.includes('permission'))) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to update list. Please try again.')
|
||||
@@ -440,6 +749,14 @@ export async function searchItems(query: string, listId?: string) {
|
||||
if (!query || !query.trim()) {
|
||||
return []
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to search items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
const searchTerm = query.toLowerCase()
|
||||
|
||||
@@ -465,6 +782,18 @@ export async function searchItems(query: string, listId?: string) {
|
||||
},
|
||||
},
|
||||
],
|
||||
list: {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
// Add list scope if specified
|
||||
@@ -485,15 +814,30 @@ export async function searchItems(query: string, listId?: string) {
|
||||
)
|
||||
|
||||
// Also search in tags (stored as JSON)
|
||||
const allItemsWhere: any = {
|
||||
list: {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
if (listId) {
|
||||
allItemsWhere.listId = listId
|
||||
}
|
||||
|
||||
const allItems = await retryOperation(() =>
|
||||
listId
|
||||
? prisma.item.findMany({
|
||||
where: { listId },
|
||||
include: { list: true },
|
||||
})
|
||||
: prisma.item.findMany({
|
||||
include: { list: true },
|
||||
})
|
||||
prisma.item.findMany({
|
||||
where: allItemsWhere,
|
||||
include: { list: true },
|
||||
})
|
||||
)
|
||||
|
||||
const tagMatches = allItems.filter((item) => {
|
||||
@@ -512,6 +856,9 @@ export async function searchItems(query: string, listId?: string) {
|
||||
return uniqueResults
|
||||
} catch (error) {
|
||||
console.error('Error searching items:', error)
|
||||
if (error instanceof Error && error.message.includes('Unauthorized')) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to search items. Please try again.')
|
||||
}
|
||||
}
|
||||
@@ -530,8 +877,29 @@ export async function getItemsByFilter(
|
||||
} = {}
|
||||
) {
|
||||
try {
|
||||
// Get current user session
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('Unauthorized: Please log in to filter items')
|
||||
}
|
||||
|
||||
const userId = session.user.id
|
||||
|
||||
// Build the where clause with compound filters (AND logic)
|
||||
const whereClause: any = {}
|
||||
const whereClause: any = {
|
||||
list: {
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
// Add list scope if specified
|
||||
if (listId) {
|
||||
@@ -644,6 +1012,9 @@ export async function getItemsByFilter(
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error filtering items:', error)
|
||||
if (error instanceof Error && error.message.includes('Unauthorized')) {
|
||||
throw error
|
||||
}
|
||||
throw new Error('Failed to filter items. Please try again.')
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { prisma } from './db'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { z } from 'zod'
|
||||
import { signIn } from '@/auth'
|
||||
import { signIn, signOut } from '@/auth'
|
||||
|
||||
// Validation schemas
|
||||
const registerSchema = z.object({
|
||||
@@ -12,10 +12,19 @@ const registerSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
})
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email({ message: 'Invalid email address' }),
|
||||
password: z.string().min(1, { message: 'Password is required' }),
|
||||
})
|
||||
|
||||
export type RegisterResult =
|
||||
| { success: true; userId: string }
|
||||
| { success: false; error: string }
|
||||
|
||||
export type LoginResult =
|
||||
| { success: true }
|
||||
| { success: false; error: string }
|
||||
|
||||
/**
|
||||
* Register a new user with email and password
|
||||
* Requirements: 1.1, 1.2, 1.3, 1.4, 1.5
|
||||
@@ -81,3 +90,86 @@ export async function registerUser(
|
||||
return { success: false, error: 'Registration failed. Please try again.' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Login user with email and password
|
||||
* Requirements: 2.1, 2.2
|
||||
*/
|
||||
export async function loginUser(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<LoginResult> {
|
||||
try {
|
||||
// Validate input (Requirement 2.1 - credential validation)
|
||||
const validation = loginSchema.safeParse({ email, password })
|
||||
|
||||
if (!validation.success) {
|
||||
const errors = validation.error.issues.map((issue) => issue.message).join(', ')
|
||||
return { success: false, error: errors }
|
||||
}
|
||||
|
||||
const { email: validEmail, password: validPassword } = validation.data
|
||||
|
||||
// Attempt to sign in (Requirement 2.1 - authenticate and create session)
|
||||
// The authorize function in auth.ts handles:
|
||||
// - Querying user from database
|
||||
// - Password verification with bcrypt
|
||||
// - Session creation on success
|
||||
await signIn('credentials', {
|
||||
email: validEmail,
|
||||
password: validPassword,
|
||||
redirect: false,
|
||||
})
|
||||
|
||||
// If signIn doesn't throw an error, authentication was successful
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
// Handle invalid credentials (Requirement 2.2)
|
||||
// NextAuth throws an error for invalid credentials
|
||||
console.error('Login error:', error)
|
||||
|
||||
// Return generic error message to avoid revealing whether email exists
|
||||
return { success: false, error: 'Invalid email or password' }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user and terminate session
|
||||
* Requirement: 2.5 - Logout terminates session and clears authentication tokens
|
||||
*/
|
||||
export async function logoutUser(): Promise<void> {
|
||||
try {
|
||||
// Sign out using NextAuth - this will:
|
||||
// 1. Clear the session token
|
||||
// 2. Remove authentication cookies
|
||||
// 3. Terminate the session
|
||||
await signOut({ redirect: false })
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error)
|
||||
throw new Error('Logout failed')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current session
|
||||
* Requirements: 3.2 - Session validation and persistence
|
||||
*/
|
||||
export async function getCurrentSession() {
|
||||
try {
|
||||
const { auth } = await import('@/auth')
|
||||
const session = await auth()
|
||||
return session
|
||||
} catch (error) {
|
||||
console.error('Session retrieval error:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if user is authenticated
|
||||
* Requirements: 2.4, 3.3 - Session expiration and validation
|
||||
*/
|
||||
export async function isAuthenticated(): Promise<boolean> {
|
||||
const session = await getCurrentSession()
|
||||
return !!session?.user
|
||||
}
|
||||
|
||||
164
lib/permissions.ts
Normal file
164
lib/permissions.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
'use server'
|
||||
|
||||
import { prisma } from './db'
|
||||
|
||||
export type Permission = 'owner' | 'editor' | 'viewer'
|
||||
|
||||
/**
|
||||
* Check if a user can access a list (view it)
|
||||
* Users can access a list if they are the owner or a collaborator
|
||||
*
|
||||
* @param userId - The ID of the user
|
||||
* @param listId - The ID of the list
|
||||
* @returns true if the user can access the list, false otherwise
|
||||
*/
|
||||
export async function canAccessList(
|
||||
userId: string,
|
||||
listId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
if (!userId || !listId) {
|
||||
return false
|
||||
}
|
||||
|
||||
const list = await prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
return list !== null
|
||||
} catch (error) {
|
||||
console.error('Error checking list access:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user can edit a list or its items
|
||||
* Users can edit if they are the owner or have editor permission
|
||||
*
|
||||
* @param userId - The ID of the user
|
||||
* @param listId - The ID of the list
|
||||
* @returns true if the user can edit the list, false otherwise
|
||||
*/
|
||||
export async function canEditList(
|
||||
userId: string,
|
||||
listId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
if (!userId || !listId) {
|
||||
return false
|
||||
}
|
||||
|
||||
const list = await prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
OR: [
|
||||
{ ownerId: userId },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: userId,
|
||||
permission: 'editor',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
return list !== null
|
||||
} catch (error) {
|
||||
console.error('Error checking list edit permission:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user can delete a list
|
||||
* Only the owner can delete a list
|
||||
*
|
||||
* @param userId - The ID of the user
|
||||
* @param listId - The ID of the list
|
||||
* @returns true if the user can delete the list, false otherwise
|
||||
*/
|
||||
export async function canDeleteList(
|
||||
userId: string,
|
||||
listId: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
if (!userId || !listId) {
|
||||
return false
|
||||
}
|
||||
|
||||
const list = await prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
ownerId: userId,
|
||||
},
|
||||
})
|
||||
|
||||
return list !== null
|
||||
} catch (error) {
|
||||
console.error('Error checking list delete permission:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the permission level a user has for a list
|
||||
*
|
||||
* @param userId - The ID of the user
|
||||
* @param listId - The ID of the list
|
||||
* @returns The permission level ('owner', 'editor', 'viewer') or null if no access
|
||||
*/
|
||||
export async function getPermission(
|
||||
userId: string,
|
||||
listId: string
|
||||
): Promise<Permission | null> {
|
||||
try {
|
||||
if (!userId || !listId) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Check if user is the owner
|
||||
const ownedList = await prisma.list.findFirst({
|
||||
where: {
|
||||
id: listId,
|
||||
ownerId: userId,
|
||||
},
|
||||
})
|
||||
|
||||
if (ownedList) {
|
||||
return 'owner'
|
||||
}
|
||||
|
||||
// Check if user is a collaborator
|
||||
const collaborator = await prisma.collaborator.findFirst({
|
||||
where: {
|
||||
userId: userId,
|
||||
listId: listId,
|
||||
},
|
||||
})
|
||||
|
||||
if (collaborator) {
|
||||
return collaborator.permission as Permission
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (error) {
|
||||
console.error('Error getting user permission:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
69
middleware.ts
Normal file
69
middleware.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { auth } from "@/auth"
|
||||
import { NextResponse } from "next/server"
|
||||
import type { NextRequest } from "next/server"
|
||||
|
||||
/**
|
||||
* Middleware for session validation and route protection
|
||||
*
|
||||
* This middleware:
|
||||
* - Validates session tokens on protected routes
|
||||
* - Redirects unauthenticated users to login
|
||||
* - Handles session expiration
|
||||
* - Allows access to auth pages for unauthenticated users
|
||||
*/
|
||||
export default auth((req) => {
|
||||
const { nextUrl } = req
|
||||
const isLoggedIn = !!req.auth?.user
|
||||
|
||||
// Define protected routes
|
||||
const isProtectedRoute =
|
||||
nextUrl.pathname === "/" ||
|
||||
nextUrl.pathname.startsWith("/list") ||
|
||||
nextUrl.pathname.startsWith("/profile") ||
|
||||
nextUrl.pathname.startsWith("/invitations")
|
||||
|
||||
// Define auth pages (login, register, etc.)
|
||||
const isAuthPage = nextUrl.pathname.startsWith("/auth")
|
||||
|
||||
// Allow access to auth pages regardless of authentication status
|
||||
if (isAuthPage) {
|
||||
// If already logged in and trying to access login/register, redirect to home
|
||||
if (isLoggedIn && (nextUrl.pathname === "/auth/login" || nextUrl.pathname === "/auth/register")) {
|
||||
return NextResponse.redirect(new URL("/", req.url))
|
||||
}
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
// Redirect to login if accessing protected route without authentication
|
||||
if (isProtectedRoute && !isLoggedIn) {
|
||||
const loginUrl = new URL("/auth/login", req.url)
|
||||
// Add callback URL to redirect back after login
|
||||
loginUrl.searchParams.set("callbackUrl", nextUrl.pathname)
|
||||
return NextResponse.redirect(loginUrl)
|
||||
}
|
||||
|
||||
// Allow access to public routes
|
||||
return NextResponse.next()
|
||||
})
|
||||
|
||||
/**
|
||||
* Matcher configuration for middleware
|
||||
* Applies middleware to all routes except:
|
||||
* - API routes (handled separately)
|
||||
* - Static files (_next/static)
|
||||
* - Image optimization (_next/image)
|
||||
* - Favicon and other public assets
|
||||
*/
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - api (API routes)
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
* - public assets (images, icons, manifest, sw.js)
|
||||
*/
|
||||
"/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|json|js)$).*)",
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user