From cd922c3efab9b7cd8728478c9fe35ffd51313ae2 Mon Sep 17 00:00:00 2001 From: npalaska Date: Thu, 12 Nov 2020 22:48:08 -0500 Subject: [PATCH] black reformat --- lib/pbench/server/api/__init__.py | 4 +- .../server/api/resources/alembic/env.py | 4 +- .../server/api/resources/elasticsearch_api.py | 1 - .../server/api/resources/graphql_api.py | 22 +++--- lib/pbench/server/api/resources/models.py | 8 +-- .../server/api/resources/pbench_users.py | 71 ++++++++++--------- lib/pbench/server/api/resources/upload_api.py | 5 +- lib/pbench/test/unit/server/test_requests.py | 42 ----------- lib/pbench/test/unit/server/test_user_auth.py | 21 +++--- server/requirements.txt | 1 + 10 files changed, 73 insertions(+), 106 deletions(-) diff --git a/lib/pbench/server/api/__init__.py b/lib/pbench/server/api/__init__.py index fbb8b21c19..b845dabbd0 100644 --- a/lib/pbench/server/api/__init__.py +++ b/lib/pbench/server/api/__init__.py @@ -127,7 +127,9 @@ def create_app(): # JWT specific configuration app.config["JWT_SECRET_KEY"] = os.getenv("SECRET_KEY", "my_precious") app.config["BCRYPT_LOG_ROUNDS"] = int(app.config_server.get("bycrypt_log_rounds")) - app.config["TOKEN_EXPIRATION_DURATION"] = app.config_server.get("token_expiration_duration") + app.config["TOKEN_EXPIRATION_DURATION"] = app.config_server.get( + "token_expiration_duration" + ) app.bcrypt = Bcrypt(app) diff --git a/lib/pbench/server/api/resources/alembic/env.py b/lib/pbench/server/api/resources/alembic/env.py index dcaf9f693d..aaaee08efb 100644 --- a/lib/pbench/server/api/resources/alembic/env.py +++ b/lib/pbench/server/api/resources/alembic/env.py @@ -64,9 +64,7 @@ def run_migrations_online(): ) with connectable.connect() as connection: - context.configure( - connection=connection, target_metadata=target_metadata - ) + context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() diff --git a/lib/pbench/server/api/resources/elasticsearch_api.py b/lib/pbench/server/api/resources/elasticsearch_api.py index 9817d72c63..7dd49dc498 100644 --- a/lib/pbench/server/api/resources/elasticsearch_api.py +++ b/lib/pbench/server/api/resources/elasticsearch_api.py @@ -1,4 +1,3 @@ - import requests from flask_restful import Resource, abort from flask import request, make_response diff --git a/lib/pbench/server/api/resources/graphql_api.py b/lib/pbench/server/api/resources/graphql_api.py index 1dcfd610d6..cc3871158e 100644 --- a/lib/pbench/server/api/resources/graphql_api.py +++ b/lib/pbench/server/api/resources/graphql_api.py @@ -1,4 +1,3 @@ - import requests from flask_restful import Resource, abort from flask import request, make_response @@ -7,15 +6,14 @@ class GraphQL(Resource): """GraphQL API for post request via server.""" + def __init__(self, app, api): self.app = app self.api = api @cross_origin() def post(self): - graphQL = ( - f"http://{self.app.config_graphql.get('host')}:{self.app.config_graphql.get('port')}" - ) + graphQL = f"http://{self.app.config_graphql.get('host')}:{self.app.config_graphql.get('port')}" json_data = request.get_json(silent=True) if not json_data: @@ -26,22 +24,30 @@ def post(self): # query GraphQL gql_response = requests.post(graphQL, json=json_data) except requests.exceptions.ConnectionError: - self.app.logger.exception("Connection refused during the GraphQL post request") + self.app.logger.exception( + "Connection refused during the GraphQL post request" + ) abort(502, message="Network problem, could not post to GraphQL Endpoint") except requests.exceptions.Timeout: - self.app.logger.exception("Connection timed out during the GraphQL post request") + self.app.logger.exception( + "Connection timed out during the GraphQL post request" + ) abort( 504, message="Connection timed out, could not post to GraphQL Endpoint" ) except Exception: - self.app.logger.exception("Exception occurred during the GraphQL post request") + self.app.logger.exception( + "Exception occurred during the GraphQL post request" + ) abort(500, message="INTERNAL ERROR") try: # construct response object response = make_response(gql_response.text) except Exception: - self.app.logger.exception("Exception occurred GraphQL response construction") + self.app.logger.exception( + "Exception occurred GraphQL response construction" + ) abort( 500, message="INTERNAL ERROR", ) diff --git a/lib/pbench/server/api/resources/models.py b/lib/pbench/server/api/resources/models.py index 0a1ee25a2a..9ceab2c94b 100644 --- a/lib/pbench/server/api/resources/models.py +++ b/lib/pbench/server/api/resources/models.py @@ -42,15 +42,15 @@ def encode_auth_token(self, app, user_id): # Expiration is not defined, token is set to expire in a second payload = { "iat": datetime.datetime.utcnow(), - "exp": datetime.datetime.utcnow() + datetime.timedelta( - milliseconds=100), + "exp": datetime.datetime.utcnow() + + datetime.timedelta(milliseconds=100), "sub": user_id, } else: payload = { "iat": datetime.datetime.utcnow(), - "exp": datetime.datetime.utcnow() + datetime.timedelta( - minutes=int(expire)), + "exp": datetime.datetime.utcnow() + + datetime.timedelta(minutes=int(expire)), "sub": user_id, } try: diff --git a/lib/pbench/server/api/resources/pbench_users.py b/lib/pbench/server/api/resources/pbench_users.py index eede362d62..aa4f59a43b 100644 --- a/lib/pbench/server/api/resources/pbench_users.py +++ b/lib/pbench/server/api/resources/pbench_users.py @@ -102,26 +102,30 @@ def post(self): db_session.add(user) db_session.commit() self.app.logger.info( - f"New user registered, Name: {user_data.get('firstName')} {user_data.get('lastName')}, " - f"username: {user_data.get('username')}, email: {email}" + f"New user registered, Name: {user_data.get('firstName')} {user_data.get('lastName')} username: {user_data.get('username')}, email: {email}" ) # generate the auth token auth_token = user.encode_auth_token(self.app, user.id) if not auth_token: - self.app.logger.info(f"User registered but unable to encode the auth token. username {user_data.get('username')}") - return make_response("{'message':'Registered but unable to encode the auth token, please try logging in}", 500) + self.app.logger.info( + f"User registered but unable to encode the auth token. username {user_data.get('username')}" + ) + return make_response( + "{'message':'Registered but unable to encode the auth token, please try logging in}", + 500, + ) self.app.logger.info(auth_token.decode()) response_object = { - 'status': 'success', - 'message': 'Successfully registered.', - 'auth_token': auth_token.decode() + "status": "success", + "message": "Successfully registered.", + "auth_token": auth_token.decode(), } response = jsonify(response_object) response.status_code = 201 return make_response(response, 201) - #return Response(response_object, status=201, mimetype="application/json") + # return Response(response_object, status=201, mimetype="application/json") except ( SQLAlchemyError, @@ -189,14 +193,18 @@ def post(self): try: # fetch the user data - user = db_session.query(UserModel).filter_by(username=post_data.get("username")).first() + user = ( + db_session.query(UserModel) + .filter_by(username=post_data.get("username")) + .first() + ) except ( - SQLAlchemyError, - DataError, - DatabaseError, - DBAPIError, - CompileError, - ) as e: + SQLAlchemyError, + DataError, + DatabaseError, + DBAPIError, + CompileError, + ) as e: self.app.logger.error( f"Some SQLAlchemy error occurred while logging in a user {e.__dict__['orig']}" ) @@ -230,9 +238,9 @@ def post(self): abort(500, message="Auth token encoding failed please try again") response_object = { - 'status': 'success', - 'message': 'Successfully logged in.', - 'auth_token': auth_token.decode(), + "status": "success", + "message": "Successfully logged in.", + "auth_token": auth_token.decode(), } return make_response(jsonify(response_object), 200) @@ -291,8 +299,8 @@ def delete(self): # Add the token to the blacklist self.app.blacklist.add(auth_token) response_object = { - 'status': 'success', - 'message': 'Successfully logged out.', + "status": "success", + "message": "Successfully logged out.", } return make_response(jsonify(response_object), 200) @@ -380,17 +388,15 @@ def get(self, username): self.app.logger.info( f"Username retrieved from the auth token {user_id} is different for the username provided" ) - abort( - 403, message="Authentication token does not belong to the user" - ) + abort(403, message="Authentication token does not belong to the user") response_object = { - 'status': 'success', - 'data': { - 'email': user.email, - 'firstName': user.firstName, - 'lastName': user.lastName, - 'registered_on': user.registered_on, + "status": "success", + "data": { + "email": user.email, + "firstName": user.firstName, + "lastName": user.lastName, + "registered_on": user.registered_on, }, } return make_response(jsonify(response_object), 200) @@ -449,8 +455,7 @@ def delete(self, username): f"Token expired, Could not decode the auth token: {auth_token} for user {user_id}" ) abort( - 401, - message="Token expired, please log back in", + 401, message="Token expired, please log back in", ) try: @@ -487,7 +492,7 @@ def delete(self, username): abort(500, message="There was something wrong deleting, please try again") response_object = { - 'status': 'success', - 'message': 'Successfully deleted.', + "status": "success", + "message": "Successfully deleted.", } return make_response(jsonify(response_object), 200) diff --git a/lib/pbench/server/api/resources/upload_api.py b/lib/pbench/server/api/resources/upload_api.py index e265d1b117..75be790fc6 100644 --- a/lib/pbench/server/api/resources/upload_api.py +++ b/lib/pbench/server/api/resources/upload_api.py @@ -1,4 +1,3 @@ - import os import humanize import tempfile @@ -25,7 +24,9 @@ def get(self): ) ) except Exception: - self.app.logger.exception("There was something wrong constructing the host info") + self.app.logger.exception( + "There was something wrong constructing the host info" + ) abort(500, message="There was something wrong with your request") response.status_code = 200 return response diff --git a/lib/pbench/test/unit/server/test_requests.py b/lib/pbench/test/unit/server/test_requests.py index 4f55bfdb85..e0d6d29681 100644 --- a/lib/pbench/test/unit/server/test_requests.py +++ b/lib/pbench/test/unit/server/test_requests.py @@ -9,54 +9,12 @@ from werkzeug.utils import secure_filename -def register_user(client, email, username, password, firstname, lastname): - return client.post( - f"{client.config['REST_URI']}/user", - data=json.dumps(dict( - email=email, - password=password, - username=username, - firstName=firstname, - lastName=lastname - )), - content_type='application/json', - ) - - -def login_user(client, username, password): - return client.post( - f"{client.config['REST_URI']}/session", - data=json.dumps(dict( - username=username, - password=password - )), - content_type='application/json', - ) - @pytest.fixture def mocked_responses(): with responses.RequestsMock() as rsps: yield rsps -class TestRegistration: - @staticmethod - def test_user_registration(client): - response = register_user(client, username='user', firstname="firstname", lastname="lastName", email='user@domain.com', password='12345') - data = json.loads(response.data.decode()) - assert data["status"] == "success" - - @staticmethod - def test_user_login(client, pytestconfig, caplog): - response = register_user(client, username='user', firstname="firstname", lastname="lastName", - email='user@domain.com', password='12345') - data = json.loads(response.data.decode()) - assert data["status"] == "success" - response = login_user(client, "user", "12345") - data = json.loads(response.data.decode()) - assert data["status"] == "success" - - class TestHostInfo: @staticmethod def test_host_info(client, pytestconfig, caplog): diff --git a/lib/pbench/test/unit/server/test_user_auth.py b/lib/pbench/test/unit/server/test_user_auth.py index 242ec6bbdc..75383a990a 100644 --- a/lib/pbench/test/unit/server/test_user_auth.py +++ b/lib/pbench/test/unit/server/test_user_auth.py @@ -297,15 +297,15 @@ def test_invalid_logout(client): password="12345", ) data_register = json.loads(resp_register.data.decode()) - assert data_register['message'] == 'Successfully registered.' - assert data_register['auth_token'] + assert data_register["message"] == "Successfully registered." + assert data_register["auth_token"] assert resp_register.status_code == 201 # user login resp_login = login_user(client, "username", "12345") data_login = json.loads(resp_login.data.decode()) - assert data_login['status'] == 'success' - assert data_login['message'] == 'Successfully logged in.' - assert data_login['auth_token'] + assert data_login["status"] == "success" + assert data_login["message"] == "Successfully logged in." + assert data_login["auth_token"] assert resp_login.status_code == 200 # invalid token logout time.sleep(1) @@ -314,7 +314,7 @@ def test_invalid_logout(client): headers=dict(Authorization="Bearer " + data_login["auth_token"]), ) data = json.loads(response.data.decode()) - assert data['message'] == 'Token expired, please log back in' + assert data["message"] == "Token expired, please log back in" assert response.status_code == 401 @staticmethod @@ -330,16 +330,13 @@ def test_delete_user(client): password="12345", ) data_register = json.loads(resp_register.data.decode()) - assert data_register['message'] == 'Successfully registered.' - assert data_register['auth_token'] + assert data_register["message"] == "Successfully registered." + assert data_register["auth_token"] response = client.delete( f"{client.config['REST_URI']}/user/username", headers=dict(Authorization="Bearer " + data_register["auth_token"]), ) data = json.loads(response.data.decode()) - assert ( - data["message"] - == 'Successfully deleted.' - ) + assert data["message"] == "Successfully deleted." assert response.status_code == 200 diff --git a/server/requirements.txt b/server/requirements.txt index 3abd539dde..b17144c4b1 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -2,6 +2,7 @@ boto3 elasticsearch1==1.10.0 email-validator flask +flask-bcrypt flask-restful flask-cors flask-jwt-extended