app.py 5.6 KB

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