使用GAE上的Python使用Github API进行身份验证

时间:2014-03-05 17:20:53

标签: python google-app-engine python-2.7 github-api

我无法在GAE中使用Github API作为应用程序(GAE在使用Github3时抛出异常)。

import os, sys
sys.path.append("lib")
import jinja2, webapp2, urllib

from google.appengine.api import users, oauth, urlfetch

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class ConsoleLogin(webapp2.RequestHandler):

    def get(self):
        google_user = users.get_current_user()

        if google_user:
            fields = {
                "client_id" : os.environ.get('CLIENT_ID'),
                "scope" : "user, repo"
            }
            url = 'https://github.com/login/oauth/authorize'
            data = urllib.urlencode(fields)
            result = urlfetch.fetch(url=url,
                payload=data,
                method=urlfetch.GET
            )

在代码中的这一点之后,你应该从Github获得一个临时代码。

问题:我根本找不到它。我在指南中看到你应该将它作为环境变量获取,但我看不到它。

帮助我完成Python脚本的人的额外分数。 ;)

3 个答案:

答案 0 :(得分:2)

以下是GitHub oAuth身份验证的实际实现。它是基于Flask而不是Webapp2构建的,但您可以轻松地将处理程序移植到Webapp2。您可以查看一个gae引导程序项目gae-init,并从一个包含各种oAuth提供gae-init-auth的分支中获取特定代码段。 (注意:装饰者@github.tokengetterflask_oauth.py

提供
github_oauth = oauth.OAuth()

github = github_oauth.remote_app(
    'github',
    base_url='https://api.github.com/',
    request_token_url=None,
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    consumer_key=config.CONFIG_DB.github_client_id,
    consumer_secret=config.CONFIG_DB.github_client_secret,
    request_token_params={'scope': 'user:email'},
  )


@app.route('/_s/callback/github/oauth-authorized/')
@github.authorized_handler
def github_authorized(resp):
  if resp is None:
    return 'Access denied: error=%s' % flask.request.args['error']
  flask.session['oauth_token'] = (resp['access_token'], '')
  me = github.get('user')
  user_db = retrieve_user_from_github(me.data)
  return signin_user_db(user_db)


@github.tokengetter
def get_github_oauth_token():
  return flask.session.get('oauth_token')


@app.route('/signin/github/')
def signin_github():
  return github.authorize(
      callback=flask.url_for('github_authorized',
          next=util.get_next_url(),
          _external=True,
        )
    )


def retrieve_user_from_github(response):
  auth_id = 'github_%s' % str(response['id'])
  user_db = model.User.retrieve_one_by('auth_ids', auth_id)
  if user_db:
    return user_db
  return create_user_db(
      auth_id,
      response['name'] or response['login'],
      response['login'],
      response['email'] or '',
    )

答案 1 :(得分:0)

运行OAuth授权请求时,您似乎缺少一些项目。根据{{​​3}},您需要将4个参数传递给授权请求(无论如何这是OAuth 2协议的标准):

  • client_id(它来自你的GitHub应用程序注册 - 你确定它存在于一个OS环境变量吗?你自己把它放在那里吗?为了测试目的,你可以先将它作为一个普通字符串放入代码;一旦一切正常,你会做得更好);
  • scope(你已经定义了 - 这没关系);
  • 您选择的随机state,GitHub将在下一步中回复您;
  • ,更重要的是,一旦用户允许访问其帐户,GitHub将转发客户端的redirect_uri:它必须是您自己网站上的一个URL,您需要处理这两个URL来获取它们codestate参数

redirect_uri可能是 - 例如 - http://localhost:8080/oauth/accept_github,然后您需要准备app.yaml文件和Python代码来处理对/oauth/accept_github的请求。在处理这些请求的代码中,尝试显示以下内容:self.request.get('state')self.request.get('code'):如果一切正常,它们应该包含GitHub API发回的内容。现在,您已准备好进行下一步:将code转换为access_token:)

答案 2 :(得分:0)

我不是说这很漂亮 - 事实并非如此。这段代码很丑陋,但它使用GAE,Webapp2和urllib2,而不是其他框架/库。

import os, sys, cgi, json, cookielib
sys.path.append("lib")
import jinja2, webapp2, urllib, urllib2

from google.appengine.api import users, oauth, urlfetch
from webapp2_extras import sessions

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

class ConsoleLogin(BaseHandler):
    def get(self):
        # Set variables to avoid problems later
        code = ''
        url = ''
        access_token = ''
        scope = ''
        username = ''

        google_user = users.get_current_user()

        if google_user:
            url = self.request.url
            if ('code' not in url and not self.session.get('access_token')):
                # First time user coming to site. Redirect to GH for code
                url = 'https://github.com/login/oauth/authorize?scope=user,repo&client_id=' + os.environ.get('CLIENT_ID')
                self.redirect(url)
            elif 'code' in url:
                # User has been to GH, continue with auth process
                code = url.replace('http://localhost:8080/?code=', '')

                # We have code, now get Access Token
                fields = {
                    "client_id" : os.environ.get('CLIENT_ID'),
                    "client_secret" : os.environ.get('CLIENT_SECRET'),
                    "code" : code
                }
                url = 'https://github.com/login/oauth/access_token'
                data = urllib.urlencode(fields)
                result = urlfetch.fetch(url=url,
                    payload=data,
                    method=urlfetch.POST
                )

                # Get the query string
                query_string = str(result.content)

                # Get the access token out of the full query string
                access_token = query_string[13:]
                end_access = access_token.find('&')
                access_token = access_token[:end_access]

                # Get the scope out of the full query string
                start_scope = query_string.find('scope')
                end_scope = query_string.find('token_type')
                start_scope = start_scope + 6   # remove the word 'scope='
                end_scope = end_scope - 1       # remove the & symobol
                scope = query_string[start_scope:end_scope]
                scope = scope.split('%2C')

            # Store the Access Token in a Session Variable
            self.session['access_token'] = access_token
            self.session['scope'] = scope

            # And redirect to the base URL for neatness and to avoid other issues
            self.redirect('/')

            access_token = self.session.get('access_token')
            scope = self.session.get('scope')

            context = {
                'access_token' : access_token,
                'scope' : scope,
                'username' : username,
            }

            # Template Settings
            temp = 'templates/index.html'

            template = JINJA_ENVIRONMENT.get_template(temp)
            self.response.write(template.render(context))


config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'the-beatles-will-always-rule',
}

application = webapp2.WSGIApplication([
    ('/', ConsoleLogin),
], debug=True, config=config)