27 lines
839 B
JavaScript
27 lines
839 B
JavaScript
import * as jose from 'jose';
|
|
import { createErrorResponse } from "../utils";
|
|
|
|
export async function verifyJWT(context) {
|
|
const { request, env } = context;
|
|
|
|
// Check for a valid JWT token
|
|
const authHeader = request.headers.get("Authorization");
|
|
if (!authHeader) {
|
|
return createErrorResponse("Missing Authorization header", 401);
|
|
}
|
|
|
|
const token = authHeader.split(" ")[1];
|
|
|
|
try {
|
|
// Verify the token
|
|
const { payload, protectedHeader } = await jose.jwtVerify(token, new TextEncoder().encode(env.JWT_SECRET), {
|
|
issuer: 'urn:example:issuer',
|
|
audience: 'urn:example:audience',
|
|
});
|
|
context.user = { userId: payload.id, username: payload.username };
|
|
return; // Continue to the next middleware or function
|
|
} catch (error) {
|
|
return createErrorResponse("Invalid or expired token", 401);
|
|
}
|
|
}
|