コード例 #1
0
def authorize_github_callback(request):

    code = request.GET["code"]
    state = request.GET["state"]

    assert state == request.session[OAUTH_STATE]
    data = {
        "client_id": os.environ["GITHUB_CLIENT_ID"],
        "client_secret": os.environ["GITHUB_CLIENT_SECRET"],
        "code": code,
        "state": state,
    }

    response = requests.post(
        "https://github.com/login/oauth/access_token",
        json=data,
        headers={"Accept": "application/json"},
    )
    assert (
        response.status_code == 200
    ), "Unexpected response {response.status_code}\n{response.content}"

    response_data = response.json()

    if "error" in response_data:
        return JsonResponse(response_data)

    # save the credentials in the db
    token, created = models.GithubOAuthToken.objects.get_or_create(
        user=request.user, defaults=response_data
    )
    if not created:
        token.update(**response_data)
        token.save()

    # get the username

    api = Api(github_token=token.access_token)
    github_name = api.who_am_i()["github_name"]

    profile, created = models.SocialProfile.objects.get_or_create(
        user=request.user, github_name=github_name
    )
    if not created:
        profile.github_name = github_name
        profile.save()

    return JsonResponse(
        {"status": "OK", "message": f"Github username set to {github_name}"}
    )
コード例 #2
0
 def handle(self, *args, **options):
     api = Api(PERSONAL_GITHUB_NAME)
     who = api.who_am_i()
     pprint(who)