-
Notifications
You must be signed in to change notification settings - Fork 3
/
gh_token.py
76 lines (57 loc) · 2.09 KB
/
gh_token.py
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
#!/usr/bin/env python3
# locate imports on sourceware
import sys
sys.path.insert(0, '/home/cygwin/.local/lib/python{}.{}/site-packages'.format(sys.version_info.major, sys.version_info.minor))
from cryptography.hazmat.backends import default_backend
import json
import jwt
import os
import time
import urllib.error
import urllib.request
GH_APP_ID = 117451
private_key = None
def _get_private_key():
global private_key
if not private_key:
# load the GitHub app private key
basedir = os.path.dirname(os.path.realpath(__file__))
pemfile = os.path.join(basedir, 'scallywag.private-key.pem')
cert = open(pemfile, 'r').read().encode()
private_key = default_backend().load_pem_private_key(cert, None)
return private_key
def _make_jwt():
now = int(time.time())
payload = {
# issued at time, 60 seconds in the past to allow for clock drift
'iat': now - 60,
# expiration time (10 minute maximum)
'exp': now + (10 * 60),
# GitHub App's identifier
'iss': GH_APP_ID,
}
return jwt.encode(payload, _get_private_key(), algorithm='RS256')
def fetch_iat():
token = _make_jwt()
# list installations for this app
req = urllib.request.Request('https://api.github.com/app/installations')
req.add_header('Authorization', 'Bearer {}'.format(token))
req.add_header('Accept', 'application/vnd.github.v3+json')
resp = urllib.request.urlopen(req)
# find the installation_id for the installation on the 'cygwin' org
j = json.loads(resp.read().decode())
for i in j:
if i['account']['login'] == 'cygwin':
access_tokens_url = i['access_tokens_url']
break
else:
return None
# create an installation access token
req = urllib.request.Request(access_tokens_url, method='POST')
req.add_header('Authorization', 'Bearer {}'.format(token))
req.add_header('Accept', 'application/vnd.github.v3+json')
resp = urllib.request.urlopen(req)
j = json.loads(resp.read().decode())
return j['token']
if __name__ == '__main__':
print(fetch_iat())