Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

29 hide access token post part #59

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def finalize_options(self):
def run_tests(self):
try:
import pytest
except:
except Exception:
raise RuntimeError('py.test is not installed, run: pip install pytest')
params = {'args': self.test_args}
if self.cov:
Expand Down
4 changes: 2 additions & 2 deletions zign/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def load_config_ztoken(config_file: str):
try:
with open(config_file) as fd:
data = yaml.safe_load(fd)
except:
except Exception:
data = None
return data or {}

Expand All @@ -112,7 +112,7 @@ def get_new_token(realm: str, scope: list, user, password, url=None, insecure=Fa
raise ServerError('Token Service returned HTTP status {}: {}'.format(response.status_code, response.text))
try:
json_data = response.json()
except:
except Exception:
raise ServerError('Token Service returned invalid JSON data')

if not json_data.get('access_token'):
Expand Down
2 changes: 1 addition & 1 deletion zign/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def delete_token(obj, name):

try:
del data[name]
except:
except Exception:
pass

with open(TOKENS_FILE_PATH, 'w') as fd:
Expand Down
71 changes: 55 additions & 16 deletions zign/oauth2.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
from urllib.parse import urlparse


SUCCESS_PAGE = '''<!DOCTYPE HTML>
Expand Down Expand Up @@ -32,6 +33,31 @@
</style>
<script>
(function extractFragmentQueryString() {{
function post(url, body, successCb, errorCb) {{
function noop() {{}}
function successCb(){{
window.location.href = "http://localhost:{port}/?success";
}}
function errorCb(){{
window.location.href = "http://localhost:{port}/?error";
}}
var success = successCb || noop;
var error = errorCb || noop;
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/json");
req.onreadystatechange = function() {{
if (req.readyState === XMLHttpRequest.DONE) {{
if (req.status >= 200 && req.status < 300) {{
success(req);
}} else {{
error(req);
}}
}}
}}
req.send(JSON.stringify(body));
}}

function displayError(message) {{
var errorElement = document.getElementById("error");
errorElement.textContent = message || "Unknown error";
Expand All @@ -52,7 +78,9 @@
var query = window.location.hash.substring(1);
var params = parseQueryString(query);
if (params.access_token) {{
window.location.href = "http://localhost:{port}/?" + query;
post("http://localhost:{port}", params, null, function error() {{
displayError("Error: Could not POST to server.")
}});
}} else {{
displayError("Error: No access_token in URL.")
}}
Expand Down Expand Up @@ -83,28 +111,38 @@
class ClientRedirectHandler(BaseHTTPRequestHandler):
'''Handles OAuth 2.0 redirect and return a success page if the flow has completed.'''

def do_GET(self):
'''Handle the GET request from the redirect.
def _set_headers(self, content_type='text/html'):
'''Sets initial response headers of the request.'''
self.send_response(200)
self.send_header('Content-type', content_type)
self.end_headers()

def do_POST(self):
'''Handle the POST request from the redirect.
Parses the token from the query parameters and returns a success page if the flow has completed'''
self._set_headers("application/json")

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
self.server.__tokeninfo = json.loads(self.data_string)
if 'access_token' in self.server.__tokeninfo.keys():
self.wfile.write('{"status": "success"}'.encode('utf-8'))
else:
self.send_error(500, json.dumps(self.server.__tokeninfo).encode('utf-8'))

def do_GET(self):
'''Handle initial GET request display EXTRACT_TOKEN_PAGE
On succesfull post XMLHttpRequest - displays SUCCESS_PAGE
'''
query_string = urlparse(self.path).query
self._set_headers()

if not query_string:
self.wfile.write(EXTRACT_TOKEN_PAGE.format(port=self.server.server_port).encode('utf-8'))
elif 'success' in query_string:
self.server.query_params = self.server.__tokeninfo
self.wfile.write(SUCCESS_PAGE.encode('utf-8'))
else:
query_params = {}
for key, val in parse_qs(query_string).items():
query_params[key] = val[0]
self.server.query_params = query_params
if 'access_token' in self.server.query_params:
page = SUCCESS_PAGE
else:
page = ERROR_PAGE
self.wfile.write(page.encode('utf-8'))
self.wfile.write(ERROR_PAGE.encode('utf-8'))

def log_message(self, format, *args):
"""Do not log messages to stdout while running as cmd. line program."""
Expand All @@ -117,6 +155,7 @@ class ClientRedirectServer(HTTPServer):
into query_params and then stops serving.
"""
query_params = {}
__tokeninfo = {}

def __init__(self, address):
super().__init__(address, ClientRedirectHandler)