refactor: Restructure project into a scalable package layout
This commit undertakes a major architectural refactoring to improve project organization, scalability, and maintainability
This commit is contained in:
parent
e8c84ba809
commit
69ffcee98f
6 changed files with 129 additions and 87 deletions
11
interbend/__init__.py
Normal file
11
interbend/__init__.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
from flask import Flask
|
||||
from config import Config
|
||||
|
||||
def create_app(config_class=Config):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config_class)
|
||||
|
||||
from interbend.routes import main_bp
|
||||
app.register_blueprint(main_bp)
|
||||
|
||||
return app
|
||||
35
interbend/auth.py
Normal file
35
interbend/auth.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
from functools import wraps
|
||||
from flask import request, jsonify, current_app
|
||||
import jwt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
def _getconfig():
|
||||
jwt_key = current_app.config['JWT_KEY']
|
||||
jwt_expire = current_app.config['JWT_EXPIRE'] # In days
|
||||
return jwt_key, jwt_expire
|
||||
|
||||
def jwt_required(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
jwt_key, _ = _getconfig()
|
||||
token = request.cookies.get("token")
|
||||
if not token:
|
||||
return jsonify({"error": "Authentication token missing"}), 400
|
||||
try:
|
||||
payload = jwt.decode(token, jwt_key, algorithms=["HS256"])
|
||||
request.bid = payload["bid"]
|
||||
except jwt.ExpiredSignatureError:
|
||||
return jsonify({"error": "Token expired"}), 401
|
||||
except jwt.InvalidTokenError:
|
||||
return jsonify({"error": "Invalid token"}), 401
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def token_gen(bid):
|
||||
jwt_key, jwt_expire = _getconfig()
|
||||
exptime = datetime.now(timezone.utc) + timedelta(days=jwt_expire)
|
||||
token = jwt.encode(
|
||||
{"bid": bid, "exp": exptime},
|
||||
jwt_key,
|
||||
algorithm="HS256")
|
||||
return token
|
||||
37
interbend/db.py
Normal file
37
interbend/db.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import mysql.connector
|
||||
from config import Config
|
||||
|
||||
db = mysql.connector.connect(
|
||||
host=Config.DB_HOST,
|
||||
user=Config.DB_USER,
|
||||
password=Config.DB_PASSWORD,
|
||||
database=Config.DB_NAME
|
||||
)
|
||||
|
||||
def init_db():
|
||||
with db.cursor(dictionary=True) as cursor:
|
||||
cursor.execute("CREATE TABLE IF NOT EXISTS users ("
|
||||
"bid VARCHAR(32) PRIMARY KEY,"
|
||||
"username VARCHAR(64) NOT NULL,"
|
||||
"email VARCHAR(128) NOT NULL,"
|
||||
"password_hash TEXT,"
|
||||
"balance DECIMAL(18, 2) DEFAULT 7500,"
|
||||
"job INT,"
|
||||
"salary_class INT,"
|
||||
"collected DATETIME"
|
||||
");")
|
||||
cursor.execute("CREATE TABLE IF NOT EXISTS salary ("
|
||||
"class INT PRIMARY KEY,"
|
||||
"money DECIMAL(18, 2));")
|
||||
cursor.execute("CREATE TABLE IF NOT EXISTS log("
|
||||
"time DATETIME PRIMARY KEY,"
|
||||
"bid VARCHAR(32),"
|
||||
"action TEXT);")
|
||||
db.commit()
|
||||
print("Tables Checked!")
|
||||
|
||||
def get_user(bid):
|
||||
"""Fetches a single user from the database by their bid."""
|
||||
with db.cursor(dictionary=True) as cur:
|
||||
cur.execute("SELECT * FROM users WHERE bid = %s", (bid,))
|
||||
return cur.fetchone()
|
||||
131
interbend/routes.py
Normal file
131
interbend/routes.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
from flask import Blueprint, make_response
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
import hmac
|
||||
import mysql.connector
|
||||
|
||||
# custom
|
||||
from interbend.db import db, get_user
|
||||
from interbend.auth import *
|
||||
|
||||
main_bp = Blueprint('main_bp', __name__)
|
||||
|
||||
@main_bp.route('/balance', methods=['GET'])
|
||||
def get_balance():
|
||||
bid = request.args.get('bid')
|
||||
user = get_user(bid)
|
||||
if not user:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
return jsonify({"balance": user["balance"]})
|
||||
|
||||
@main_bp.route('/register', methods=['POST'])
|
||||
def register():
|
||||
data = request.get_json()
|
||||
bid = data.get('bid')
|
||||
username = data.get('username')
|
||||
email = data.get('email')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not email or not password or not bid:
|
||||
return jsonify({"error": "Username, email, and password are required."}), 400
|
||||
password_hash = generate_password_hash(password)
|
||||
try:
|
||||
with db.cursor(dictionary=True) as cur:
|
||||
cur.execute("INSERT INTO users (bid, username, email, password_hash) VALUES (%s, %s, %s, %s)",
|
||||
(bid, username, email, password_hash))
|
||||
db.commit()
|
||||
token = token_gen(bid)
|
||||
response = make_response(jsonify({"message": "Login successful."}), 201)
|
||||
response.set_cookie('token', token, httponly=True, samesite='Strict', max_age=30 * 24 * 60 * 60)
|
||||
return response
|
||||
except mysql.connector.IntegrityError:
|
||||
return jsonify({"error": "Username or email already exists."}), 409
|
||||
|
||||
|
||||
|
||||
@main_bp.route('/login', methods=['POST'])
|
||||
def login():
|
||||
data = request.get_json()
|
||||
bid = data.get('bid')
|
||||
password = data.get('password')
|
||||
|
||||
if not bid or not password:
|
||||
return jsonify({"error": "BID and password are required"}), 400
|
||||
user = get_user(bid)
|
||||
if not user:
|
||||
return jsonify({"error": "User not found"}), 404
|
||||
if not check_password_hash(user['password_hash'], password):
|
||||
return jsonify({"error": "Invalid password"}), 401
|
||||
token = token_gen(bid)
|
||||
response = make_response(jsonify({"message": "Login successful."}), 200)
|
||||
response.set_cookie('token', token, httponly=True, samesite='Strict', max_age=30 * 24 * 60 * 60)
|
||||
# secure=True - Implement once HTTPS
|
||||
return response
|
||||
|
||||
@main_bp.route('/transfer', methods=['POST'])
|
||||
@jwt_required
|
||||
def transfer():
|
||||
# Ignore warning because its 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')
|
||||
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
|
||||
try:
|
||||
amount = float(amount)
|
||||
if amount <= 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
return jsonify({"error": "Invalid amount","message":"Try to request Money instead"}), 400
|
||||
sender = get_user(fbid)
|
||||
receiver = get_user(tbid)
|
||||
if not sender or not receiver:
|
||||
return jsonify({"error":"User not found"}), 404
|
||||
if sender["balance"] < amount:
|
||||
return jsonify({"error": "Insufficient funds"}), 400
|
||||
try:
|
||||
db.start_transaction()
|
||||
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))
|
||||
db.commit()
|
||||
return jsonify({"message": "Transfer successful"}), 200
|
||||
except mysql.connector.Error as err:
|
||||
db.rollback()
|
||||
print(f"Transactional Error: {err}")
|
||||
return jsonify({"error": "A database error occurred during the transfer."}), 500
|
||||
|
||||
|
||||
@main_bp.route('/admin/change-password', methods=['POST', 'PATCH'])
|
||||
def change_password():
|
||||
data = request.get_json()
|
||||
bid = data.get('bid')
|
||||
new_password = data.get('password')
|
||||
key = data.get('key')
|
||||
if not bid or not new_password or not key:
|
||||
return jsonify({"error": "BID, new password, and key are required"}), 400
|
||||
oskey = current_app.config['ADMIN_KEY']
|
||||
if not oskey or not hmac.compare_digest(key, oskey):
|
||||
return jsonify({"error": "Admin Key required"}), 403
|
||||
user = get_user(bid)
|
||||
if not user:
|
||||
return jsonify({"error": "User not found"}), 404
|
||||
new_password_hash = generate_password_hash(new_password)
|
||||
with db.cursor(dictionary=True) as cur:
|
||||
(cur.execute("UPDATE users SET password_hash = %s WHERE bid = %s", (new_password_hash, bid)))
|
||||
db.commit()
|
||||
return jsonify({"message": "Password changed successfully"}), 200
|
||||
|
||||
@main_bp.route('/collect', methods=['POST'])
|
||||
def collect_salary():
|
||||
return jsonify({"message":"no implementation"}), 501
|
||||
|
||||
@main_bp.route('/')
|
||||
def hello_world(): # put application's code here
|
||||
return 'Hello World!'
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue