-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
81 lines (67 loc) · 1.82 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package github
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/golang-jwt/jwt"
)
type Auth struct {
JWTToken string
Token string
}
// Builds the JWT token from the provided appId and key
func (ghApp *GitHubApp) buildJWTToken() error {
// Generate JWT token
token := jwt.New(jwt.SigningMethodRS256)
claims := token.Claims.(jwt.MapClaims)
claims["iat"] = time.Now().Add(time.Duration(-1) * time.Minute).Unix()
claims["exp"] = time.Now().Add(10 * time.Minute).Unix()
claims["iss"] = ghApp.Config.ApplicationID
// Parse RSA private key
key, err := jwt.ParseRSAPrivateKeyFromPEM(ghApp.Config.PrivateKey)
if err != nil {
return err
}
// Sign the token
jwtToken, err := token.SignedString(key)
if err != nil {
return err
}
ghApp.Auth.JWTToken = jwtToken
return nil
}
// TokenResponse is a struct that represents the response from the API
type TokenResponse struct {
Token string `json:"token"`
}
// Gets the access token to authenticate with github
func (ghApp *GitHubApp) GetAccessToken() (string, error) {
// Parse url
url := fmt.Sprintf("%s/app/installations/%d/access_tokens", githubAPIURL, ghApp.Config.InstallationID)
// Create the request to github's api
req, _ := http.NewRequest("POST", url, nil)
req.Header.Add("Accept", "application/vnd.github+json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", ghApp.Auth.JWTToken))
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return "", errors.New("couldn't get the token")
}
// Read the the response from the server
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Parse the response to the struct
t := TokenResponse{}
json.Unmarshal(body, &t)
return t.Token, nil
}