sprinklers3/server/express/verifyAuthorization.ts

50 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-08-29 08:00:41 -06:00
import * as Express from "express";
import ApiError from "@common/ApiError";
import { ErrorCode } from "@common/ErrorCode";
import * as tok from "@common/TokenClaims";
import { verifyToken } from "@server/authentication";
declare global {
2018-09-02 02:57:55 -06:00
namespace Express {
interface Request {
token?: tok.AccessToken;
2018-08-29 08:00:41 -06:00
}
2018-09-02 02:57:55 -06:00
}
2018-08-29 08:00:41 -06:00
}
export interface VerifyAuthorizationOpts {
2018-09-02 02:57:55 -06:00
type: tok.TokenClaims["type"];
2018-08-29 08:00:41 -06:00
}
2018-09-02 02:57:55 -06:00
export function verifyAuthorization(
options?: Partial<VerifyAuthorizationOpts>
): Express.RequestHandler {
const opts: VerifyAuthorizationOpts = {
type: "access",
...options
};
return (req, res, next) => {
const fun = async () => {
const bearer = req.headers.authorization;
if (!bearer) {
throw new ApiError(
"No Authorization header specified",
ErrorCode.BadToken
);
}
const matches = /^Bearer (.*)$/.exec(bearer);
if (!matches || !matches[1]) {
throw new ApiError(
"Invalid Authorization header, must be Bearer",
ErrorCode.BadToken
);
}
const token = matches[1];
2018-08-29 08:00:41 -06:00
2018-09-02 02:57:55 -06:00
req.token = (await verifyToken(token, opts.type)) as any;
2018-08-29 08:00:41 -06:00
};
2018-09-02 02:57:55 -06:00
fun().then(() => next(null), err => next(err));
};
2018-08-29 08:00:41 -06:00
}