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
This commit is contained in:
2025-12-02 00:39:04 +00:00
parent 211ed50503
commit 895ceba55f
4 changed files with 125 additions and 4 deletions

15
auth.ts
View File

@@ -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
},
},