Commit 7e5593bc authored by Alex Kakiris's avatar Alex Kakiris
Browse files

Refine log levels in register service

parent ac7be123
Loading
Loading
Loading
Loading
Loading
+12 −8
Original line number Diff line number Diff line
@@ -31,6 +31,7 @@ def generate_tokens(username):
    }
    access_token = jwt.encode(access_payload, current_app.config['REGISTRE_SECRET_KEY'], algorithm='HS256')
    refresh_token = jwt.encode(refresh_payload, current_app.config['REGISTRE_SECRET_KEY'], algorithm='HS256')
    # TODO: should we remove this log to avoid logging access/refresh tokens?
    current_app.logger.debug(f"Access token : {access_token}\nRefresh token : {refresh_token}")
    return access_token, refresh_token

@@ -42,11 +43,11 @@ def verify_password(username, password):
    client = MongoDatabse()
    admin = client.get_col_by_name(client.capif_admins).find_one({"admin_name": username})
    if admin and check_password(password, admin["admin_pass"]):
        current_app.logger.debug(f"Verified admin {username}")
        current_app.logger.info(f"Verified admin {username}")
        return username, "admin"
    for user in users:
        if user["username"] == username and check_password(password, user["password"]):
            current_app.logger.debug(f"Verified user {username}")
            current_app.logger.info(f"Verified user {username}")
            return username, "client"


@@ -58,15 +59,16 @@ def admin_required():
            current_app.logger.debug("Checking admin token...")
            token = request.headers.get('Authorization')
            if not token:
                current_app.logger.debug("Token is missing.")
                current_app.logger.warning("Token is missing.")
                return jsonify({'message': 'Token is missing'}), 401
            
            if token.startswith('Bearer '):
                # Token is not missing but provided with the "Bearer " prefix. Consider changing the following message accordingly or remove it.
                current_app.logger.debug("Token is missing.")
                token = token.split('Bearer ')[1]
            
            if not token:
                current_app.logger.debug("Token is missing.")
                current_app.logger.warning("Token is missing.")
                return jsonify({'message': 'Token is missing'}), 401

            try:
@@ -85,7 +87,7 @@ def admin_required():
def login():
    username, rol = auth.current_user()
    if rol != "admin":
        current_app.logger.debug(f"User {username} trying to log in as admin")
        current_app.logger.warning(f"User {username} trying to log in as admin")
        return jsonify(message="Unauthorized. Administrator privileges required."), 401
    access_token, refresh_token = generate_tokens(username)
    return jsonify({'access_token': access_token, 'refresh_token': refresh_token})
@@ -117,24 +119,26 @@ def register(username):
    }

    user_info = request.get_json()
    # TODO: consider excluding sensitive fields (e.g. password) from logged user info even in debug mode.
    # Example: log_user_info = {k: v for k, v in user_info.items() if k != "password"}
    current_app.logger.debug(f"User Info: {user_info}")
    missing_fields = []
    for field, field_type in required_fields.items():
        if field not in user_info:
            missing_fields.append(field)
        elif not isinstance(user_info[field], field_type):
            current_app.logger.debug(f"Error: Field {field} must be of type {field_type.__name__}")
            current_app.logger.warning(f"Error: Field {field} must be of type {field_type.__name__}")
            return jsonify({"error": f"Field '{field}' must be of type {field_type.__name__}"}), 400

    for field, field_type in optional_fields.items():
        if field in user_info and not isinstance(user_info[field], field_type):
            current_app.logger.debug(f"Error: Field {field} must be of type {field_type.__name__}")
            current_app.logger.warning(f"Error: Field {field} must be of type {field_type.__name__}")
            return jsonify({"error": f"Optional field '{field}' must be of type {field_type.__name__}"}), 400
        if field not in user_info:
            user_info[field] = None

    if missing_fields:
        current_app.logger.debug(f"Error: missing requuired fields : {missing_fields}")
        current_app.logger.warning(f"Error: missing requuired fields : {missing_fields}")
        return jsonify({"error": "Missing required fields", "fields": missing_fields}), 400

    return register_operation.register_user(user_info)
+12 −4
Original line number Diff line number Diff line
@@ -24,7 +24,7 @@ class RegisterOperations:
        mycol = self.db.get_col_by_name(self.db.capif_users)
        exist_user = mycol.find_one({"username": user_info["username"]})
        if exist_user:
            current_app.logger.debug(f"User already exists : {user_info["username"]}")
            current_app.logger.warning(f"User already exists : {user_info["username"]}")
            return jsonify("user already exists"), 409
        
        name_space = uuid.UUID(self.config["register"]["register_uuid"])
@@ -36,7 +36,7 @@ class RegisterOperations:
        user_info["password"] = hash_password(user_info["password"])
        mycol.insert_one(user_info)

        current_app.logger.debug(f"User with uuid {user_uuid} and username {user_info["username"]} registered successfully")
        current_app.logger.info(f"User with uuid {user_uuid} and username {user_info["username"]} registered successfully")

        return jsonify(message="User registered successfully", uuid=user_uuid), 201

@@ -49,10 +49,11 @@ class RegisterOperations:
            exist_user = mycol.find_one({"username": username})

            if exist_user is None:
                current_app.logger.debug(f"No user exists with these credentials: {username}")
                current_app.logger.warning(f"No user exists with these credentials: {username}")
                return jsonify("No user exists with these credentials"), 400

            access_token = create_access_token(identity=(username + " " + exist_user["uuid"]))
            # TODO: should we remove this log to avoid logging access/refresh tokens?
            current_app.logger.debug(f"Access token generated for user {username} : {access_token}")
            
            cert_file = open("certs/ca_root.crt", 'rb')
@@ -71,6 +72,8 @@ class RegisterOperations:
                            ccf_security_url="capif-security/v1/trustedInvokers/<apiInvokerId>"), 200

        except Exception as e:
            # TODO: consider logging exceptions here for troubleshooting.
            # Example: current_app.logger.exception(f"Unexpected error in get_auth for user {username}")
            return jsonify(message=f"Errors when try getting auth: {e}"), 500

    def remove_user(self, uuid):
@@ -84,20 +87,25 @@ class RegisterOperations:
            
            current_app.logger.debug(f"Removing User with uuid {uuid} from db")
            mycol.delete_one({"uuid": uuid})
            current_app.logger.debug(f"User with uuid {uuid} removed successfully")
            current_app.logger.info(f"User with uuid {uuid} removed successfully")
            return jsonify(message="User removed successfully"), 204
        except Exception as e:
            # TODO: consider logging exceptions here for troubleshooting.
            # Example: current_app.logger.exception(f"Unexpected error in remove_user for uuid {uuid}")
            return jsonify(message=f"Errors when try remove user: {e}"), 500
        
    def get_users(self):
        mycol = self.db.get_col_by_name(self.db.capif_users)

        try:
            # TODO: consider excluding sensitive fields (e.g. password) from logged user info even in debug mode.
            current_app.logger.debug(f"users")
            users=list(mycol.find({}, {"_id":0}))
            current_app.logger.debug(f"{users}")
            return jsonify(message="Users successfully obtained", users=users), 200
        except Exception as e:
            # TODO: consider logging exceptions here for troubleshooting.
            # Example: current_app.logger.exception(f"Unexpected error in get_users")
            return jsonify(message=f"Error trying to get users: {e}"), 500