You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

47 lines
1.2 KiB

import { FastifyReply, FastifyRequest } from "fastify";
import Application from "@server/Application";
import jwt from "jsonwebtoken";
import { IteratorNext } from ".";
/**
* Attempt to authenticate a client's JWT token
*/
function authenticateJwtToken<T = any>(request: FastifyRequest, reply: FastifyReply): T | undefined {
// Verify headers
if (!request.headers["authorization"]) {
reply.status(401);
reply.send();
return;
}
if (!request.headers["authorization"].startsWith("Bearer ")) {
reply.status(400);
reply.send();
return;
}
// Construct the token string
let token = request.headers["authorization"].slice(7).trim();
if ((token.match(/\./g)||[]).length < 2) {
token += '.' + (request.cookies.jwt_signature ?? "").trim();
}
// Decode the token
let decoded: T;
try {
decoded = <any>jwt.verify(token, Application.instance().APP_KEY);
} catch(e) {
reply.status(401);
reply.send();
return;
}
return decoded;
}
/**
* Ensure that a valid authentication token is provided
*/
export function auth(request: FastifyRequest, reply: FastifyReply, next: IteratorNext) {
let token = authenticateJwtToken(request, reply);
if (token === undefined) {
return;
}
next();
}