From 3c5550beedee7653815ccee6724f855c0d5fb865 Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Sat, 20 Sep 2025 20:28:26 -0500 Subject: [PATCH 1/7] fix(admin): Correct variable name in add_money validation --- interbend/routes/admin_routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interbend/routes/admin_routes.py b/interbend/routes/admin_routes.py index b772692..6e8a81f 100644 --- a/interbend/routes/admin_routes.py +++ b/interbend/routes/admin_routes.py @@ -41,7 +41,7 @@ def add_money(): bid = data.get('bid') amount = data.get('amount') key = data.get('key') - if not bid or not money or not key: + if not bid or not amount or not key: return jsonify({"error": "BID, Amount and AdminKey are required"}), 400 if not _keychecker(key): return jsonify({"error":"Admin Key required"}), 403 From dcee6058cb6b2539ad4a3c7f57dff8796ddc8b2e Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Sat, 20 Sep 2025 20:59:19 -0500 Subject: [PATCH 2/7] feat: Add transaction routes and update configurations This commit introduces new transaction routes for handling various transaction-related operations. It also includes updates to the `config.py` file to support these new features. The following files were modified: - `README.md`: Updated documentation to clarify .env variables and their purposes - `To-Do.md`: Updated task meaningless - `config.py`: Added COLLECT_COOLDOWN and TAX_ACCOUNT_BID configurations. Main Thing: - `interbend/routes/transaction_routes.py`: Added boilerplate transaction to handle all transfers and separated business transfers with tax application. /transfer for personal transfers /transfer-business for business transfers with tax deduction TODO: add route to change tax rate and add non hardcoded tax rate. Type 6 and 7 are reserved for future use. currently implemented are 0 and 1. --- README.md | 5 +- To-Do.md | 6 +- config.py | 1 + interbend/routes/transaction_routes.py | 82 ++++++++++++++++++++------ 4 files changed, 73 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 05ef30d..78677a4 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,14 @@ Interbend is a Flask-based web application that provides a backend API for manag Create a `.env` file in the root directory of the project and add the following variables: ``` JWT_KEY=your_secret_jwt_key - JWT_EXPIRATION=30 + JWT_EXPIRATION=30 // jwt experation duration in days DB_HOST=your_database_host DB_USER=your_database_user DB_PASSWORD=your_database_password DB_NAME=your_database_name ADMIN_KEY=your_secret_admin_key - COLLECT_COOLDOWN=30 + COLLECT_COOLDOWN=24 // collect cooldown in hours + TAX_ACCOUNT_BID=BUSINESS_BID_HERE // tax account bid here ``` ## Usage diff --git a/To-Do.md b/To-Do.md index 238ab43..cfa7b53 100644 --- a/To-Do.md +++ b/To-Do.md @@ -14,4 +14,8 @@ This file tracks potential new features and improvements for the Interbend banki * **Description:** Create a new API endpoint (e.g., `GET /transactions`) that allows an authenticated user to retrieve a paginated list of their own transaction history. * **Benefits:** Provides users with transparency and a way to track their finances, which is a core feature of any banking application. - * FINISHED: PLEASE CHECK IF WORKING! \ No newline at end of file + * FINISHED: PLEASE CHECK IF WORKING! + +Frontend? + +idfk? \ No newline at end of file diff --git a/config.py b/config.py index 62a2adf..9659b73 100644 --- a/config.py +++ b/config.py @@ -19,3 +19,4 @@ class Config: # Admin ADMIN_KEY = os.getenv('ADMIN_KEY') COLLECT_COOLDOWN = int(os.getenv('COLLECT_COOLDOWN', 24)) + TAX_ACCOUNT_BID = os.getenv('TAX_ACCOUNT_BID') \ No newline at end of file diff --git a/interbend/routes/transaction_routes.py b/interbend/routes/transaction_routes.py index c8a2155..6d90d7b 100644 --- a/interbend/routes/transaction_routes.py +++ b/interbend/routes/transaction_routes.py @@ -94,23 +94,17 @@ def get_transactions(): return jsonify({"error": "An unexpected server error occurred."}), 500 -# this should be fine -@transactions_bp.route('/transfer', methods=['POST']) -@jwt_required -def transfer(): - # Ignore warning because it's dynamically added via jwt required. - user_bid = request.bid - data = request.get_json() - fbid = data.get('from') - tbid = data.get('to') - amount = data.get('amount') - note = data.get('note') - if not tbid or not amount: - return jsonify({"error": "To and amount are required"}), 400 - if not fbid: - fbid = user_bid - if fbid != user_bid: - return jsonify({"error": "Unauthorized transfer from another account"}), 401 +# this should be fine (not) + +def transfer_boilerplate(user_bid, fbid, tbid, amount, note, type): + if not user_bid or not fbid or not tbid or not amount: + return jsonify({"error": "From, To, and amount are required"}), 400 + if not note: + print(f"{type} failed to provide note. No trace available because I am lazy to program such things.") + return jsonify ({"error": "Note shouldve been passed by internal method."}), 500 + if not type in [0, 1, 2, 3, 4, 5, 6, 7, 8]: # 0 = personal, 1 = business, 2 = fine, 3 = salary, 4 = bill, 5 = admin adjustment, 6 = placeholder, 7 = placeholder2, 8 = other + print(f"type was {type}, which is invalid. This is a bug. Internal Method failed to provide a valid type. No trace available because I am lazy to program such things.") + return jsonify({"error": "Internal method failed to provide a valid type."}), 500 try: amount = float(amount) if amount <= 0: @@ -121,6 +115,15 @@ def transfer(): receiver = get_user(tbid) if not sender or not receiver: return jsonify({"error":"User not found"}), 404 + # here is space to add tax if its a business transaction. + if type == 1: # Business Transfer + gtax = 0.3 # 30% tax for business transactions - configurable later TO DO + tax = amount * gtax + note += f" (Tax applied: {tax})" + tax_account_bid = Config.TAX_ACCOUNT_BID + if sender["balance"] < amount + tax: + return jsonify({"error": "Insufficient funds"}), 400 + if sender["balance"] < amount: return jsonify({"error": "Insufficient funds"}), 400 try: @@ -128,6 +131,9 @@ def transfer(): with db.cursor(dictionary=True) as cur: cur.execute("UPDATE users SET balance = balance - %s WHERE bid = %s", (amount, fbid)) cur.execute("UPDATE users SET balance = balance + %s WHERE bid = %s", (amount, tbid)) + if type == 1: # Business Transfer + cur.execute("UPDATE users SET balance = balance - %s WHERE bid = %s", (tax, fbid)) + cur.execute("UPDATE users SET balance = balance + %s WHERE bid = %s", (tax, tax_account_bid)) cur.execute("INSERT INTO transactions (source, target, amount, note, type, timestamp, status) VALUES (%s, %s, " "%s, %s, %s, %s)", fbid, tbid, amount, note, "transfer", datetime.now(timezone.utc), "completed", ) @@ -136,4 +142,44 @@ def transfer(): except mysql.connector.Error as err: db.rollback() print(f"Transactional Error: {err}") - return jsonify({"error": "A database error occurred during the transfer."}), 500 \ No newline at end of file + return jsonify({"error": "A database error occurred during the transfer."}), 500 + +# PERSONAL TRANSFERS +@transactions_bp.route('/transfer', methods=['POST']) +@jwt_required +def transfer(): + # Ignore warning because it's dynamically added via jwt required. + user_bid = request.bid + data = request.get_json() + fbid = data.get('from') + tbid = data.get('to') + amount = data.get('amount') + note = data.get('note') + type = int(0) # Personal Transfer + if not fbid: + user_bid = fbid + if fbid != user_bid: + return jsonify({"error": "Unauthorized transfer from another account"}), 401 + if not note: + note = "No note provided, Personal Transfer from " + fbid + return transfer_boilerplate(user_bid, fbid, tbid, amount, note, type) + +# BUSINESS TRANSFERS +@transactions_bp.route('/transfer', methods=['POST']) +@jwt_required +def transfer(): + # Ignore warning because it's dynamically added via jwt required. + user_bid = request.bid + data = request.get_json() + fbid = data.get('from') + tbid = data.get('to') + amount = data.get('amount') + note = data.get('note') + type = int(1) # Business Transfer + if not fbid: + user_bid = fbid + if fbid != user_bid: + return jsonify({"error": "Unauthorized transfer from another account"}), 401 + if not note: + note = "No note provided, Business Transfer from " + fbid + return transfer_boilerplate(user_bid, fbid, tbid, amount, note, type) \ No newline at end of file From 2987adad3e3e424d0fac182050d5c855c1212295 Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Sat, 20 Sep 2025 21:04:30 -0500 Subject: [PATCH 3/7] fix two routes being named equally --- interbend/routes/transaction_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interbend/routes/transaction_routes.py b/interbend/routes/transaction_routes.py index 6d90d7b..5635e3c 100644 --- a/interbend/routes/transaction_routes.py +++ b/interbend/routes/transaction_routes.py @@ -165,9 +165,9 @@ def transfer(): return transfer_boilerplate(user_bid, fbid, tbid, amount, note, type) # BUSINESS TRANSFERS -@transactions_bp.route('/transfer', methods=['POST']) +@transactions_bp.route('/transfer-business', methods=['POST']) @jwt_required -def transfer(): +def transfer_business(): # Ignore warning because it's dynamically added via jwt required. user_bid = request.bid data = request.get_json() From 132545f996593b89193d3c43af3cba5e87a29cc8 Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Sat, 20 Sep 2025 21:07:50 -0500 Subject: [PATCH 4/7] docs: Add request body details for transfer-business endpoint in README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 78677a4..e3b8050 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,10 @@ The application will start in debug mode on `http://127.0.0.1:5000`. - **Request Body**: `{ "to": "recipient_bid", "amount": 50.00, "note": "Payment for services" }` - **Response**: A success message. +- **`POST /transfer-business`**: Transfers a specified amount from the authenticated user to another user with an appled tax. + - **Authentication**: JWT token required. + - **Request Body**: `{ "to": "recipient_bid", "amount": 50.00, "note": "Payment for services" }` + - **Response**: A success message. ### Admin All admin endpoints require an admin key in the request body. From 7b9521391456d8fc1af472b790d2929320fbf64c Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Sat, 20 Sep 2025 21:16:25 -0500 Subject: [PATCH 5/7] updated to do --- To-Do.md | 45 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/To-Do.md b/To-Do.md index cfa7b53..29ca1fb 100644 --- a/To-Do.md +++ b/To-Do.md @@ -4,18 +4,41 @@ This file tracks potential new features and improvements for the Interbend banki ## Feature Suggestions -1. **Automated Payroll System:** - * **Description:** Instead of requiring users to manually call the `/collect` endpoint, a scheduled script could run periodically (e.g., every 24 hours) to automatically distribute salaries to all eligible users. - * **Benefits:** Improves user experience, ensures consistent pay, and reduces repeated API calls to the server. - * **Important:** Due to the concept of this whole system it needs to be considered to only pay users who are attend. Bad Idea. - * **Alternative:** Implement system to make sure you can only collect if the host is online. Make admin route to open server (set global bool) +1. **Automated Payroll System** + * **Description:** Instead of requiring users to manually call the `/collect` endpoint, a scheduled script could run periodically to automatically distribute salaries to all eligible users. + * **Benefits:** Improves user experience, ensures consistent pay, and reduces repeated API calls to the server. + * **Status:** Under Review + * **Note:** Due to system concept, needs to be modified to only pay active users. + * **Alternative:** Implement system to verify host is online; add admin route to control server availability. -2. **User Transaction History:** - * **Description:** Create a new API endpoint (e.g., `GET /transactions`) that allows an authenticated user to retrieve a paginated list of their own transaction history. - * **Benefits:** Provides users with transparency and a way to track their finances, which is a core feature of any banking application. +2. **User Transaction History** + * **Description:** Create API endpoint for retrieving paginated transaction history. + * **Benefits:** Provides transparency and financial tracking for users. + * **Status:** COMPLETED + * **Note:** Needs verification testing. - * FINISHED: PLEASE CHECK IF WORKING! +3. **Changeable Tax Rate** + * **Description:** Add system for dynamic tax rate adjustment through admin interface. + * **Benefits:** Allows economic control and flexibility for different transaction types. + * **Status:** In Progress + * **Implementation:** Store in database for persistence, add admin routes for modification. -Frontend? +4. **User Roles System** + * **Description:** Implement comprehensive role-based access control (RBAC). + * **Benefits:** Enables different permissions for police, government, admin, and regular users. + * **Status:** Not Started + * **Required Features:** + - Role assignment and management + - Permission hierarchy + - Role-specific interfaces + - Audit logging for role changes -idfk? \ No newline at end of file +5. **Frontend Development** + * **Description:** Create user interface for the banking system. + * **Benefits:** Provides intuitive access to banking features. + * **Status:** Not Started + * **Components Needed:** + - User dashboard + - Transaction interface + - Admin control panel + - Role-specific views \ No newline at end of file From e09463b59c05e80b2a127c4900d045eec604aa87 Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Wed, 24 Sep 2025 19:16:46 -0500 Subject: [PATCH 6/7] feat: Add Discord routes and configuration for bot key validation --- config.py | 3 +++ interbend/__init__.py | 2 ++ interbend/auth.py | 11 ++++++++++- interbend/routes/__init__.py | 0 interbend/routes/discord_routes.py | 26 ++++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 1 deletion(-) delete mode 100644 interbend/routes/__init__.py create mode 100644 interbend/routes/discord_routes.py diff --git a/config.py b/config.py index 9659b73..1acde42 100644 --- a/config.py +++ b/config.py @@ -9,6 +9,9 @@ class Config: # General Config JWT_KEY = os.getenv('JWT_KEY') JWT_EXPIRE = int(os.getenv('JWT_EXPIRATION', 30)) + + # Gets the Key to ensure discord bot requests are being done by the discord bot + BOT_KEY = os.getenv('BOT_KEY') # Database DB_HOST = os.getenv('DB_HOST') diff --git a/interbend/__init__.py b/interbend/__init__.py index bb81e6b..620b6ac 100644 --- a/interbend/__init__.py +++ b/interbend/__init__.py @@ -8,8 +8,10 @@ def create_app(config_class=Config): from .routes.auth_routes import auth_bp from .routes.transaction_routes import transactions_bp from .routes.admin_routes import admin_bp + from .routes.discord_routes import discord_bp app.register_blueprint(auth_bp) app.register_blueprint(transactions_bp) app.register_blueprint(admin_bp, url_prefix='/admin') + app.register_blueprint(discord_bp, url_prefix='/discord') return app \ No newline at end of file diff --git a/interbend/auth.py b/interbend/auth.py index dcf65ae..5ecafc0 100644 --- a/interbend/auth.py +++ b/interbend/auth.py @@ -40,4 +40,13 @@ def token_gen(bid): {"bid": bid, "exp": exptime}, jwt_key, algorithm="HS256") - return token \ No newline at end of file + return token + +def bot_key(input_key): + bot_key = current_app.config['BOT_KEY'] + if input_key != bot_key: + return False + if input_key == bot_key: # Extra Security which doesnt actually add anything but peace of mind. + return True + return "OhShit" # This should never happen?? +# I dont think I should be a programmer, I dont even understand python and prefer golang or java or C#. ANYTHING THAT HAS {} \ No newline at end of file diff --git a/interbend/routes/__init__.py b/interbend/routes/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/interbend/routes/discord_routes.py b/interbend/routes/discord_routes.py new file mode 100644 index 0000000..07091d9 --- /dev/null +++ b/interbend/routes/discord_routes.py @@ -0,0 +1,26 @@ +from flask import Blueprint, make_response +from interbend.db import db, get_user +from interbend.auth import * +import mysql.connector +from werkzeug.security import generate_password_hash, check_password_hash + +discord_bp = Blueprint('discord_bp', __name__) + +@discord_bp.route('/register-id', methods=['POST']) +def register_id(): + data = request.get_json() + bid = data.get('bid') + name = data.get('name') + origin = data.get('origin') + age = data.get('age') + gender = data.get('gender') + bot_key2 = data.get('bot_key') + if bot_key2 != current_app.config['BOT_KEY']: + return jsonify({"error": "Unauthorized"}), 401 + if not bid or not name or not origin or not age or not gender: + return jsonify({"error": "BID, name, origin, age, and gender are required"}), 400 + user = get_user(bid) + if not user: + return jsonify({"error": "User is not registered"}), 404 + # Should the user be automatically registered here? + return jsonify({"error": "Method not implemented"}), 501 \ No newline at end of file From af3f02341ed9e30dad93976e17f36346a127375e Mon Sep 17 00:00:00 2001 From: MrEisbear Date: Wed, 24 Sep 2025 19:42:46 -0500 Subject: [PATCH 7/7] feat: Update README and implement Discord user registration endpoints --- README.md | 9 ++++++ interbend/auth.py | 9 ++++-- interbend/routes/discord_routes.py | 47 +++++++++++++++++++++++++++++- 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e3b8050..1924ec1 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ Interbend is a Flask-based web application that provides a backend API for managing user balances and transactions. It features a robust authentication system using JWT and includes a separate set of administrative endpoints for system management. The application is designed to be extensible and can be used as a foundation for a variety of financial applications. +### Note +The GitHub branch may lag behind the development branch. For the most up-to-date code and pull requests, please visit [https://git.albioncloud.de/Eisbear/Interbend](https://git.albioncloud.de/Eisbear/Interbend). + ## Installation 1. **Clone the repository:** @@ -88,3 +91,9 @@ All admin endpoints require an admin key in the request body. - **`POST /admin/change-password`**: Changes the password for a user. - **Request Body**: `{ "bid": "user_bid", "password": "new_password", "key": "your_admin_key" }` - **Response**: A success message. +### Bot + +All bot endpoints require a bot key in the request body. These endpoints are designed with the InterBot discordbot in mind. +You should never use these manually because they trust the discord bot for authentication and are therefore insecure. +(i dont think thats best practice?) +// TODO - Add Discord End Points here \/ \ No newline at end of file diff --git a/interbend/auth.py b/interbend/auth.py index 5ecafc0..32d740e 100644 --- a/interbend/auth.py +++ b/interbend/auth.py @@ -42,11 +42,16 @@ def token_gen(bid): algorithm="HS256") return token -def bot_key(input_key): +def botKey(input_key): bot_key = current_app.config['BOT_KEY'] if input_key != bot_key: return False if input_key == bot_key: # Extra Security which doesnt actually add anything but peace of mind. return True return "OhShit" # This should never happen?? -# I dont think I should be a programmer, I dont even understand python and prefer golang or java or C#. ANYTHING THAT HAS {} \ No newline at end of file +# I dont think I should be a programmer, I dont even understand python and prefer golang or java or C#. ANYTHING THAT HAS {} + +def bot_key(input_key): + return botKey(input_key) +# Legacy, decaprecated (wait I didnt even implement this so why do I even keep this?) +# Random bloat :3 \ No newline at end of file diff --git a/interbend/routes/discord_routes.py b/interbend/routes/discord_routes.py index 07091d9..50ed41f 100644 --- a/interbend/routes/discord_routes.py +++ b/interbend/routes/discord_routes.py @@ -1,7 +1,9 @@ +from webbrowser import get from flask import Blueprint, make_response from interbend.db import db, get_user from interbend.auth import * import mysql.connector +import auth # For bot_key function from werkzeug.security import generate_password_hash, check_password_hash discord_bp = Blueprint('discord_bp', __name__) @@ -23,4 +25,47 @@ def register_id(): if not user: return jsonify({"error": "User is not registered"}), 404 # Should the user be automatically registered here? - return jsonify({"error": "Method not implemented"}), 501 \ No newline at end of file + return jsonify({"error": "Method not implemented"}), 501 + +@discord_bp.route('/register-2', methods=['POST']) +def register2(): + data = request.get_json() + bid = data.get('bid') + # Bid is now generated by API -- Not in this case because this is for the discord bot to register users + username = data.get('username') + email = data.get('email') + # This wont work because the bot wont have access to the email. Its a bot not OAuth, which will be added later. + password = data.get('password') # The bot will generate a random password and send it to the user via DM or something? + bot_key2 = data.get('bot_key') + if not botKey(bot_key2): + return jsonify({"error": "Unauthorized"}), 401 + + if not username or not password: + return jsonify({"error": "Bot error, did not supply username or password"}), 404 + password_hash = generate_password_hash(password) + if email == "example@example.com": + return jsonify({"error": "bro"}), 400 + bidf = "D-".join(bid) + try: + with db.cursor(dictionary=True) as cur: + cur.execute("SELECT * FROM users WHERE bid = %s", (bidf,)) + if cur.fetchone(): + return jsonify({"error": "BID already exists."}), 409 + except mysql.connector.Error as err: + db.rollback() + current_app.logger.error(f"Database error in register: {err}") + return jsonify({"error": "Database Error"}), 500 + try: + with db.cursor(dictionary=True) as cur: + cur.execute("INSERT INTO users (bid, username, password_hash) VALUES (%s, %s, %s)", + (bid, username, password_hash)) + db.commit() + return jsonify({"message": "Creation Successful"}), 201 + except mysql.connector.Error as err: + db.rollback() + current_app.logger.error(f"Database error in register: {err}") + return jsonify({"error": "Database Error"}), 500 + +@discord_bp.route('/balance', methods=['GET']) +def blo_chicken_tiki_masala(): #can I name it like this? + return jsonify({"error": "use normal balance bro"}), 404 \ No newline at end of file