Skip to content

Commit

Permalink
black reformat
Browse files Browse the repository at this point in the history
  • Loading branch information
npalaska committed Nov 13, 2020
1 parent 3b2fd36 commit cd922c3
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 106 deletions.
4 changes: 3 additions & 1 deletion lib/pbench/server/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 1 addition & 3 deletions lib/pbench/server/api/resources/alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 0 additions & 1 deletion lib/pbench/server/api/resources/elasticsearch_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import requests
from flask_restful import Resource, abort
from flask import request, make_response
Expand Down
22 changes: 14 additions & 8 deletions lib/pbench/server/api/resources/graphql_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import requests
from flask_restful import Resource, abort
from flask import request, make_response
Expand All @@ -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:
Expand All @@ -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",
)
Expand Down
8 changes: 4 additions & 4 deletions lib/pbench/server/api/resources/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
71 changes: 38 additions & 33 deletions lib/pbench/server/api/resources/pbench_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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']}"
)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
5 changes: 3 additions & 2 deletions lib/pbench/server/api/resources/upload_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import os
import humanize
import tempfile
Expand All @@ -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
Expand Down
42 changes: 0 additions & 42 deletions lib/pbench/test/unit/server/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='[email protected]', 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='[email protected]', 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):
Expand Down
21 changes: 9 additions & 12 deletions lib/pbench/test/unit/server/test_user_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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
1 change: 1 addition & 0 deletions server/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ boto3
elasticsearch1==1.10.0
email-validator
flask
flask-bcrypt
flask-restful
flask-cors
flask-jwt-extended
Expand Down

0 comments on commit cd922c3

Please sign in to comment.