Files
Todo/auth.ts
Paul Bailey 895ceba55f Implement session management (Task 5)
- Configure JWT session strategy with 30-day expiration
- Implement session validation middleware for route protection
- Create logout functionality with session termination
- Handle session expiration automatically via JWT
- Add session helper functions (getCurrentSession, isAuthenticated)
- Protect routes: /, /list/*, /profile/*, /invitations/*
- Redirect unauthenticated users to login with callback URL
- Requirements: 2.4, 2.5, 3.1, 3.2, 3.4
2025-12-02 00:39:04 +00:00

92 lines
2.4 KiB
TypeScript

import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { prisma } from "@/lib/db"
import bcrypt from "bcryptjs"
import { z } from "zod"
// Validation schemas
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
})
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({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
// Validate credentials format
const { email, password } = loginSchema.parse(credentials)
// Query user from database
const user = await prisma.user.findUnique({
where: { email },
})
// Check if user exists
if (!user || !user.passwordHash) {
return null
}
// Verify password with bcrypt
const isPasswordValid = await bcrypt.compare(password, user.passwordHash)
if (!isPasswordValid) {
return null
}
// Return user object (without password hash)
return {
id: user.id,
email: user.email,
name: user.name,
}
} catch (error) {
console.error("Authorization error:", error)
return null
}
},
}),
],
callbacks: {
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 && 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
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
error: "/auth/error",
},
})