Example #1
0
    def _on_access_token(self, future, client_id, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(
                AuthError('QQ auth access_token error: %s' % str(response)))
            return

        print 'response:', response.body
        if 'error' in response.body:
            future.set_exception(
                AuthError('QQ auth access_token error: %s' %
                          str(response.body)))
            return
        args = escape.native_str(response.body).split('&')
        access_token = ''
        for a in args:
            print a
            k, v = a.split('=')
            if k == 'access_token':
                access_token = v
                break
        http = self.get_auth_http_client()
        url = 'https://graph.qq.com/oauth2.0/me?access_token=%s' % access_token
        http.fetch(
            url,
            functools.partial(self._on_get_openid, future, client_id,
                              access_token))
Example #2
0
    def _on_access_token(self, redirect_uri, client_id, client_secret, future,
                         fields, response):
        if response.error:
            future.set_exception(
                AuthError("Github auth error: %s" % str(response)))
            return

        args = parse_qs_bytes(native_str(response.body))
        if "error" in args:
            future.set_exception(
                AuthError("Github auth error: %s" % args["error"][-1]))
            return

        access_token = args["access_token"][-1]
        if isinstance(access_token, bytes):
            access_token = access_token.decode()
        session = {
            "access_token": access_token,
        }

        self.github_request(path="/user",
                            callback=functools.partial(self._on_get_user_info,
                                                       future, session,
                                                       fields),
                            access_token=access_token)
Example #3
0
    def _parse_response(self, future, response):
        """ Parse the JSON from the API """
        if response.error:
            logging.warning("HTTP error from Github get user: %s",
                            response.error)
            future.set_exception(
                AuthError('Github auth get user info error: %s' %
                          str(response)))
            return
        try:
            json = tornado.escape.json_decode(response.body)
        except Exception:
            logging.warning("Invalid JSON from Github: %r", response.body)
            future.set_exception(
                AuthError('Invalid JSON from Github: %s' % str(response)))
            return

        if isinstance(json, dict) and json.get("error_code"):
            logging.warning("Github error: %d: %r", json["error_code"],
                            json.get("error_msg"))
            future.set_exception(
                AuthError("Github error: %d: %r" %
                          (json["error_code"], json.get("error_msg"))))
            return
        future.set_result(json)
Example #4
0
    def verify_params(self, params):
        if not params.get('username'):
            raise AuthError('Invalid response, no username given')

        if 'opaque' not in params:
            raise AuthError('Invalid response, no opaque given')

        if 'nonce' not in params:
            raise AuthError('Invalid response, no nonce given')
Example #5
0
    def _on_access_token(self, future, response_fut):
        """Callback function for the exchange to the access token."""
        try:
            response = response_fut.result()
        except Exception as e:
            future.set_exception(AuthError('Wexin auth error: %s' % str(e)))
            return

        args = escape.json_decode(response.body)
        if args.get('errcode'):
            future.set_exception(
                AuthError('Wexin auth error: %s' % str(args['errmsg'])))
            return
        future_set_result_unless_cancelled(future, args)
Example #6
0
 def _on_access_token(self, future, response):
     """Callback function for the exchange to the access token."""
     if response.error:
         future.set_exception(AuthError('LinkedIn auth error: %s' % str(response)))
         return
     args = json.loads(response.body)
     future.set_result(args)
Example #7
0
 def _on_lengjing_request(self, future, response):
     if response.error:
         future.set_exception(AuthError(
             "Error response %s fetching %s" % (response.error,
                                                response.request.url)))
         return
     future.set_result(response.body)
Example #8
0
    def _on_access_token(self, redirect_uri, client_id, client_secret, future,
                         fields, response):
        if response.error:
            future.set_exception(
                AuthError('SinaWeibo auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        session = {
            'access_token': args['access_token'],
            'expires_in': args['expires_in'],
            'uid': args['uid'],
        }

        weibo_request(
            path='users/show',
            callback=partial(
                self._on_get_user_info,
                future,
                session,
                fields,
            ),
            access_token=session['access_token'],
            uid=session['uid'],
            httpclient=self.get_auth_http_client(),
        )
Example #9
0
 def _on_qihu360_request(self, future, response):
     if response.error:
         future.set_exception(AuthError(
             "Error response %s fetching %s" % (response.error,
                                                response.request.url)))
         return
     future.set_result(escape.json_decode(response.body))
Example #10
0
 def _on_get_user_request(self, future, response):
     if response.error:
         future.set_exception(
             AuthError('Error response fetching', response.error,
                       response.request.url))
         return
     future.set_result(escape.json_decode(response.body))
Example #11
0
    def _on_access_token(self, future, response):
        if response.error:
            future.set_exception(AuthError('Gitlab auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future.set_result(args)
Example #12
0
 def _on_access_token(self, future, response):
     """Callback function for the exchange to the access token."""
     if response.error:
         future.set_exception(
             AuthError('FullContact auth error: %s' % str(response)))
         return
     args = escape.json_decode(response.body)
     future.set_result(args)
Example #13
0
 def _on_access_token(self, future, response):
     """Callback function for the exchange to the access token."""
     if response.error:
         future.set_exception(AuthError('GitHub auth error: %s' % str(response)))
         return
     args = dict()
     tornado.httputil.parse_body_arguments(response.headers.get("Content-Type"), response.body, args, None)
     future.set_result(args)
Example #14
0
 def _on_user_info(self, future, response):
     if response.error:
         future.set_exception(
             AuthError('Google auth error: %s [%s]' %
                       (str(response), response.body)), response)
         return
     user_info = json.loads(response.body)
     future.set_result(user_info)
Example #15
0
 def _on_github_request(self, future, response):
     if response.error:
         future.set_exception(AuthError("Error response: %s" % response,
                                        response.error,
                                        response.request.url,
                                        response.body))
         return
     future.set_result(escape.json_decode(response.body))
Example #16
0
    def _on_douban_request(future, response):
        if response.error:
            future.set_exception(
                AuthError('Error response % fetching %s', response.error,
                          response.request.url))

            return

        future.set_result(escape.json_decode(response.body))
Example #17
0
 def _on_access_token(self, future, response):
     if response.error:
         future.set_exception(
             AuthError('Douban Auth Error: %s' % str(response)))
         return
     args = escape.json_decode(response.body)
     # future.set_result(args)
     self.get_user_info(access_token=args['access_token'],
                        callback=functools.partial(self._on_get_user_info, future))
Example #18
0
    def get_authenticated_user(self, code):
        """Handles the login for the Github user, returning a user object.

        Example usage::
            class GithubOAuth2LoginHandler(tornado.web.RequestHandler,
                                           GithubOAuth2Mixin):
                @tornado.gen.coroutine
                def get(self):
                    if self.get_argument("code", False):
                        user = yield self.get_authenticated_user(code=self.get_argument("code"))
                        # Save the user with e.g. set_secure_cookie
                    else:
                        return self.redirect(self.get_auth_url(scope=["user:email"]))
        """
        http = self.get_auth_http_client()
        body = urlencode({
            "client_id":
            self.gh_settings[self._OAUTH_SETTINGS_KEY]["key"],
            "client_secret":
            self.gh_settings[self._OAUTH_SETTINGS_KEY]["secret"],
            "code":
            code
        })

        # retrieve access token
        resp = yield http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                                method="POST",
                                headers={
                                    "Content-Type":
                                    "application/x-www-form-urlencoded",
                                    "Accept": "application/json",
                                },
                                body=body)
        if resp.error:
            raise AuthError("Github auth error: %s" % str(resp))
        args = escape.json_decode(escape.native_str(resp.body))
        access_token = args.get("access_token", None)
        if not access_token:
            log.warn("no access_token in token request")
            return None

        # retrieve user info
        user = yield self.github_request(path="/user",
                                         access_token=access_token)
        user['access_token'] = access_token

        scopes = args["scope"].split(",")
        has_user_email_scope = scopes.count("user:email") > 0
        if not has_user_email_scope:
            return user

        # retrieve email info
        emails = yield self.github_request(path="/user/emails",
                                           access_token=access_token)
        user["private_emails"] = emails
        return user
Example #19
0
    def _on_get_user_info(self, future, session, user):

        if user is None or user.get("errcode", None):
            future.set_exception(
                AuthError('Weixin getuserinfo error: %s' %
                          str(user['errcode'])))
            return

        user.update(session)
        future.set_result(user)
Example #20
0
    def _on_access_token(self, client_id, client_secret, future, response):

        if response.error:
            future.set_exception(
                AuthError('Weixin auth error: %s' % str(response)))
            return

        session = escape.json_decode(response.body)

        if session.get("errcode", None):
            future.set_exception(
                AuthError('Weixin auth error: %s' % str(session['errcode'])))
            return

        self.weixin_request('/userinfo',
                            callback=functools.partial(self._on_get_user_info,
                                                       future, session),
                            access_token=session['access_token'],
                            openid=session['openid'])
Example #21
0
    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(
                AuthError('Github auth error: %s' % str(response)))
            return

        args = tornado.escape.parse_qs_bytes(
            tornado.escape.native_str(response.body))

        future.set_result(args)
Example #22
0
    def _on_access_token(self, redirect_uri, client_id, client_secret,
                         callback, fields, response, future):
        if response.error:
            future.set_exception(AuthError('QQ auth error %s' % str(response)))
            return

        args = escape.parse_qs_bytes(escape.native_str(response.body))
        if args.get("error", None):
            future.set_exception(AuthError('QQ auth error %s' % str(response)))
            return

        session = {
            "access_token": args["access_token"][-1],
            "expires": args.get("expires_in")[0]
        }

        http = self.get_auth_http_client()
        http.fetch(
            url_concat('https://graph.qq.com/oauth2.0/me?',
                       {'access_token': session['access_token']}),
            functools.partial(self._on_access_openid, redirect_uri, client_id,
                              client_secret, session, callback, fields))
Example #23
0
    def _on_access_token(self, redirect_uri, client_id, client_secret,
                         future, fields, response):
        if response.error:
            future.set_exception(
                AuthError("Github auth error: %s" % str(response)))
            return

        args = parse_qs_bytes(native_str(response.body))

        if "error" in args:
            future.set_exception(
                AuthError("Github auth error: %s" % args["error"][-1]))
            return

        session = {
            "access_token": args["access_token"][-1],
        }

        self.github_request(path="/user",
                            callback=self.async_callback(
                                self._on_get_user_info, future, session, fields),
                            access_token=session["access_token"])
Example #24
0
    def _on_get_openid(self, future, client_id, access_token, response):
        if response.error:
            future.set_exception(
                AuthError('QQ auth get_openid error: %s' % str(response)))
            return
        print 'response:', response.body
        m = re.findall(r'"openid":"(.*?)"', response.body)
        if not m:
            future.set_exception(
                AuthError('QQ get openid bad return: %s' % str(response)))
            return
        openid = m[0]
        print 'openid:', openid
        args = {
            'access_token': access_token,
            'oauth_consumer_key': client_id,
            'openid': openid,
        }

        self.qq_request(callback=functools.partial(self._on_get_user_info,
                                                   future, args),
                        args=args)
Example #25
0
 def _on_access_token(self, future, response):
     """Callback function for the exchange to the access token."""
     if response.error:
         future.set_exception(
             AuthError('Google auth error: %s [%s]' %
                       (str(response), response.body)), response)
         return
     args = json.loads(response.body)
     if not args.has_key('access_token'):
         GoogleAuthHandler.log_error(
             'Google auth error: Key `access_token` not found in response: %r\nResponse body: %r\nResponse headers: %r',
             args, response.body, list(response.headers.get_all()))
         future.set_result(None)
         return
     future.set_result(args)
Example #26
0
    def _on_access_token(self, redirect_uri, client_id, client_secret, future,
                         fields, response):
        if response.error:
            future.set_exception(
                AuthError('LinkedIn auth error: %s' % str(response)))
            return

        session = escape.json_decode(response.body)
        http_callback = functools.partial(self._on_get_user_info, future,
                                          session)
        self.linkedin_request(
            path=
            "/people/~:(id,formatted-name,public-profile-url,picture-url;secure=true)",
            callback=http_callback,
            access_token=session["access_token"])
Example #27
0
    def _on_access_token(self, redirect_uri, client_id, client_secret, future,
                         fields, response):
        if response.error:
            future.set_exception(
                AuthError('Weibo auth error: %s' % str(response)))
            return

        args = escape.json_decode(escape.native_str(response.body))
        session = {
            "access_token": args.get("access_token"),
            "expires_in": args.get("expires_in")
        }

        self.weibo_request(path="/users/show.json",
                           callback=functools.partial(self._on_get_user_info,
                                                      future, session, fields),
                           access_token=session["access_token"],
                           uid=args.get("uid"))
Example #28
0
def _on_github_request(future, response):
    """ Parse the JSON from the API """
    if response.error:
        print response.error
        future.set_exception(
            AuthError("Error response %s fetching %s" %
                      (response.error, response.request.url)))
        return

    result = ObjectDict(code=response.code, headers=response.headers, body=None)

    try:
        result.body = json_decode(response.body)
    except Exception:
        gen_log.warning("Invalid JSON from Github: %r", response.body)
        future.set_result(result)
        return
    future.set_result(result)
Example #29
0
    def _on_access_openid(self, redirect_uri, client_id, client_secret,
                          session, future, fields, response):

        if response.error:
            future.set_exception(AuthError('QQ auth error: %s' %
                                           str(response)))
            return
        m = re.search(r'"openid":"([a-zA-Z0-9]+)"',
                      escape.native_str(response.body))

        session["openid"] = m.group(1)

        self.qq_request(path="/user/get_user_info",
                        callback=self.async_callback(self._on_get_user_info,
                                                     future, session, fields),
                        access_token=session["access_token"],
                        oauth_consumer_key=client_id,
                        openid=session["openid"])
Example #30
0
    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(
                AuthError("Github auth error: %s" % str(response)))
            return

        args = escape.json_decode(escape.native_str(response.body))
        access_token = args.get("access_token", None)
        if not access_token:
            future.set_result(None)
        scopes = args["scope"].split(",")
        has_user_email_scope = scopes.count("user:email") > 0
        self.github_request(path="/user",
                            callback=functools.partial(self._on_get_user_info,
                                                       future, access_token,
                                                       has_user_email_scope),
                            access_token=access_token)