Skip to content

Commit

Permalink
refactor: move generate jwt to helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
kailashchoudhary11 committed Jul 6, 2024
1 parent 9370f7b commit 4d40665
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 56 deletions.
18 changes: 7 additions & 11 deletions handlers/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,32 @@ import (
"io"
"net/http"
"os"
"strings"

"github.com/google/go-github/v62/github"
"github.com/kailashchoudhary11/repo-guard/helpers"
"github.com/kailashchoudhary11/repo-guard/initializers"
"github.com/kailashchoudhary11/repo-guard/models"
"github.com/kailashchoudhary11/repo-guard/services"
)

func Webhook(w http.ResponseWriter, r *http.Request) {
fmt.Println("Inside webhook")
clientId := os.Getenv("CLIENT_ID")
jwtToken, err := services.GenerateJWTForApp(clientId, "repository-guard.2024-07-02.private-key.pem")
privatePem := os.Getenv("PRIVATE_KEY")
privatePem = strings.ReplaceAll(privatePem, "\\n", "\n")
jwtToken, err := helpers.GenerateJWT(clientId, privatePem)
if err != nil {
fmt.Println("Error: ", err)
return
}

body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body", http.StatusInternalServerError)
return
}
defer r.Body.Close()

webhookPayload := models.WebhookPayload{}
if err := json.Unmarshal(body, &webhookPayload); err != nil {
fmt.Println("There was an error in converting json", err)
Expand All @@ -39,20 +44,13 @@ func Webhook(w http.ResponseWriter, r *http.Request) {
authenticatedClient := initializers.GetClientWithToken(accessToken)

if webhookPayload.Action == "opened" {
fmt.Println("New issue opened")
// if webhookPayload.Issue.AuthorAssociation == "OWNER" {
// fmt.Println("Issue is opened by repo owner, skipping checks")
// return
// }
if isSpamIssue := validateIssue(authenticatedClient, webhookPayload.Repository, &webhookPayload.Issue); isSpamIssue {
fmt.Println("The duplicate issue is closed successfully")
}
}
}

func validateIssue(githubClient *github.Client, repo models.Repository, currentIssue *models.Issue) bool {
fmt.Println("Validating the issue", currentIssue.Number)

duplicateIssue := make(chan int)

allOpenIssues := services.FetchIssues(githubClient, repo)
Expand Down Expand Up @@ -81,7 +79,6 @@ func validateIssue(githubClient *github.Client, repo models.Repository, currentI
}

func compareIssues(issueOne *models.Issue, issueTwo *models.Issue, isDuplicate chan int) {
fmt.Println("Comparing the issues")
payload := fmt.Sprintf(`{"issue1_title": "%v", "issue1_body": "", "issue2_title": "%v", "issue2_body": "" }`, issueOne.Title, issueTwo.Title)
jsonBody := []byte(payload)

Expand Down Expand Up @@ -111,7 +108,6 @@ func compareIssues(issueOne *models.Issue, issueTwo *models.Issue, isDuplicate c
fmt.Println("Response is in invalid format", err)
isDuplicate <- -1
}
fmt.Println("Response", res)
if response.Similarity > 0.75 {
isDuplicate <- issueTwo.Number
}
Expand Down
37 changes: 37 additions & 0 deletions helpers/generateJWT.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package helpers

import (
"crypto/x509"
"encoding/pem"
"time"

"github.com/golang-jwt/jwt/v5"
)

func GenerateJWT(clientId, privatePem string) (string, error) {
block, _ := pem.Decode([]byte(privatePem))
if block == nil || block.Type != "RSA PRIVATE KEY" {
return "", nil
}

privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}

now := time.Now().Unix()
payload := jwt.MapClaims{
"iat": now - 60,
"exp": now + (10 * 60),
"iss": clientId,
}

token := jwt.NewWithClaims(jwt.SigningMethodRS256, payload)

tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
}

return tokenString, nil
}
45 changes: 0 additions & 45 deletions services/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@ package services

import (
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"

"github.com/golang-jwt/jwt/v5"

"github.com/google/go-github/v62/github"
"github.com/kailashchoudhary11/repo-guard/models"
Expand Down Expand Up @@ -63,7 +56,6 @@ func _fetchIssuesForPage(client *github.Client, repo models.Repository, page int
}

func FetchIssues(client *github.Client, repo models.Repository) []*models.Issue {
fmt.Println("Fetching the issues")
allIssues := []*models.Issue{}
ch := make(chan []*models.Issue)
countCh := make(chan int)
Expand Down Expand Up @@ -107,43 +99,6 @@ func CloseIssue(client *github.Client, repo models.Repository, issueNumber int,
return nil
}

func GenerateJWTForApp(clientId, filePath string) (string, error) {
// Read the private key
privatePem := os.Getenv("PRIVATE_KEY")
privatePem = strings.ReplaceAll(privatePem, "\\n", "\n")

// Parse the PEM block
block, _ := pem.Decode([]byte(privatePem))
if block == nil || block.Type != "RSA PRIVATE KEY" {
return "", nil
}

// Parse the RSA private key
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}

// Define the payload
now := time.Now().Unix()
payload := jwt.MapClaims{
"iat": now - 60, // issued at time, 60 seconds in the past to allow for clock drift
"exp": now + (10 * 60), // expiration time (10 minute maximum)
"iss": clientId, // GitHub App's client ID
}

// Create the token
token := jwt.NewWithClaims(jwt.SigningMethodRS256, payload)

// Sign the token with the private key
tokenString, err := token.SignedString(privateKey)
if err != nil {
return "", err
}

return tokenString, nil
}

func GetInstallationAccessToken(installationId int, jwtToken string) string {
response := struct {
Token string `json:"token"`
Expand Down

0 comments on commit 4d40665

Please sign in to comment.