mirror of
https://github.com/ION606/static-site-hosting.git
synced 2026-05-14 22:16:54 +00:00
shift to subdomains
This commit is contained in:
@@ -17,3 +17,7 @@ logs:
|
|||||||
|
|
||||||
clean: stop
|
clean: stop
|
||||||
rm -f output.log app.pid
|
rm -f output.log app.pid
|
||||||
|
|
||||||
|
reset: clean
|
||||||
|
rm -rf instance
|
||||||
|
rm -rf sites
|
||||||
@@ -25,15 +25,51 @@ import os
|
|||||||
import shutil
|
import shutil
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from waitress import serve
|
from waitress import serve
|
||||||
|
import re
|
||||||
|
from secrets import token_hex
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config["SECRET_KEY"] = "your-secret-key"
|
|
||||||
|
try:
|
||||||
|
with open("instance/secret.key", "rb") as f:
|
||||||
|
app.config["SECRET_KEY"] = bytes.hex(f.readline())
|
||||||
|
except FileNotFoundError as e:
|
||||||
|
os.mkdir('instance')
|
||||||
|
with open("instance/secret.key", "wb") as f:
|
||||||
|
newKey = token_hex(64)
|
||||||
|
f.write(bytearray.fromhex(newKey))
|
||||||
|
app.config["SECRET_KEY"] = newKey
|
||||||
|
|
||||||
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
|
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
|
||||||
app.config["UPLOAD_FOLDER"] = "sites"
|
app.config["UPLOAD_FOLDER"] = "sites"
|
||||||
|
app.config["SERVER_NAME"] = "tinysite.cloud"
|
||||||
|
app.config["SESSION_COOKIE_DOMAIN"] = ".tinysite.cloud"
|
||||||
db = SQLAlchemy(app)
|
db = SQLAlchemy(app)
|
||||||
|
|
||||||
|
|
||||||
|
RESERVED_SUBDOMAINS = {
|
||||||
|
"",
|
||||||
|
"www",
|
||||||
|
"api",
|
||||||
|
"admin",
|
||||||
|
"support",
|
||||||
|
"docs",
|
||||||
|
"blog",
|
||||||
|
"cdn",
|
||||||
|
"test",
|
||||||
|
"dev",
|
||||||
|
"staging",
|
||||||
|
"secure",
|
||||||
|
"mail",
|
||||||
|
"status",
|
||||||
|
"gateway"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def isDefaultRoute(subdomain):
|
||||||
|
return not subdomain 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)
|
||||||
@@ -51,11 +87,16 @@ 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))
|
||||||
slug = 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.errorhandler(404)
|
||||||
|
def page_not_found(_):
|
||||||
|
return render_template("404.html", domain=request.host), 404
|
||||||
|
|
||||||
|
|
||||||
# Auth setup
|
# Auth setup
|
||||||
login_manager = LoginManager()
|
login_manager = LoginManager()
|
||||||
login_manager.init_app(app)
|
login_manager.init_app(app)
|
||||||
@@ -138,21 +179,28 @@ def register():
|
|||||||
@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("dashboard.html", sites=sites)
|
return render_template("dashboard.html", sites=sites, subdomain=request.host.split('.')[0], 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")
|
||||||
slug = request.form.get("slug").strip()
|
subdomain = request.form.get("subdomain").strip().lower() # normalize to lowercase
|
||||||
|
|
||||||
if not site_name or not slug:
|
# Subdomain validation
|
||||||
flash("Site name and URL slug are required", "error")
|
if not re.match(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", subdomain):
|
||||||
|
flash(
|
||||||
|
"Invalid subdomain. Use lowercase letters, numbers, and hyphens.", "error"
|
||||||
|
)
|
||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
# Check slug availability
|
if not site_name or not subdomain:
|
||||||
if Site.query.filter_by(slug=slug).first():
|
flash("Site name and URL subdomain are required", "error")
|
||||||
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
|
# Check subdomain availability
|
||||||
|
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"))
|
||||||
|
|
||||||
@@ -163,7 +211,7 @@ def upload_site():
|
|||||||
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, slug=slug)
|
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()
|
||||||
|
|
||||||
@@ -259,10 +307,13 @@ def delete_file(site_id, filename):
|
|||||||
return redirect(url_for("dashboard"))
|
return redirect(url_for("dashboard"))
|
||||||
|
|
||||||
|
|
||||||
@app.route("/site/<slug>/", defaults={"filename": "index.html"})
|
# use subdomains
|
||||||
@app.route("/site/<slug>/<path:filename>")
|
@app.route("/", subdomain="<subdomain>", defaults={"filename": "index.html"})
|
||||||
def serve_site_content(slug, filename):
|
@app.route("/<path:filename>")
|
||||||
site = Site.query.filter_by(slug=slug).first_or_404()
|
def serve_site_content(filename):
|
||||||
|
subdomain = request.host.split('.')[0]
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
@@ -270,21 +321,22 @@ def serve_site_content(slug, filename):
|
|||||||
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
|
app.config["UPLOAD_FOLDER"], str(site.user_id), str(site.id)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# TODO: add specific page redirects here as they're added
|
||||||
|
if isDefaultRoute(subdomain):
|
||||||
|
return send_from_directory("index.html")
|
||||||
|
|
||||||
# Security check
|
# Security check
|
||||||
if ".." in filename or filename.startswith("/") or not os.path.exists(site_dir):
|
if ".." in filename or filename.startswith("/") or not os.path.exists(site_dir):
|
||||||
abort(404)
|
return render_template("404.html"), 404
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# First try to serve requested file
|
|
||||||
return send_from_directory(site_dir, filename)
|
return send_from_directory(site_dir, filename)
|
||||||
except NotFound:
|
except NotFound:
|
||||||
# Handle extensionless URLs and SPA-style routing
|
|
||||||
if "." not in filename:
|
if "." not in filename:
|
||||||
# Try with .html extension
|
|
||||||
try:
|
try:
|
||||||
return send_from_directory(site_dir, f"{filename}.html")
|
return send_from_directory(site_dir, f"{filename}.html")
|
||||||
except NotFound:
|
except NotFound:
|
||||||
# Fallback to index.html for client-side routing
|
redirect(app.config["SERVER_NAME"])
|
||||||
return send_from_directory(site_dir, "index.html")
|
return send_from_directory(site_dir, "index.html")
|
||||||
abort(404)
|
abort(404)
|
||||||
|
|
||||||
@@ -303,7 +355,10 @@ def inject_utilities():
|
|||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
def home():
|
def home():
|
||||||
|
if isDefaultRoute(request.host):
|
||||||
return render_template("home.html")
|
return render_template("home.html")
|
||||||
|
else:
|
||||||
|
return serve_site_content('index.html')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<style>
|
||||||
|
.error-container {
|
||||||
|
text-align: center;
|
||||||
|
padding: 100px 20px;
|
||||||
|
min-height: 60vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-emoji {
|
||||||
|
font-size: 4rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 0 auto 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cta-button {
|
||||||
|
margin-top: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alien {
|
||||||
|
font-size: 5rem;
|
||||||
|
margin: 2rem 0;
|
||||||
|
animation: float 3s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes float {
|
||||||
|
0% {
|
||||||
|
transform: translateY(0px);
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
transform: translateY(-20px);
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
transform: translateY(0px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener("DOMContentLoaded", () => {
|
||||||
|
const emojis = ["👽", "🚀", "🛸", "🌌", "🌠", "🔭", "🪐", "🌍", "✨", "👾"];
|
||||||
|
const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];
|
||||||
|
|
||||||
|
const alienElement = document.querySelector(".alien");
|
||||||
|
if (alienElement) {
|
||||||
|
alienElement.textContent = randomEmoji;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="error-container">
|
||||||
|
<div class="alien">👽</div>
|
||||||
|
<h1>Houston, We Have a Problem!</h1>
|
||||||
|
|
||||||
|
<div class="error-message">
|
||||||
|
<p>The site you're looking for doesn't exist... yet!</p>
|
||||||
|
<p>But don't worry, this corner of the internet is just waiting for your creativity.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if current_user.is_authenticated %}
|
||||||
|
<a href="{{ url_for('dashboard') }}" class="btn cta-button">
|
||||||
|
🚀 Create {{ domain }}
|
||||||
|
</a>
|
||||||
|
{% else %}
|
||||||
|
<div class="auth-buttons">
|
||||||
|
<p>Start your web hosting journey today!</p>
|
||||||
|
<a href="{{ url_for('register') }}" class="btn">Sign Up</a>
|
||||||
|
<a href="{{ url_for('login') }}" class="btn">Login</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div style="margin-top: 3rem;">
|
||||||
|
<small>PS: If you were looking for someone else's site, maybe they forgot to launch it! 🚀</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -12,11 +12,14 @@
|
|||||||
<input type="text" name="name" required>
|
<input type="text" name="name" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Add slug input -->
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>Custom URL Slug:</label>
|
<label>Site URL:</label>
|
||||||
<input type="text" name="slug" required pattern="[a-zA-Z0-9\-_]+"
|
<div style="display: flex; align-items: center;">
|
||||||
title="Letters, numbers, hyphens, and underscores only">
|
<input type="text" name="subdomain" required pattern="[a-zA-Z0-9\-_]+"
|
||||||
|
title="Letters, numbers, hyphens, and underscores only" value="{{ subdomain }}"
|
||||||
|
style="flex: 1;">
|
||||||
|
<span style="margin-left: 5px;">.{{ hostname }}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group" onclick="document.querySelector('#file-input').click()">
|
<div class="form-group" onclick="document.querySelector('#file-input').click()">
|
||||||
@@ -27,7 +30,6 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- File Preview Section -->
|
|
||||||
<div id="file-preview" class="file-preview">
|
<div id="file-preview" class="file-preview">
|
||||||
<h5>Selected Files:</h5>
|
<h5>Selected Files:</h5>
|
||||||
<div id="file-grid" class="file-grid"></div>
|
<div id="file-grid" class="file-grid"></div>
|
||||||
@@ -69,7 +71,9 @@
|
|||||||
<!-- Site Actions -->
|
<!-- Site Actions -->
|
||||||
<div class="site-actions">
|
<div class="site-actions">
|
||||||
<a href="{{ url_for('edit_site', site_id=site.id) }}" class="btn">Edit</a>
|
<a href="{{ url_for('edit_site', site_id=site.id) }}" class="btn">Edit</a>
|
||||||
<a href="{{ url_for('serve_site_content', slug=site.slug) }}" class="btn" target="_blank">View Site</a>
|
<a href="{{ url_for('serve_site_content', filename='index.html', _external=True, subdomain=site.subdomain) }}">Visit
|
||||||
|
{{ site.name }}
|
||||||
|
</a>
|
||||||
<form method="POST" action="{{ url_for('delete_site', site_id=site.id) }}" style="display: inline;">
|
<form method="POST" action="{{ url_for('delete_site', site_id=site.id) }}" style="display: inline;">
|
||||||
<button type="submit" class="btn btn-danger">Delete Site</button>
|
<button type="submit" class="btn btn-danger">Delete Site</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<h2>Edit {{ site.name }}</h2>
|
<h2>Edit {{ site.name }}</h2>
|
||||||
<a href="{{ url_for('serve_site_content', slug=site.slug) }}" class="btn" target="_blank">View Site</a>
|
<a href="{{ url_for('serve_site_content', subdomain=site.subdomain) }}" class="btn" target="_blank">View Site</a>
|
||||||
|
|
||||||
<div style="margin-bottom: 30px;"></div>
|
<div style="margin-bottom: 30px;"></div>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user