added better url fixes

This commit is contained in:
2025-02-17 15:41:48 -05:00
parent f988ddc489
commit 8b53ceb12d
2 changed files with 264 additions and 242 deletions
+258 -235
View File
@@ -1,23 +1,23 @@
from flask import ( from flask import (
Flask, Flask,
render_template, render_template,
request, request,
redirect, redirect,
url_for, url_for,
send_from_directory, send_from_directory,
flash, flash,
abort, abort,
jsonify, jsonify,
session session,
) )
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from flask_login import ( from flask_login import (
LoginManager, LoginManager,
UserMixin, UserMixin,
login_user, login_user,
logout_user, logout_user,
login_required, login_required,
current_user, current_user,
) )
from flask_apscheduler import APScheduler from flask_apscheduler import APScheduler
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
@@ -32,84 +32,112 @@ from secrets import token_hex
app = Flask(__name__) app = Flask(__name__)
try: try:
with open("/app/instance/secret.key", "rb") as f: with open("/app/instance/secret.key", "rb") as f:
app.config["SECRET_KEY"] = bytes.hex(f.readline()) app.config["SECRET_KEY"] = bytes.hex(f.readline())
except FileNotFoundError as e: except FileNotFoundError as e:
if not os.path.exists("/app/instance"): if not os.path.exists("/app/instance"):
os.mkdir("/app/instance") os.mkdir("/app/instance")
with open("/app/instance/secret.key", "wb") as f: with open("/app/instance/secret.key", "wb") as f:
newKey = token_hex(64) newKey = token_hex(64)
f.write(bytearray.fromhex(newKey)) f.write(bytearray.fromhex(newKey))
app.config["SECRET_KEY"] = newKey app.config["SECRET_KEY"] = newKey
PORT = 5121 PORT = 5121
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////app/instance/db.sqlite" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////app/instance/db.sqlite"
app.config["UPLOAD_FOLDER"] = "sites" app.config["UPLOAD_FOLDER"] = "sites"
app.config["SERVER_NAME"] = "tinysite.cloud" app.config["SERVER_NAME"] = "tinysite.cloud"
# app.config["SESSION_COOKIE_DOMAIN"] = ".tinysite.cloud" app.config["SESSION_COOKIE_DOMAIN"] = ".tinysite.cloud"
db = SQLAlchemy(app) db = SQLAlchemy(app)
RESERVED_SUBDOMAINS = { RESERVED_SUBDOMAINS = {
"", "",
"www", "www",
"api", "api",
"admin", "admin",
"support", "support",
"docs", "docs",
"blog", "blog",
"cdn", "cdn",
"test", "test",
"dev", "dev",
"staging", "staging",
"secure", "secure",
"mail", "mail",
"status", "status",
"gateway", "gateway",
} }
# TODO: add specific page redirects here as they're added # TODO: add specific page redirects here as they're added
def isDefaultRoute(hostname: str): def isDefaultRoute(hostname: str):
if hostname.count(".") < 2: # exactly the main domain
return True if hostname == app.config["SERVER_NAME"]:
return True
subdomain = hostname.split(".")[0] # a reserved subdomain
return not subdomain or subdomain in RESERVED_SUBDOMAINS parts = hostname.split(".")
server_parts = app.config["SERVER_NAME"].split(".")
# the host ends with the server domain
if parts[-len(server_parts) :] != server_parts:
return False
# subdomain portion
subdomain = ".".join(parts[: -len(server_parts)])
# any part of the subdomain is reserved
return (
any(part in RESERVED_SUBDOMAINS for part in subdomain.split("."))
or subdomain in RESERVED_SUBDOMAINS
)
# Models # Models
class User(UserMixin, db.Model): class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True) email = db.Column(db.String(100), unique=True)
password_hash = db.Column(db.String(128)) # Renamed for clarity password_hash = db.Column(db.String(128)) # Renamed for clarity
def set_password(self, password): def set_password(self, password):
self.password_hash = generate_password_hash(password) self.password_hash = generate_password_hash(password)
def check_password(self, password): def check_password(self, password):
return check_password_hash(self.password_hash, password) return check_password_hash(self.password_hash, password)
class Site(db.Model): class Site(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer) user_id = db.Column(db.Integer)
name = db.Column(db.String(100)) name = db.Column(db.String(100))
subdomain = db.Column(db.String(100), unique=True) subdomain = db.Column(db.String(100), unique=True)
last_accessed = db.Column(db.DateTime) last_accessed = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, default=datetime.utcnow) created_at = db.Column(db.DateTime, default=datetime.utcnow)
@app.context_processor
def inject_subdomain():
host = request.host
server_parts = app.config["SERVER_NAME"].split(".")
host_parts = host.split(".")
subdomain = None
if host_parts[-len(server_parts) :] == server_parts:
subdomain_parts = host_parts[: -len(server_parts)]
if subdomain_parts:
subdomain = ".".join(subdomain_parts)
return {
"SUBDOMAIN": subdomain,
"FULL_DOMAIN": host,
"SERVERNAME": app.config["SERVER_NAME"],
}
@app.errorhandler(404) @app.errorhandler(404)
def page_not_found(_): def page_not_found(_):
return render_template("404.html", domain=request.host), 404 return render_template("404.html", domain=request.host), 404
@app.context_processor
def inject_global_variable():
return {
"SERVERNAME": app.config["SERVER_NAME"],
}
# Auth setup # Auth setup
@@ -120,7 +148,7 @@ login_manager.login_view = "login"
@login_manager.user_loader @login_manager.user_loader
def load_user(user_id): def load_user(user_id):
return User.query.get(int(user_id)) return User.query.get(int(user_id))
# Scheduler for auto-deletion # Scheduler for auto-deletion
@@ -129,259 +157,254 @@ scheduler.init_app(app)
def delete_inactive_sites(): def delete_inactive_sites():
with app.app_context(): with app.app_context():
cutoff = datetime.utcnow() - timedelta(days=30) cutoff = datetime.utcnow() - timedelta(days=30)
sites = Site.query.filter(Site.last_accessed < cutoff).all() sites = Site.query.filter(Site.last_accessed < cutoff).all()
for site in sites: for site in sites:
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id) app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
) )
if os.path.exists(site_dir): if os.path.exists(site_dir):
shutil.rmtree(site_dir) shutil.rmtree(site_dir)
db.session.delete(site) db.session.delete(site)
db.session.commit() db.session.commit()
if not scheduler.running: if not scheduler.running:
scheduler.start() scheduler.start()
scheduler.add_job( scheduler.add_job(
id="delete_job", func=delete_inactive_sites, trigger="interval", days=1 id="delete_job", func=delete_inactive_sites, trigger="interval", days=1
) )
# Routes # Routes
@app.route("/login", methods=["GET", "POST"]) @app.route("/login", methods=["GET", "POST"])
def login(): def login():
if request.method == "POST": if request.method == "POST":
email = request.form.get("email") email = request.form.get("email")
password = request.form.get("password") password = request.form.get("password")
user = User.query.filter_by(email=email).first() user = User.query.filter_by(email=email).first()
if user and user.check_password(password): if user and user.check_password(password):
login_user(user) login_user(user)
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
flash("Invalid email or password") flash("Invalid email or password")
return render_template("login.html") return render_template("login.html")
@app.route("/logout") @app.route("/logout")
def logout(): def logout():
logout_user() logout_user()
return redirect(url_for("home")) return redirect(url_for("home"))
@app.route("/register", methods=["GET", "POST"]) @app.route("/register", methods=["GET", "POST"])
def register(): def register():
if request.method == "POST": if request.method == "POST":
email = request.form.get("email") email = request.form.get("email")
password = request.form.get("password") password = request.form.get("password")
if User.query.filter_by(email=email).first(): if User.query.filter_by(email=email).first():
flash("Email already exists") flash("Email already exists")
return redirect(url_for("register")) return redirect(url_for("register"))
new_user = User(email=email) new_user = User(email=email)
new_user.set_password(password) new_user.set_password(password)
db.session.add(new_user) db.session.add(new_user)
db.session.commit() db.session.commit()
login_user(new_user) login_user(new_user)
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
return render_template("register.html") return render_template("register.html")
@app.route("/dashboard") @app.route("/dashboard")
@login_required @login_required
def dashboard(): def dashboard():
sites = Site.query.filter_by(user_id=current_user.id).all() sites = Site.query.filter_by(user_id=current_user.id).all()
return render_template( return render_template(
"dashboard.html", "dashboard.html",
sites=sites, sites=sites,
subdomain=request.host.split(".")[0], subdomain=request.host.split(".")[0],
hostname=app.config["SERVER_NAME"], hostname=app.config["SERVER_NAME"],
) )
@app.route("/upload", methods=["POST"]) @app.route("/upload", methods=["POST"])
@login_required @login_required
def upload_site(): def upload_site():
site_name = request.form.get("name") site_name = request.form.get("name")
subdomain = request.form.get("subdomain").strip().lower() # normalize to lowercase subdomain = request.form.get("subdomain").strip().lower() # normalize to lowercase
# Subdomain validation # Subdomain validation
if not re.match(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", subdomain): if not re.match(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", subdomain):
flash( flash(
"Invalid subdomain. Use lowercase letters, numbers, and hyphens.", "error" "Invalid subdomain. Use lowercase letters, numbers, and hyphens.", "error"
) )
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
if not site_name or not subdomain: if not site_name or not subdomain:
flash("Site name and URL subdomain are required", "error") flash("Site name and URL subdomain are required", "error")
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
# Check subdomain availability # Check subdomain availability
if Site.query.filter_by(subdomain=subdomain).first(): if Site.query.filter_by(subdomain=subdomain).first():
flash("This URL is already taken", "error") flash("This URL is already taken", "error")
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
# Check if index.html is included # Check if index.html is included
files = request.files.getlist("files") files = request.files.getlist("files")
if not any(file.filename == "index.html" for file in files): if not any(file.filename == "index.html" for file in files):
flash("You must include an index.html file", "error") flash("You must include an index.html file", "error")
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
# Create site directory # Create site directory
site = Site(user_id=current_user.id, name=site_name, subdomain=subdomain) site = Site(user_id=current_user.id, name=site_name, subdomain=subdomain)
db.session.add(site) db.session.add(site)
db.session.commit() db.session.commit()
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id) app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
) )
os.makedirs(site_dir, exist_ok=True) os.makedirs(site_dir, exist_ok=True)
# Save uploaded files # Save uploaded files
for file in files: for file in files:
if file.filename == "": if file.filename == "":
continue continue
file.save(os.path.join(site_dir, file.filename)) file.save(os.path.join(site_dir, file.filename))
flash("Site created successfully!", "success") flash("Site created successfully!", "success")
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
@app.route("/edit/<int:site_id>", methods=["GET", "POST"]) @app.route("/edit/<int:site_id>", methods=["GET", "POST"])
@login_required @login_required
def edit_site(site_id): def edit_site(site_id):
site = Site.query.get_or_404(site_id) site = Site.query.get_or_404(site_id)
if site.user_id != current_user.id: if site.user_id != current_user.id:
return "Unauthorized", 403 return "Unauthorized", 403
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id) app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
) )
if request.method == "POST": if request.method == "POST":
site.name = request.form.get("name", site.name) site.name = request.form.get("name", site.name)
db.session.commit() db.session.commit()
for filename, content in request.form.items(): for filename, content in request.form.items():
if filename.endswith((".html", ".css", ".js")): if filename.endswith((".html", ".css", ".js")):
filepath = os.path.join(site_dir, filename) filepath = os.path.join(site_dir, filename)
with open(filepath, "w") as f: with open(filepath, "w") as f:
f.write(content) f.write(content)
if request.headers.get("X-Requested-With") == "XMLHttpRequest": if request.headers.get("X-Requested-With") == "XMLHttpRequest":
return jsonify({"success": True, "message": "Site updated successfully!"}) return jsonify({"success": True, "message": "Site updated successfully!"})
flash("Site updated successfully!", "success") flash("Site updated successfully!", "success")
return redirect(url_for("edit_site", site_id=site.id)) return redirect(url_for("edit_site", site_id=site.id))
files = {} files = {}
for file in os.listdir(site_dir): for file in os.listdir(site_dir):
with open(os.path.join(site_dir, file), "r") as f: with open(os.path.join(site_dir, file), "r") as f:
files[file] = f.read() files[file] = f.read()
return render_template("edit.html", site=site, files=files) return render_template("edit.html", site=site, files=files)
@app.route("/delete/<int:site_id>", methods=["POST"]) @app.route("/delete/<int:site_id>", methods=["POST"])
@login_required @login_required
def delete_site(site_id): def delete_site(site_id):
site = Site.query.get_or_404(site_id) site = Site.query.get_or_404(site_id)
if site.user_id != current_user.id: if site.user_id != current_user.id:
return "Unauthorized", 403 return "Unauthorized", 403
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id) app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
) )
if os.path.exists(site_dir): if os.path.exists(site_dir):
shutil.rmtree(site_dir) shutil.rmtree(site_dir)
db.session.delete(site) db.session.delete(site)
db.session.commit() db.session.commit()
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
@app.route("/delete_file/<int:site_id>/<filename>", methods=["POST"]) @app.route("/delete_file/<int:site_id>/<filename>", methods=["POST"])
@login_required @login_required
def delete_file(site_id, filename): def delete_file(site_id, filename):
# Get the site and verify ownership # Get the site and verify ownership
site = Site.query.get_or_404(site_id) site = Site.query.get_or_404(site_id)
if site.user_id != current_user.id: if site.user_id != current_user.id:
return "Unauthorized", 403 return "Unauthorized", 403
# Build the file path # Build the file path
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id) app.config["UPLOAD_FOLDER"], str(current_user.id), str(site.id)
) )
file_path = os.path.join(site_dir, filename) file_path = os.path.join(site_dir, filename)
# Delete the file if it exists # Delete the file if it exists
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
flash(f"File '{filename}' deleted successfully!", "success") flash(f"File '{filename}' deleted successfully!", "success")
else: else:
flash(f"File '{filename}' not found!", "error") flash(f"File '{filename}' not found!", "error")
return redirect(url_for("dashboard")) return redirect(url_for("dashboard"))
# use subdomains
@app.route("/", subdomain="<subdomain>", defaults={"filename": "index.html"}) @app.route("/", subdomain="<subdomain>", defaults={"filename": "index.html"})
@app.route("/<path:filename>") @app.route("/<path:filename>", subdomain="<subdomain>")
def serve_site_content(filename): def serve_site_content(subdomain, filename):
subdomain = request.host.split(".")[0] if isDefaultRoute(request.host):
abort(404) # Reserve default routes for main app
site = Site.query.filter_by(subdomain=subdomain).first_or_404() site = Site.query.filter_by(subdomain=subdomain).first_or_404()
site.last_accessed = datetime.utcnow() site.last_accessed = datetime.utcnow()
db.session.commit() db.session.commit()
site_dir = os.path.join( site_dir = os.path.join(
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id) app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
) )
if isDefaultRoute(request.host): # Security checks
return send_from_directory("index.html") if ".." in filename or filename.startswith("/") or not os.path.exists(site_dir):
abort(404)
# Security check try:
if ".." in filename or filename.startswith("/") or not os.path.exists(site_dir): return send_from_directory(site_dir, filename)
return render_template("404.html"), 404 except NotFound:
if "." not in filename:
try: try:
return send_from_directory(site_dir, filename) return send_from_directory(site_dir, f"{filename}.html")
except NotFound: except NotFound:
if "." not in filename: return send_from_directory(site_dir, "index.html")
try: abort(404)
return send_from_directory(site_dir, f"{filename}.html")
except NotFound:
redirect(app.config["SERVER_NAME"])
return send_from_directory(site_dir, "index.html")
abort(404)
def list_files(directory): def list_files(directory):
try: try:
return os.listdir(directory) return os.listdir(directory)
except FileNotFoundError: except FileNotFoundError:
return [] return []
@app.context_processor @app.context_processor
def inject_utilities(): def inject_utilities():
return dict(list_files=list_files) return dict(list_files=list_files)
@app.route("/") @app.route("/")
def home(): def home():
if isDefaultRoute(request.host): if not isDefaultRoute(request.host):
return render_template("home.html") abort(404)
else: return render_template("home.html")
return serve_site_content("index.html")
if __name__ == "__main__": if __name__ == "__main__":
os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True) os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
with app.app_context(): with app.app_context():
db.create_all() db.create_all()
serve(app, host="0.0.0.0", port=PORT) serve(app, host="0.0.0.0", port=PORT)
+6 -7
View File
@@ -13,14 +13,13 @@
<meta property="og:description" <meta property="og:description"
content="Host and share your static sites effortlessly with ION Static Site Hosting. Enjoy instant deployment, a sleek dark mode interface, and secure, private data handling!"> content="Host and share your static sites effortlessly with ION Static Site Hosting. Enjoy instant deployment, a sleek dark mode interface, and secure, private data handling!">
<meta property="og:image" content="{{ url_for('static', filename='hosting.png') }}"> <meta property="og:image" content="{{ url_for('static', filename='hosting.png') }}">
<meta property="og:url" content="https://{{session['servername']}}/"> <meta property="og:url" content="https://{{ SERVERNAME }}/">
<meta name="twitter:card" content="{{ url_for('static', filename='hosting.png') }}"> <meta name="twitter:card" content="{{ url_for('static', filename='hosting.png') }}">
<meta name="twitter:title" content="ION Static Site Hosting"> <meta name="twitter:title" content="ION Static Site Hosting">
<meta name="twitter:description" <meta name="twitter:description"
content="Host and share your static sites effortlessly with ION Static Site Hosting. Enjoy instant deployment, a sleek dark mode interface, and secure, private data handling!"> content="Host and share your static sites effortlessly with ION Static Site Hosting. Enjoy instant deployment, a sleek dark mode interface, and secure, private data handling!">
<meta name="twitter:image" content="{{ url_for('static', filename='hosting.png') }}"> <meta name="twitter:image" content="{{ url_for('static', filename='hosting.png') }}">
<title>ION Static Site Hosting - {% block title %}{% endblock %}</title> <title>ION Static Site Hosting - {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" id="theme-style"> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" id="theme-style">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"> <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
@@ -53,13 +52,13 @@
<body> <body>
<nav class="navbar"> <nav class="navbar">
<div class="container"> <div class="container">
<a href="https://{{ SERVERNAME }}">Home</a> <a href="{{ url_for('home', _external=True) }}">Home</a>
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<a href="https://{{ SERVERNAME }}/dashboard">Dashboard</a> <a href="{{ url_for('dashboard', _external=True) }}">Dashboard</a>
<a href="https://{{ SERVERNAME }}/logout">Logout</a> <a href="{{ url_for('logout', _external=True) }}">Logout</a>
{% else %} {% else %}
<a href="{{ url_for('login') }}">Login</a> <a href="{{ url_for('login', _external=True) }}">Login</a>
<a href="{{ url_for('register') }}">Register</a> <a href="{{ url_for('register', _external=True) }}">Register</a>
{% endif %} {% endif %}
<button id="theme-toggle" class="btn">Toggle Dark Mode</button> <button id="theme-toggle" class="btn">Toggle Dark Mode</button>
</div> </div>