Skip to content

Commit 370fa9e

Browse files
authored
Merge pull request #195 from hoomano/kroussel/authenticate_with_secret_as_decorator
start refacto with decorator to authenticate with secret
2 parents 2a95621 + bec28d3 commit 370fa9e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+195
-295
lines changed

backend/app/app.py

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
from gevent import monkey
2-
3-
42
monkey.patch_all()
53

64
import hashlib
75
import random
86
import string
97
from packaging import version
10-
118
from flask import Flask
129
from flask_socketio import SocketIO, join_room, ConnectionRefusedError, emit
1310
from flask_restful import Api
@@ -36,7 +33,6 @@
3633
cors_allowed_origins="*", )
3734

3835
from flask_restful import request
39-
from functools import wraps
4036
import jwt
4137

4238
from datetime import datetime
@@ -60,43 +56,6 @@
6056
timing_logger = TimingLogger("/data/timing_logs.log")
6157

6258

63-
def authenticate_function(token):
64-
try:
65-
payload = jwt.decode(token, os.environ["JWT_SECRET"], algorithms=os.environ["ENCODING_ALGORITHM"])
66-
user_id = payload["sub"].split(os.environ['TOKEN_SECRET_SPLITTER'])[0]
67-
return True, user_id
68-
except KeyError:
69-
return {"error": "Authorization key required"}, 403
70-
except jwt.ExpiredSignatureError:
71-
return {"error": "Token expired."}, 403
72-
except jwt.InvalidTokenError:
73-
return {"error": "Invalid token."}, 403
74-
75-
76-
def authenticate(methods=["PUT", "POST", "DELETE", "GET"]):
77-
methods = [name.lower() for name in methods]
78-
79-
def authenticate_wrapper(func):
80-
@wraps(func)
81-
def wrapper(*args, **kwargs):
82-
83-
if func.__name__ not in methods:
84-
return func(*args, **kwargs)
85-
try:
86-
token = request.headers['Authorization']
87-
auth = authenticate_function(token)
88-
if auth[0] is not True:
89-
return auth
90-
else:
91-
kwargs["user_id"] = auth[1]
92-
except Exception as e:
93-
return {"error": f"Authentication error : {e}"}, 403
94-
95-
return func(*args, **kwargs)
96-
97-
return wrapper
98-
99-
return authenticate_wrapper
10059

10160

10261
def generate_session_id(user_id):

backend/app/routes/associate_free_product.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from jinja2 import Template
66
from flask import request
77
from flask_restful import Resource
8-
from app import authenticate, db
8+
from app import db
9+
from mojodex_core.authentication import authenticate
910
from mojodex_core.logging_handler import log_error
1011
from mojodex_core.entities.db_base_entities import MdPurchase, MdProduct, MdProductCategory, MdUser, MdEvent
1112
from models.purchase_manager import PurchaseManager

backend/app/routes/check_expired_purchases.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from flask import request
55
from flask_restful import Resource
66
from app import db
7+
from mojodex_core.authentication import authenticate_with_scheduler_secret
78
from mojodex_core.logging_handler import log_error
89
from mojodex_core.entities.db_base_entities import *
910

@@ -17,22 +18,16 @@
1718

1819
class ExpiredPurchasesChecker(Resource):
1920

21+
def __init__(self):
22+
ExpiredPurchasesChecker.method_decorators = [authenticate_with_scheduler_secret(methods=["POST"])]
23+
2024
# checking for expired purchases
2125
def post(self):
2226
error_message = "Error checking for expired purchases"
2327
if not request.is_json:
2428
log_error(f"{error_message} : Request must be JSON", notify_admin=True)
2529
return {"error": "Invalid request"}, 400
2630

27-
try:
28-
secret = request.headers['Authorization']
29-
if secret != os.environ["MOJODEX_SCHEDULER_SECRET"]:
30-
log_error(f"{error_message} : Authentication error : Wrong secret", notify_admin=True)
31-
return {"error": "Authentication error : Wrong secret"}, 403
32-
except KeyError:
33-
log_error(f"{error_message} : Missing Authorization secret in headers", notify_admin=True)
34-
return {"error": f"Missing Authorization secret in headers"}, 403
35-
3631
try:
3732
timestamp = request.json['datetime']
3833
n_purchases = min(50, int(request.args["n_purchases"])) if "n_purchases" in request.args else 50

backend/app/routes/company.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import requests
33
from flask import request
44
from flask_restful import Resource
5-
from app import db, authenticate
5+
from app import db
6+
from mojodex_core.authentication import authenticate
67
from mojodex_core.documents.website_parser import WebsiteParser
78
from mojodex_core.logging_handler import log_error
89
from mojodex_core.entities.db_base_entities import MdCompany, MdUser

backend/app/routes/device.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from app import authenticate, db
1+
from app import db
2+
from mojodex_core.authentication import authenticate
23
from mojodex_core.logging_handler import log_error
34
from mojodex_core.entities.db_base_entities import *
45
from flask import request

backend/app/routes/error.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from flask import request
22
from flask_restful import Resource
3-
from app import authenticate
3+
from mojodex_core.authentication import authenticate
44
from mojodex_core.logging_handler import log_error
55

66

backend/app/routes/free_users_engagement.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from flask import request
66
from flask_restful import Resource
77
from app import db
8+
from mojodex_core.authentication import authenticate_with_scheduler_secret
89
from mojodex_core.logging_handler import log_error
910
from mojodex_core.entities.db_base_entities import *
1011
from sqlalchemy import func, text, and_
@@ -19,6 +20,10 @@
1920
class FreeUsersEngagementChecker(Resource):
2021
logger_prefix = "FreeUsersEngagementChecker::"
2122

23+
def __init__(self):
24+
FreeUsersEngagementChecker.method_decorators = [authenticate_with_scheduler_secret(methods=["POST"])]
25+
26+
2227

2328
def __init__(self):
2429
self.logger = MojodexBackendLogger(FreeUsersEngagementChecker.logger_prefix)
@@ -44,15 +49,6 @@ def post(self):
4449
log_error(f"{error_message} : Request must be JSON")
4550
return {"error": "Request must be JSON"}, 400
4651

47-
try:
48-
secret = request.headers['Authorization']
49-
if secret != os.environ["MOJODEX_SCHEDULER_SECRET"]:
50-
log_error(f"{error_message} : Authentication error : Wrong secret", notify_admin=True)
51-
return {"error": "Authentication error : Wrong secret"}, 403
52-
except KeyError:
53-
log_error(f"{error_message} : Missing Authorization secret in headers", notify_admin=True)
54-
return {"error": f"Missing Authorization secret in headers"}, 403
55-
5652
try:
5753
timestamp = request.json['datetime']
5854
n_disengaged_users = min(50, int(request.json["n_disengaged_users"])) if "n_disengaged_users" in request.json else 50

backend/app/routes/goal.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from flask import request
22
from flask_restful import Resource
3-
from app import db, authenticate
3+
from app import db
4+
from mojodex_core.authentication import authenticate
45
from mojodex_core.logging_handler import log_error
56
from mojodex_core.entities.db_base_entities import *
67

backend/app/routes/home_chat.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
from mojodex_core.tag_manager import TagManager
44
from flask import request
55
from flask_restful import Resource
6-
from app import authenticate, db, server_socket
7-
6+
from app import db, server_socket
7+
from mojodex_core.authentication import authenticate, authenticate_with_scheduler_secret
88
from mojodex_core.knowledge_manager import KnowledgeManager
99

1010
from mojodex_core.entities.message import Message
@@ -28,7 +28,7 @@ class HomeChat(Resource):
2828
message_body_start_tag, message_body_end_tag = "<message_body>", "</message_body>"
2929

3030
def __init__(self):
31-
HomeChat.method_decorators = [authenticate(methods=["GET", "POST"])]
31+
HomeChat.method_decorators = [authenticate(methods=["GET", "POST"]), authenticate_with_scheduler_secret(methods=["PUT"])]
3232
self.session_creator = SessionCreator()
3333

3434
@with_db_session
@@ -191,15 +191,6 @@ def get(self, user_id):
191191
def put(self):
192192
error_message = "Error preparing next week first home chat"
193193

194-
try:
195-
secret = request.headers['Authorization']
196-
if secret != os.environ["MOJODEX_SCHEDULER_SECRET"]:
197-
log_error(f"{error_message} : Authentication error : Wrong secret", notify_admin=True)
198-
return {"error": "Authentication error : Wrong secret"}, 403
199-
except KeyError:
200-
log_error(f"{error_message} : Missing Authorization secret in headers", notify_admin=True)
201-
return {"error": f"Missing Authorization secret in headers"}, 403
202-
203194
if not request.is_json:
204195
log_error(f"{error_message} : Request must be JSON")
205196
return {"error": "Request must be JSON"}, 400

backend/app/routes/image.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
from flask import request
55
from flask_restful import Resource
6-
from app import db, authenticate
6+
from app import db
7+
from mojodex_core.authentication import authenticate
78
from mojodex_core.logging_handler import log_error
89
from flask import send_file
910
from mojodex_core.user_storage_manager.user_images_file_manager import UserImagesFileManager

0 commit comments

Comments
 (0)