-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithubauth.go
71 lines (58 loc) · 1.44 KB
/
githubauth.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
package main
import (
"context"
"io/ioutil"
"time"
"github.com/golang-jwt/jwt"
"github.com/google/go-github/v57/github"
"golang.org/x/oauth2"
)
func generateJWT(AppID int, PrivateKeyPath string) (string, error) {
privateKey, err := ioutil.ReadFile(PrivateKeyPath)
if err != nil {
return "", err
}
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
return "", err
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iat": time.Now().Unix(),
"exp": time.Now().Add(time.Minute * 10).Unix(),
"iss": AppID,
})
tokenString, err := token.SignedString(parsedKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func getInstallationAccessToken(jwt string, InstallationID int64) (string, error) {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: jwt},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
token, _, err := client.Apps.CreateInstallationToken(ctx, InstallationID, nil)
if err != nil {
return "", err
}
return token.GetToken(), nil
}
func githubClient() *github.Client {
jwt, err := generateJWT(AppID, PrivateKeyPath)
if err != nil {
panic(err)
}
token, err := getInstallationAccessToken(jwt, InstallationID)
if err != nil {
panic(err)
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}