Merge pull request #1021 from rigaspapas/implement-apps-oauth-endpoints

Implement OAuth for apps
This commit is contained in:
Jannis Gebauer
2020-07-20 11:51:32 +02:00
committed by GitHub
11 changed files with 352 additions and 3 deletions
+74
View File
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
import github.GithubObject
class AccessToken(github.GithubObject.NonCompletableGithubObject):
"""
This class represents access tokens.
"""
def __repr__(self):
return self.get__repr__(
{
"token": "{}...".format(self.token[:5]),
"scope": self.scope,
"type": self.type,
}
)
@property
def token(self):
"""
:type: string
"""
return self._token.value
@property
def type(self):
"""
:type: string
"""
return self._type.value
@property
def scope(self):
"""
:type: string
"""
return self._scope.value
def _initAttributes(self):
self._token = github.GithubObject.NotSet
self._type = github.GithubObject.NotSet
self._scope = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "access_token" in attributes: # pragma no branch
self._token = self._makeStringAttribute(attributes["access_token"])
if "token_type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["token_type"])
if "scope" in attributes: # pragma no branch
self._scope = self._makeStringAttribute(attributes["scope"])
+114
View File
@@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
############################ Copyrights and license ###########################
# #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more#
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
import urllib
import github.GithubObject
from github.AccessToken import AccessToken
class ApplicationOAuth(github.GithubObject.NonCompletableGithubObject):
"""
This class is used for identifying and authorizing users for Github Apps.
https://developer.github.com/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#1-users-are-redirected-to-request-their-github-identity
"""
def __repr__(self):
return self.get__repr__({"client_id": self._client_id.value})
@property
def client_id(self):
return self._client_id.value
@property
def client_secret(self):
return self._client_secret.value
def _initAttributes(self):
self._client_id = github.GithubObject.NotSet
self._client_secret = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "client_id" in attributes: # pragma no branch
self._client_id = self._makeStringAttribute(attributes["client_id"])
if "client_secret" in attributes: # pragma no branch
self._client_secret = self._makeStringAttribute(attributes["client_secret"])
def get_login_url(self, redirect_uri=None, state=None, login=None):
"""
Return the URL you need to redirect a user to in order to authorize
your App.
:type: string
"""
parameters = {"client_id": self.client_id}
if redirect_uri is not None:
assert isinstance(redirect_uri, str), redirect_uri
parameters["redirect_uri"] = redirect_uri
if state is not None:
assert isinstance(state, str), state
parameters["state"] = state
if login is not None:
assert isinstance(login, str), login
parameters["login"] = login
parameters = urllib.parse.urlencode(parameters)
base_url = "https://github.com/login/oauth/authorize"
return u"{}?{}".format(base_url, parameters)
def get_access_token(self, code, state=None):
"""
:calls: `POST /login/oauth/access_token <https://developer.github.com/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/>`_
:param code: string
:param state: string
"""
assert isinstance(code, str), code
post_parameters = {
"code": code,
"client_id": self.client_id,
"client_secret": self.client_secret,
}
if state is not None:
post_parameters["state"] = state
self._requester._Requester__authorizationHeader = None
headers, data = self._requester.requestJsonAndCheck(
"POST",
"https://github.com/login/oauth/access_token",
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "PyGithub/Python",
},
input=post_parameters,
)
return AccessToken(
requester=self._requester,
# not required, this is a NonCompletableGithubObject
headers={},
attributes=data,
completed=False,
)
+15
View File
@@ -21,6 +21,7 @@
# Copyright 2018 bryanhuntesl <31992054+bryanhuntesl@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2018 itsbruce <it.is.bruce@gmail.com> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
@@ -1108,6 +1109,20 @@ class AuthenticatedUser(github.GithubObject.CompletableGithubObject):
github.Repository.Repository, self._requester, "/user/subscriptions", None
)
def get_installations(self):
"""
:calls: `GET /user/installations <http://developer.github.com/v3/apps>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Installation.Installation`
"""
return github.PaginatedList.PaginatedList(
github.Installation.Installation,
self._requester,
"/user/installations",
None,
headers={"Accept": Consts.mediaTypeIntegrationPreview},
list_item="installations",
)
def has_in_following(self, following):
"""
:calls: `GET /user/following/:user <http://developer.github.com/v3/users/followers>`_
+35 -1
View File
@@ -6,6 +6,7 @@
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
@@ -52,7 +53,31 @@ class Installation(github.GithubObject.NonCompletableGithubObject):
@property
def id(self):
return self._id
"""
:type: integer
"""
return self._id.value
@property
def app_id(self):
"""
:type: integer
"""
return self._app_id.value
@property
def target_id(self):
"""
:type: integer
"""
return self._target_id.value
@property
def target_type(self):
"""
:type: string
"""
return self._target_type.value
def get_repos(self):
"""
@@ -72,7 +97,16 @@ class Installation(github.GithubObject.NonCompletableGithubObject):
def _initAttributes(self):
self._id = github.GithubObject.NotSet
self._app_id = github.GithubObject.NotSet
self._target_id = github.GithubObject.NotSet
self._target_type = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "app_id" in attributes: # pragma no branch
self._app_id = self._makeIntAttribute(attributes["app_id"])
if "target_id" in attributes: # pragma no branch
self._target_id = self._makeIntAttribute(attributes["target_id"])
if "target_type" in attributes: # pragma no branch
self._target_type = self._makeStringAttribute(attributes["target_type"])
+10
View File
@@ -29,6 +29,7 @@
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2018 itsbruce <it.is.bruce@gmail.com> #
# Copyright 2019 Tomas Tomecek <tomas@tomecek.net> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
@@ -57,6 +58,7 @@ import jwt
import requests
import urllib3
import github.ApplicationOAuth
import github.Event
import github.Gist
import github.GithubObject
@@ -778,6 +780,14 @@ class Github(object):
self.__requester, headers={}, attributes={"id": id}, completed=True
)
def get_oauth_application(self, client_id, client_secret):
return github.ApplicationOAuth.ApplicationOAuth(
self.__requester,
headers={},
attributes={"client_id": client_id, "client_secret": client_secret},
completed=False,
)
class GithubIntegration(object):
"""
+1
View File
@@ -538,6 +538,7 @@ class Requester:
self.__hostname,
"uploads.github.com",
"status.github.com",
"github.com",
], o.hostname
assert o.path.startswith((self.__prefix, "/api/"))
assert o.port == self.__port
+71
View File
@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class ApplicationOAuth(Framework.TestCase):
def setUp(self):
super().setUp()
self.CLIENT_ID = "client_id_removed"
self.CLIENT_SECRET = "client_secret_removed"
self.app = self.g.get_oauth_application(self.CLIENT_ID, self.CLIENT_SECRET)
def testLoginURL(self):
BASE_URL = "https://github.com/login/oauth/authorize"
sample_uri = "https://myapp.com/some/path"
sample_uri_encoded = "https%3A%2F%2Fmyapp.com%2Fsome%2Fpath"
self.assertEqual(
self.app.get_login_url(), "{}?client_id={}".format(BASE_URL, self.CLIENT_ID)
)
self.assertTrue(
"redirect_uri={}".format(sample_uri_encoded)
in self.app.get_login_url(redirect_uri=sample_uri)
)
self.assertTrue(
"client_id={}".format(self.CLIENT_ID)
in self.app.get_login_url(redirect_uri=sample_uri)
)
self.assertTrue(
"state=123abc" in self.app.get_login_url(state="123abc", login="user")
)
self.assertTrue(
"login=user" in self.app.get_login_url(state="123abc", login="user")
)
self.assertTrue(
"client_id={}".format(self.CLIENT_ID)
in self.app.get_login_url(state="123abc", login="user")
)
def testGetAccessToken(self):
access_token = self.app.get_access_token(
"oauth_code_removed", state="state_removed"
)
# Test string representation
self.assertEqual(
str(access_token), 'AccessToken(type="bearer", token="acces...", scope="")'
)
self.assertEqual(access_token.token, "access_token_removed")
self.assertEqual(access_token.scope, "")
self.assertEqual(access_token.type, "bearer")
+8
View File
@@ -746,3 +746,11 @@ class AuthenticatedUser(Framework.TestCase):
def testGetMigrations(self):
self.assertEqual(self.user.get_migrations().totalCount, 46)
def testInstallations(self):
installations = self.user.get_installations()
self.assertEqual(installations[0].id, 123456)
self.assertEqual(installations[0].app_id, 10101)
self.assertEqual(installations[0].target_id, 3344556)
self.assertEqual(installations[0].target_type, "User")
self.assertEqual(installations.totalCount, 1)
+2 -2
View File
@@ -167,7 +167,7 @@ class GithubIntegration(unittest.TestCase):
self.get_mock.calls[0][0],
("https://api.github.com/repos/foo/bar/installation",),
)
self.assertEqual(inst.id.value, 111111)
self.assertEqual(inst.id, 111111)
def test_get_installation_custom_base_url(self):
from github import GithubIntegration
@@ -178,7 +178,7 @@ class GithubIntegration(unittest.TestCase):
self.get_mock.calls[0][0],
("https://corp.com/v3/repos/foo/bar/installation",),
)
self.assertEqual(inst.id.value, 111111)
self.assertEqual(inst.id, 111111)
def tearDown(self):
GithubObject.setCheckAfterInitFlag(self.origin_check_after_init_flag)
@@ -0,0 +1,11 @@
https
POST
github.com
None
/login/oauth/access_token
{'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'PyGithub/Python'}
{"client_secret": "client_secret_removed", "code": "oauth_code_removed", "client_id": "client_id_removed", "state": "state_removed"}
200
[('Date', 'Fri, 25 Jan 2019 11:06:39 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Server', 'GitHub.com'), ('Status', '200 OK'), ('Vary', 'X-PJAX, Accept-Encoding'), ('ETag', 'W/"deebfe47f0039427b39ec010749014f6"'), ('Cache-Control', 'max-age=0, private, must-revalidate'), ('Set-Cookie', 'has_recent_activity=1; path=/; expires=Fri, 25 Jan 2019 12:06:38 -0000, ignored_unsupported_browser_notice=false; path=/'), ('X-Request-Id', 'ed8794eb-dc95-481f-8e52-2cd5db0494a0'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '1; mode=block'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Expect-CT', 'max-age=2592000, report-uri="https://api.github.com/_private/browser/errors"'), ('Content-Security-Policy', "default-src 'none'; base-uri 'self'; block-all-mixed-content; connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: github.githubassets.com assets-cdn.github.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com; manifest-src 'self'; media-src 'none'; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com"), ('Content-Encoding', 'gzip'), ('X-GitHub-Request-Id', 'C8AC:1D8B2:126D746:1BF8DE4:5C4AEDBE')]
{"access_token":"access_token_removed","token_type":"bearer","scope":""}
@@ -0,0 +1,11 @@
https
GET
api.github.com
None
/user/installations
{'Accept': 'application/vnd.github.machine-man-preview+json', 'Authorization': 'Basic login_and_password_removed', 'User-Agent': 'PyGithub/Python'}
None
200
[('Server', 'GitHub.com'), ('Date', 'Wed, 23 Jan 2019 22:55:08 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Status', '200 OK'), ('X-RateLimit-Limit', '5000'), ('X-RateLimit-Remaining', '4999'), ('X-RateLimit-Reset', '1548287423'), ('Cache-Control', 'private, max-age=60, s-maxage=60'), ('Vary', 'Accept, Authorization, Cookie, X-GitHub-OTP'), ('ETag', 'W/"a5a8c1fcbecacfdb17b4b714f28556ba"'), ('X-OAuth-Scopes', ''), ('X-Accepted-OAuth-Scopes', ''), ('X-OAuth-Client-Id', 'Iv1.11b0acc03bd76665'), ('X-GitHub-Media-Type', 'github.machine-man-preview; format=json'), ('Access-Control-Expose-Headers', 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type'), ('Access-Control-Allow-Origin', '*'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '1; mode=block'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Content-Security-Policy', "default-src 'none'"), ('Content-Encoding', 'gzip')]
{"total_count":1,"installations":[{"id":123456,"account":{"login":"rigaspapas","id":12345,"node_id":"MDQ6VXNlcjE3NzM2NTI=","avatar_url":"https://avatars1.githubusercontent.com/u/12345?v=4","gravatar_id":"","url":"https://api.github.com/users/rigaspapas","html_url":"https://github.com/rigaspapas","followers_url":"https://api.github.com/users/rigaspapas/followers","following_url":"https://api.github.com/users/rigaspapas/following{/other_user}","gists_url":"https://api.github.com/users/rigaspapas/gists{/gist_id}","starred_url":"https://api.github.com/users/rigaspapas/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/rigaspapas/subscriptions","organizations_url":"https://api.github.com/users/rigaspapas/orgs","repos_url":"https://api.github.com/users/rigaspapas/repos","events_url":"https://api.github.com/users/rigaspapas/events{/privacy}","received_events_url":"https://api.github.com/users/rigaspapas/received_events","type":"User","site_admin":false},"repository_selection":"selected","access_tokens_url":"https://api.github.com/installations/242638/access_tokens","repositories_url":"https://api.github.com/installation/repositories","html_url":"https://github.com/settings/installations/123456","app_id":10101,"target_id":3344556,"target_type":"User","permissions":{"contents":"write","pull_requests":"write","administration":"read","metadata":"read","statuses":"read"},"events":["push"],"created_at":"2018-07-13T17:59:47.000+03:00","updated_at":"2018-07-13T17:59:47.000+03:00","single_file_name":null}]}