Skip to content

Instantly share code, notes, and snippets.

@b4n92uid
Last active August 17, 2021 22:49
Show Gist options
  • Save b4n92uid/4fef7bc03b72ba771766779a7b3701a6 to your computer and use it in GitHub Desktop.
Save b4n92uid/4fef7bc03b72ba771766779a7b3701a6 to your computer and use it in GitHub Desktop.
[Apollo] buildRequestContext (Federation)
export function getUserFromToken(token): ITokenUser {
const cert = readFileSync(join(__dirname, "../../keys/public.pem"));
if (token) {
const decoded = jwt.verify(token, cert, { algorithms: ["RS256"] });
return decoded["user"] as ITokenUser;
}
return null;
}
export async function buildRequestContext({ req }): Promise<IContext> {
let user = null;
let token = null;
if (req.headers.authorization) {
try {
const matches = req.headers.authorization.match(/Bearer (.+)/);
token = matches[1];
user = getUserFromToken(token);
} catch (error) {
token = null;
user = null;
}
}
return {
user,
token
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment