|  | 
| 1 | 1 | #!/usr/bin/env python3 | 
| 2 |  | - | 
| 3 | 2 | """ | 
| 4 | 3 | Created by sarathkaul on 14/11/19 | 
|  | 4 | +Updated by lawric1 on 24/11/20 | 
| 5 | 5 | 
 | 
| 6 |  | -Basic authentication using an API password is deprecated and will soon no longer work. | 
| 7 |  | -Visit https://developer.github.com/changes/2020-02-14-deprecating-password-auth | 
| 8 |  | -for more information around suggested workarounds and removal dates. | 
| 9 |  | -""" | 
|  | 6 | +Authentication will be made via access token. | 
|  | 7 | +To generate your personal access token visit https://github.com/settings/tokens. | 
|  | 8 | +
 | 
|  | 9 | +NOTE: | 
|  | 10 | +Never hardcode any credential information in the code. Always use an environment | 
|  | 11 | +file to store the private information and use the `os` module to get the information | 
|  | 12 | +during runtime. | 
| 10 | 13 | 
 | 
|  | 14 | +Create a ".env" file in the root directory and write these two lines in that file | 
|  | 15 | +with your token:: | 
|  | 16 | +
 | 
|  | 17 | +#!/usr/bin/env bash | 
|  | 18 | +export USER_TOKEN="" | 
|  | 19 | +""" | 
|  | 20 | +import os | 
|  | 21 | +from typing import Any, Dict | 
| 11 | 22 | 
 | 
| 12 | 23 | import requests | 
| 13 | 24 | 
 | 
| 14 |  | -_GITHUB_API = "https://api.github.com/user" | 
|  | 25 | +BASE_URL = "https://api.github.com" | 
| 15 | 26 | 
 | 
|  | 27 | +# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user | 
|  | 28 | +AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user" | 
| 16 | 29 | 
 | 
| 17 |  | -def fetch_github_info(auth_user: str, auth_pass: str) -> dict: | 
|  | 30 | +# https://github.com/settings/tokens | 
|  | 31 | +USER_TOKEN = os.environ.get("USER_TOKEN", "") | 
|  | 32 | + | 
|  | 33 | + | 
|  | 34 | +def fetch_github_info(auth_token: str) -> Dict[Any, Any]: | 
| 18 | 35 |     """ | 
| 19 | 36 |     Fetch GitHub info of a user using the requests module | 
| 20 | 37 |     """ | 
| 21 |  | -    return requests.get(_GITHUB_API, auth=(auth_user, auth_pass)).json() | 
| 22 |  | - | 
| 23 |  | - | 
| 24 |  | -if __name__ == "__main__": | 
| 25 |  | -    for key, value in fetch_github_info("<USER NAME>", "<PASSWORD>").items(): | 
| 26 |  | -        print(f"{key}: {value}") | 
|  | 38 | +    headers = { | 
|  | 39 | +        "Authorization": f"token {auth_token}", | 
|  | 40 | +        "Accept": "application/vnd.github.v3+json", | 
|  | 41 | +    } | 
|  | 42 | +    return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json() | 
|  | 43 | + | 
|  | 44 | + | 
|  | 45 | +if __name__ == "__main__":  # pragma: no cover | 
|  | 46 | +    if USER_TOKEN: | 
|  | 47 | +        for key, value in fetch_github_info(USER_TOKEN).items(): | 
|  | 48 | +            print(f"{key}: {value}") | 
|  | 49 | +    else: | 
|  | 50 | +        raise ValueError("'USER_TOKEN' field cannot be empty.") | 
0 commit comments