def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in post_params.items(): decoded_param = param.decode('utf-8') decoded_value = value[0].decode('utf-8') if decoded_param == "username" or decoded_param == "password": params[decoded_param] = decoded_value params["grant_type"] = "password" params["client_id"] = self.client_id params["client_secret"] = self.client_secret # Request an access token by POSTing a request to the auth server. try: response = urllib2.urlopen(self.token_endpoint, urlencode(params)) except HTTPError, he: if he.code == 400: error_body = json.loads(he.read()) body = self.SERVER_ERROR_TEMPLATE\ .format(error_type=error_body["error"], error_description=error_body["error_description"]) return "400 Bad Request", body, {"Content-Type": "text/html"} if he.code == 401: return "302 Found", "", {"Location": "/login?failed=1"}
def verify(self, token): params = {"access_token": token} try: response = urllib2.urlopen(self.verify_token, urlencode(params)) token = json.load(response) return token except HTTPError as he: return None except URLError as e: return None else: return None
def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """ query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_code = 302 response.body = "" response.add_header("Location", location) return response
def login(self): params = { "grant_type": "password", "client_id": self.client_id, "client_secret": self.client_secret, "username": self.request.form.get('username', ''), "password": self.request.form.get('password', ''), } try: response = urllib2.urlopen(self.token_endpoint, urlencode(params)) except HTTPError as he: if he.code == 400: error_body = json.loads(he.read()) return 400, error_body, None if he.code == 401: return 401, None, None except URLError as e: print e return 503, no_service, None token = json.load(response) return 200, None, token