verifying jwt now works

issue - I was importing the textEncoder for browser, rather than using the native one
This commit is contained in:
andrzej 2024-09-16 14:55:34 +02:00
parent 274ee8e4de
commit 8a04297768
4 changed files with 25 additions and 8 deletions

7
package-lock.json generated
View File

@ -38,6 +38,7 @@
"recharts": "^2.12.7",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"text-encoding": "^0.7.0",
"zod": "^3.23.8"
},
"devDependencies": {
@ -9625,6 +9626,12 @@
"node": ">=10"
}
},
"node_modules/text-encoding": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/text-encoding/-/text-encoding-0.7.0.tgz",
"integrity": "sha512-oJQ3f1hrOnbRLOcwKz0Liq2IcrvDeZRHXhd9RgLrsT+DjWY/nty1Hi7v3dtkaEYbPYe0mUoOfzRrMwfXXwgPUA==",
"deprecated": "no longer maintained"
},
"node_modules/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",

View File

@ -41,6 +41,7 @@
"recharts": "^2.12.7",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"text-encoding": "^0.7.0",
"zod": "^3.23.8"
},
"devDependencies": {

View File

@ -4,20 +4,30 @@ import { jwtVerify, JWTPayload, decodeJwt, SignJWT } from 'jose';
import { cookies } from 'next/headers';
import { loginSchema, LoginSchema } from 'app/login/schema';
import { NextResponse } from 'next/server';
import { TextEncoder } from 'util';
export async function getJWTSecretKey() {
export async function getJWTSecretKey<Uint8Array>() {
console.log('getJWTSecretKey called!')
const secret = process.env.JWT_SECRET
console.log('secret: ' + secret)
if (!secret) throw new Error("There is no JWT secret key")
const enc: Uint8Array = new TextEncoder().encode(secret)
return enc
console.log('encoding...')
try {
const enc: Uint8Array = new TextEncoder().encode(secret)
console.log('enc')
return enc
} catch (error) {
console.error('aw shit: ' + error.message)
}
}
export async function verifyJwt(token: string): Promise<JWTPayload | null> {
console.log('verifyJwt called for token: ' + token)
const key = await getJWTSecretKey()
console.log('key: ' + key)
const { payload } = await jwtVerify(token, key)
console.log('payload: ' + payload)
return payload
try {
//the curly braces here are used because you can't access the result of an await using dot notation
const { payload } = await jwtVerify(token, getJWTSecretKey)
return payload
} catch {
return null
}

View File

@ -19,7 +19,6 @@ export default async function(request: NextRequest) {
url.pathname = "/login"
if (protectedRoutes.some(pattern => matchesWildcard(request.nextUrl.pathname, pattern))) {
const token = request.cookies.get('token')
console.log(`token: ${JSON.stringify(token)}`)
//NOTE - may need to add logic to return 401 for api routes
if (!token) {