app.py 6.4 KB

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