Skip to content

Commit

Permalink
Keep session management logic together
Browse files Browse the repository at this point in the history
  • Loading branch information
delbaoliveira committed Apr 24, 2024
1 parent 6489fc2 commit ece4c05
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
15 changes: 13 additions & 2 deletions app/auth/02-stateless-session.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import 'server-only';

import type { SessionPayload } from '@/app/auth/definitions';
import { SignJWT, jwtVerify } from 'jose';
import { cookies } from 'next/headers';
import type { SessionPayload } from '@/app/auth/definitions';
import { redirect } from 'next/navigation';

const secretKey = process.env.SECRET;
const key = new TextEncoder().encode(secretKey);
Expand All @@ -22,7 +23,6 @@ export async function decrypt(session: string | undefined = '') {
});
return payload;
} catch (error) {
console.log('Failed to verify session');
return null;
}
}
Expand All @@ -40,6 +40,17 @@ export async function createSession(userId: string) {
});
}

export async function verifySession() {
const cookie = cookies().get('session')?.value;
const session = await decrypt(cookie);

if (!session?.userId) {
redirect('/login');
}

return { isAuth: true, userId: Number(session.userId) };
}

export async function updateSession() {
const session = cookies().get('session')?.value;
const payload = await decrypt(session);
Expand Down
19 changes: 1 addition & 18 deletions app/auth/03-dal.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
// Authorization begins with middleware.ts, where we check for a local cookie

import 'server-only';
import { db } from '@/drizzle/db';
import { eq } from 'drizzle-orm';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { cache } from 'react';
import { users } from '@/drizzle/schema';
import { decrypt } from '@/app/auth/02-stateless-session';

// todo: Have verify session return the session payload, and use it in updateSession
export async function verifySession() {
const cookie = cookies().get('session')?.value;
const session = await decrypt(cookie);

if (!session?.userId) {
redirect('/login');
}

return { isAuth: true, userId: Number(session.userId) };
}
import { verifySession } from '@/app/auth/02-stateless-session';

// Use react.cache
export const getUser = cache(async () => {
const session = await verifySession();
if (!session) return null;
Expand Down

0 comments on commit ece4c05

Please sign in to comment.