Created
October 20, 2019 10:47
-
-
Save revant/c919ff93639c4927dc5b202aa6092dcd to your computer and use it in GitHub Desktop.
NestJS GithubWebHookGuard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2019 Revant Nandgaonkar | |
// License: MIT | |
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; | |
import * as crypto from 'crypto'; | |
import * as rawBody from 'raw-body'; | |
@Injectable() | |
export class GithubWebHookGuard implements CanActivate { | |
async canActivate(context: ExecutionContext): Promise<boolean> { | |
const req = context.switchToHttp().getRequest(); | |
if (req.readable) { | |
const X_HUB_SIGNATURE = 'x-hub-signature'; | |
const chunk = (await rawBody(req)).toString().trim(); | |
const headerSignature = req.headers[X_HUB_SIGNATURE]; | |
const signature = `sha1=${crypto | |
.createHmac('sha1', process.env.GITHUB_SECRET) | |
.update(chunk) | |
.digest('hex')}`; | |
return headerSignature === signature; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment