Skip to content

Commit

Permalink
Switch to jose (supported in the Edge runtime)
Browse files Browse the repository at this point in the history
  • Loading branch information
delbaoliveira committed Mar 14, 2024
1 parent 8601e86 commit 1cca22a
Show file tree
Hide file tree
Showing 4 changed files with 1,178 additions and 3,266 deletions.
40 changes: 28 additions & 12 deletions app/auth/02-client-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,38 @@
// This file goes through **client-side session** management
// See `middleware.ts` and `03-dal.ts` for the authorization / data access logic

// Recommend iron-session and jose
// Recommend jose as it supports Edge Runtime (Middleware)

import 'server-only';

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

// TODO: Replace with secret key from environment variables
const secretKey = 'yourSecretKey';
const key = new TextEncoder().encode(secretKey);

export async function createSession(id: number) {
const token = jwt.sign({ id }, secretKey, {
expiresIn: '1h',
async function encrypt(payload: SessionPayload) {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('1hr')
.sign(key);
}

async function decrypt(userId: string) {
const { payload } = await jwtVerify(userId, key, {
algorithms: ['HS256'],
});
return payload;
}

export async function createSession(userId: string) {
const expiresAt = new Date(Date.now() + 60 * 60 * 1000);
const session = await encrypt({ userId, expiresAt });

cookies().set('token', token, {
cookies().set('session', session, {
httpOnly: true,
secure: true,
expires: expiresAt,
Expand All @@ -34,20 +49,21 @@ export async function createSession(id: number) {
// - Server Actions or Server Components, use `cookies()`
// - Route handler, can use either headers or cookies

export async function verifyClientSession(token: string | undefined) {
if (!token) return null;
export async function verifyClientSession(session: string | undefined) {
// const session = cookies().get('session')?.value;
if (!session) return null;

try {
const { id } = jwt.verify(token, secretKey);
if (!id) return null;
return { isAuth: true, userId: id };
const { userId } = await decrypt(session);
return { isAuth: true, userId };
} catch (error) {
console.log(error);
return null;
}
}

export function updateSession() {}

export function deleteSession() {
cookies().delete('token');
cookies().delete('session');
}
5 changes: 5 additions & 0 deletions app/auth/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,8 @@ export type FormState =
message?: string;
}
| undefined;

export type SessionPayload = {
userId: string;
expiresAt: Date;
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"drizzle-orm": "^0.30.1",
"jose": "^5.2.3",
"jsonwebtoken": "^9.0.2",
"lucide-react": "^0.356.0",
"next": "14.1.3",
Expand Down
Loading

0 comments on commit 1cca22a

Please sign in to comment.