-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgithub.go
72 lines (62 loc) · 1.71 KB
/
github.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
package github
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
)
type AccessToken struct {
Token string `json:"token"`
ExpireAt string `json:"expires_at"`
Permissions map[string]string `json:"permissions"`
RepositorySelection string `json:"repository_selection"`
}
func getJWT(key []byte, appID int64) (string, error) {
signKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
if err != nil {
return "", err
}
t := jwt.New(jwt.GetSigningMethod("RS256"))
claims := make(jwt.MapClaims)
claims["iat"] = time.Now().Unix()
claims["iss"] = appID
claims["exp"] = time.Now().Add(time.Minute * 10).Unix()
t.Claims = claims
tokenString, err := t.SignedString(signKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func getInstallationToken(key []byte, appID int64, installationID string) (AccessToken, error) {
url := fmt.Sprintf("https://api.github.com/app/installations/%s/access_tokens", installationID)
tokenString, err := getJWT(key, appID)
if err != nil {
return AccessToken{}, err
}
c := http.Client{}
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return AccessToken{}, err
}
req.Header.Add("Accept", "application/vnd.github.v3+json")
req.Header.Add("Authorization", "Bearer "+tokenString)
res, err := c.Do(req)
if err != nil {
return AccessToken{}, err
}
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return AccessToken{}, err
}
bodyString := string(bodyBytes)
accesstToken := AccessToken{}
err = json.Unmarshal([]byte(bodyString), &accesstToken)
if err != nil {
return AccessToken{}, err
}
return accesstToken, nil
}