Skip to content

Commit

Permalink
attempt to read header(it never arives :( )
Browse files Browse the repository at this point in the history
  • Loading branch information
violetaperezandrade committed Apr 11, 2024
1 parent 5bb10f0 commit 5ba6a9e
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 3 deletions.
5 changes: 3 additions & 2 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
LOGGING_LEVEL=
PORT=
USERS_HOST=
MEASUREMENTS_HOST=
PLANTS_HOST=
PLANTS_HOST=
JWT_SECRET=
HASH_ALGORITHM=
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ RUN pip install -r requirements.txt

EXPOSE 5000

CMD ["gunicorn", "wsgi:app", "-b", "0.0.0.0:5000"]
CMD ["gunicorn", "wsgi:app", "--reload", "-b", "0.0.0.0:5000"]
6 changes: 6 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import sys
import logging
from flask import Flask
from flask import request
from flask_restful import Api
from werkzeug.routing import BaseConverter
from src.resource import Gateway
Expand Down Expand Up @@ -33,6 +35,10 @@ def __init__(self, url_map, *items):

@app.after_request
def _build_cors_post_response(response):
print(f"Headers(post response): {request.headers}")
sys.stdout.flush()
# if 'Origin' in request.headers:
# response.headers.add("Access-Control-Allow-Origin", request.headers['Origin'])
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("Access-Control-Allow-Methods", "*")
Expand Down
44 changes: 44 additions & 0 deletions src/apps/users.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
import http.client
import os
import logging
import jwt
import sys

import requests
from flask import make_response


TOKEN_FIELD_NAME = "x-access-token"


def get_query_params(queryParam) -> str:
if not queryParam:
return ""
return f"?{str(queryParam, 'utf-8')}"


def _get_token(headers: dict):
keyName = None
for key in headers.keys():
if key.lower() == TOKEN_FIELD_NAME:
keyName = key
if not keyName:
return None
return headers.get(keyName)


def process_header(headers, body: dict) -> (dict, bool):
token = _get_token(headers)
if not token and not (body and "user_id" in body): # Check to not allow to bypass the token
return body, False
newBody = body.copy() if body else {}
try:
processToken = jwt.decode(token, key=os.getenv("HASH_SECRET"), algorithms=[os.getenv("HASH_ALGORITHM"), ])
newBody["user_id"] = processToken.get("id", "")
newBody["email"] = processToken.get("email")
except jwt.ExpiredSignatureError:
return {"message": "expired token", "status": http.client.UNAUTHORIZED}, True
except jwt.InvalidTokenError:
return {"message": "invalid token", "status": http.client.FORBIDDEN}, True
return newBody, False


class Users:
def __init__(self):
self.host = os.getenv("USERS_HOST")
Expand All @@ -29,12 +61,24 @@ def get(self, url, body, headers, query_params):
response.status_code)

def post(self, url, body, headers, query_params):
print(f"URL: {url}")
sys.stdout.flush()
if not(url.startswith("login")):
print(f"NO ES UN CASO DE LOG IN !!!!!!! {url}")
sys.stdout.flush()
body, error = process_header(headers, body)
if error:
print(f"ES UN CASO DE ERROR(SEGUIMOS EN LOG IN'T ) !!!!!!! {url}")
sys.stdout.flush()
return make_response(body, body.get("status"))
response = requests.post(f"{self.host}{url}"
f"{get_query_params(query_params)}",
json=body,
headers=headers)
logging.info(f"USERS | POST | {url}")
logging.debug(f"BODY: {body}")
print(f"headers: {headers}")
sys.stdout.flush()
return make_response(self.getResponseJson(response),
response.status_code)

Expand Down
1 change: 1 addition & 0 deletions src/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ def getExtraData():
body = request.json
else:
body = {}
print(f"en get extract data headers: {request.headers}")
headers = dict(request.headers)
if 'Host' in headers:
headers.pop('Host') # Invalid header
Expand Down

0 comments on commit 5ba6a9e

Please sign in to comment.