app.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # app.py
  2. from flask import Flask, render_template, request, redirect, url_for, session, send_file, jsonify
  3. from flask_caching import Cache
  4. import requests.auth
  5. import os
  6. from lib.datetime import filter_accounts_current_month, filter_accounts_expired
  7. from lib.reqs import get_urls, get_user_accounts, add_user_account, delete_user_account, get_user_accounts_count
  8. from flask import send_from_directory
  9. import requests
  10. import base64
  11. from flask import Flask
  12. from config import DevelopmentConfig
  13. from paddleocr import PaddleOCR
  14. from PIL import Image
  15. import numpy as np
  16. os.environ["OMP_NUM_THREADS"] = "1"
  17. os.environ["MKL_NUM_THREADS"] = "1"
  18. app = Flask(__name__)
  19. app.config.from_object(
  20. DevelopmentConfig
  21. )
  22. cache = Cache(app, config={"CACHE_TYPE": "SimpleCache"})
  23. ocr = PaddleOCR(use_angle_cls=True, lang='en') # Adjust language if needed
  24. app.config['SESSION_COOKIE_SECURE'] = True # Only send cookie over HTTPS
  25. app.config['SESSION_COOKIE_HTTPONLY'] = True # Prevent JavaScript access
  26. app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # Adjust for cross-site requests
  27. app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60 * 24 * 365 # 1 year in seconds
  28. cache.clear() # Clears all cache entries
  29. @app.before_request
  30. def make_session_permanent():
  31. session.permanent = True
  32. @app.route('/manifest.json')
  33. def serve_manifest():
  34. return send_file('manifest.json', mimetype='application/manifest+json')
  35. @app.route("/favicon.ico")
  36. def favicon():
  37. return send_from_directory(
  38. os.path.join(app.root_path, "static"),
  39. "favicon.ico",
  40. mimetype="image/vnd.microsoft.icon",
  41. )
  42. @app.route("/")
  43. def index():
  44. # If the user is logged in, redirect to a protected page like /accounts
  45. if session.get("logged_in"):
  46. return redirect(url_for("home"))
  47. return render_template("index.html")
  48. @app.route("/home")
  49. @cache.cached(timeout=60) # cache for 120 seconds
  50. def home():
  51. if session.get("logged_in"):
  52. base_url = app.config["BASE_URL"] # Access base_url from the config
  53. all_accounts = get_user_accounts(base_url, session["auth_credentials"])
  54. count = len(all_accounts)
  55. current_month_accounts = filter_accounts_current_month(all_accounts)
  56. expired_accounts = filter_accounts_expired(all_accounts)
  57. return render_template(
  58. "home.html",
  59. username=session["username"],
  60. accounts=count,
  61. current_month_accounts=current_month_accounts,
  62. expired_accounts=expired_accounts,
  63. )
  64. return render_template("index.html")
  65. @app.route("/login", methods=["POST"])
  66. def login():
  67. username = request.form["username"]
  68. password = request.form["password"]
  69. # Encode the username and password in Base64
  70. credentials = f"{username}:{password}"
  71. encoded_credentials = base64.b64encode(credentials.encode()).decode()
  72. base_url = app.config["BASE_URL"] # Access base_url from the config
  73. login_url = f"{base_url}/Login" # Construct the full URL
  74. # Send GET request to the external login API with Basic Auth
  75. response = requests.get(
  76. login_url, auth=requests.auth.HTTPBasicAuth(username, password)
  77. )
  78. # Check if login was successful
  79. if response.status_code == 200 and response.json().get("auth") == "Success":
  80. # Set session variable to indicate the user is logged in
  81. session["logged_in"] = True
  82. session["username"] = username
  83. session["auth_credentials"] = encoded_credentials
  84. return redirect(url_for("home")) # Redirect to the Accounts page
  85. else:
  86. # Show error on the login page
  87. error = "Invalid username or password. Please try again."
  88. return render_template("index.html", error=error)
  89. @app.route("/urls", methods=["GET"])
  90. @cache.cached(timeout=300) # cache for 5 minutes
  91. def urls():
  92. # Check if the user is logged in
  93. if not session.get("logged_in"):
  94. return redirect(url_for("home"))
  95. # Placeholder content for Accounts page
  96. base_url = app.config["BASE_URL"] # Access base_url from the config
  97. return render_template(
  98. "urls.html", urls=get_urls(base_url, session["auth_credentials"])
  99. )
  100. @app.route("/accounts", methods=["GET"])
  101. @cache.cached(timeout=120) # cache for 120 seconds
  102. def user_accounts():
  103. # Check if the user is logged in
  104. if not session.get("logged_in"):
  105. return redirect(url_for("home"))
  106. # Placeholder content for Accounts page
  107. base_url = app.config["BASE_URL"] # Access base_url from the config
  108. return render_template(
  109. "user_accounts.html",
  110. username=session["username"],
  111. user_accounts=get_user_accounts(base_url, session["auth_credentials"]),
  112. auth=session["auth_credentials"],
  113. )
  114. @app.route("/accounts/add", methods=["GET", "POST"])
  115. def add_account():
  116. base_url = app.config["BASE_URL"] # Access base_url from the config
  117. if request.method == "POST":
  118. username = request.form["username"]
  119. password = request.form["password"]
  120. stream = request.form["stream"]
  121. if add_user_account(
  122. base_url, session["auth_credentials"], username, password, stream
  123. ):
  124. cache.clear() # Clears all cache entries
  125. return redirect(url_for("user_accounts"))
  126. return render_template("add_account.html")
  127. return render_template("add_account.html")
  128. @app.route("/accounts/delete", methods=["POST"])
  129. def delete_account():
  130. stream = request.form.get("stream")
  131. username = request.form.get("username")
  132. base_url = app.config["BASE_URL"]
  133. if delete_user_account(base_url, session["auth_credentials"], stream, username):
  134. cache.clear() # Clears all cache entries
  135. return redirect(url_for("user_accounts"))
  136. return redirect(url_for("user_accounts"))
  137. @app.route('/OCRupload', methods=['POST'])
  138. def OCRupload():
  139. if 'image' not in request.files:
  140. return jsonify({"error": "No image file found"}), 400
  141. # Get the uploaded file
  142. file = request.files['image']
  143. try:
  144. image = Image.open(file.stream)
  145. image_np = np.array(image)
  146. result = ocr.ocr(image_np)
  147. # Extract text
  148. extracted_text = []
  149. for line in result[0]:
  150. extracted_text.append(line[1][0])
  151. return render_template("add_account.html", username=extracted_text[2], password=extracted_text[3])
  152. except Exception as e:
  153. return jsonify({"error": str(e)}), 500
  154. if __name__ == "__main__":
  155. app.run(debug=app.config["DEBUG"], host=app.config["HOST"], port=app.config["PORT"])