feat: implement session-based authentication and modern login UI
This commit is contained in:
parent
e8b72e861c
commit
394c27401d
4 changed files with 156 additions and 11 deletions
|
|
@ -9,7 +9,7 @@ import ipaddress
|
||||||
import shutil
|
import shutil
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from flask import Flask, jsonify, render_template, request, abort, Response, send_from_directory
|
from flask import Flask, jsonify, render_template, request, abort, Response, send_from_directory, session, redirect, url_for
|
||||||
|
|
||||||
# Load config from environment variables
|
# Load config from environment variables
|
||||||
API_URL = os.getenv("API_URL", "http://localhost:8457/api")
|
API_URL = os.getenv("API_URL", "http://localhost:8457/api")
|
||||||
|
|
@ -28,6 +28,7 @@ HEADERS = {"Authorization": f"Token {API_TOKEN}"}
|
||||||
# Serve static files from ui/dist
|
# Serve static files from ui/dist
|
||||||
STATIC_FOLDER = os.path.join(os.getcwd(), 'ui', 'dist')
|
STATIC_FOLDER = os.path.join(os.getcwd(), 'ui', 'dist')
|
||||||
app = Flask(__name__, static_folder=STATIC_FOLDER, static_url_path='/')
|
app = Flask(__name__, static_folder=STATIC_FOLDER, static_url_path='/')
|
||||||
|
app.secret_key = os.getenv("FLASK_SECRET_KEY", "tubesortermagicpika") # Change in production!
|
||||||
|
|
||||||
# Database setup
|
# Database setup
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
@ -918,22 +919,44 @@ def check_auth(username, password):
|
||||||
"""Checks whether a username/password combination is valid."""
|
"""Checks whether a username/password combination is valid."""
|
||||||
return username == UI_USERNAME and password == UI_PASSWORD
|
return username == UI_USERNAME and password == UI_PASSWORD
|
||||||
|
|
||||||
def authenticate():
|
|
||||||
"""Sends a 401 response that enables basic auth"""
|
|
||||||
return Response(
|
|
||||||
'Could not verify your access level for that URL.\n'
|
|
||||||
'You have to login with proper credentials', 401,
|
|
||||||
{'WWW-Authenticate': 'Basic realm="Login Required"'})
|
|
||||||
|
|
||||||
def requires_auth(f):
|
def requires_auth(f):
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
def decorated(*args, **kwargs):
|
def decorated(*args, **kwargs):
|
||||||
auth = request.authorization
|
if not session.get('logged_in'):
|
||||||
if not auth or not check_auth(auth.username, auth.password):
|
if request.path.startswith('/api/'):
|
||||||
return authenticate()
|
return jsonify({"error": "Unauthorized"}), 401
|
||||||
|
return redirect('/login')
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
return decorated
|
return decorated
|
||||||
|
|
||||||
|
@app.route("/api/auth/login", methods=["POST"])
|
||||||
|
def api_login():
|
||||||
|
data = request.json
|
||||||
|
username = data.get("username")
|
||||||
|
password = data.get("password")
|
||||||
|
|
||||||
|
if check_auth(username, password):
|
||||||
|
session['logged_in'] = True
|
||||||
|
session['username'] = username
|
||||||
|
return jsonify({"success": True})
|
||||||
|
return jsonify({"error": "Invalid credentials"}), 401
|
||||||
|
|
||||||
|
@app.route("/api/auth/logout", methods=["POST"])
|
||||||
|
def api_logout():
|
||||||
|
session.clear()
|
||||||
|
return jsonify({"success": True})
|
||||||
|
|
||||||
|
@app.route("/api/auth/status")
|
||||||
|
def api_auth_status():
|
||||||
|
return jsonify({
|
||||||
|
"logged_in": session.get('logged_in', False),
|
||||||
|
"username": session.get('username')
|
||||||
|
})
|
||||||
|
|
||||||
|
@app.route("/login")
|
||||||
|
def login_page():
|
||||||
|
return send_from_directory(app.static_folder, 'login/index.html')
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
@requires_auth
|
@requires_auth
|
||||||
def index():
|
def index():
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,10 @@
|
||||||
async function fetchData() {
|
async function fetchData() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/status");
|
const res = await fetch("/api/status");
|
||||||
|
if (res.status === 401) {
|
||||||
|
window.location.href = "/login";
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!res.ok) throw new Error("Failed to fetch status");
|
if (!res.ok) throw new Error("Failed to fetch status");
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -70,6 +70,12 @@ const { title } = Astro.props;
|
||||||
>
|
>
|
||||||
<i class="bi bi-film mr-1"></i> Transcoding
|
<i class="bi bi-film mr-1"></i> Transcoding
|
||||||
</a>
|
</a>
|
||||||
|
<button
|
||||||
|
id="logout-btn"
|
||||||
|
class="text-gray-500 hover:text-neon-pink hover:bg-white/5 px-3 py-2 rounded-md text-sm font-medium transition-colors cursor-pointer"
|
||||||
|
>
|
||||||
|
<i class="bi bi-box-arrow-right mr-1"></i> Logout
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -95,5 +101,16 @@ const { title } = Astro.props;
|
||||||
>
|
>
|
||||||
<p>TUBESORTER // SYSTEM_V2 // BUN_POWERED</p>
|
<p>TUBESORTER // SYSTEM_V2 // BUN_POWERED</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
<script>
|
||||||
|
const logoutBtn = document.getElementById('logout-btn');
|
||||||
|
logoutBtn?.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/logout', { method: 'POST' });
|
||||||
|
if (res.ok) window.location.href = '/login';
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Logout failed', err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
101
ui/src/pages/login.astro
Normal file
101
ui/src/pages/login.astro
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
---
|
||||||
|
import Layout from "../layouts/Layout.astro";
|
||||||
|
---
|
||||||
|
|
||||||
|
<Layout title="Login">
|
||||||
|
<div class="min-h-[70vh] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
|
||||||
|
<div class="max-w-md w-full space-y-8 glass-panel p-8 rounded-2xl relative overflow-hidden group">
|
||||||
|
<!-- Glow Effect -->
|
||||||
|
<div class="absolute -top-24 -left-24 w-48 h-48 bg-neon-cyan/20 blur-[80px] rounded-full pointer-events-none group-hover:bg-neon-cyan/30 transition-colors"></div>
|
||||||
|
<div class="absolute -bottom-24 -right-24 w-48 h-48 bg-neon-pink/20 blur-[80px] rounded-full pointer-events-none group-hover:bg-neon-pink/30 transition-colors"></div>
|
||||||
|
|
||||||
|
<div class="relative z-10">
|
||||||
|
<div class="text-center">
|
||||||
|
<i class="bi bi-shield-lock text-6xl neon-text-cyan animate-pulse inline-block mb-4"></i>
|
||||||
|
<h2 class="mt-2 text-3xl font-extrabold italic tracking-tighter text-white">
|
||||||
|
ACCESS_REQUIRED
|
||||||
|
</h2>
|
||||||
|
<p class="mt-2 text-sm text-gray-400 font-mono">
|
||||||
|
// PLEASE_IDENTIFY_YOURSELF
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form id="login-form" class="mt-8 space-y-6">
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label for="username" class="sr-only">Username</label>
|
||||||
|
<div class="relative">
|
||||||
|
<span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
|
||||||
|
<i class="bi bi-person-fill"></i>
|
||||||
|
</span>
|
||||||
|
<input id="username" name="username" type="text" required
|
||||||
|
class="appearance-none relative block w-full px-10 py-3 border border-gray-800 bg-cyber-darker/50 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-neon-cyan/50 focus:border-neon-cyan transition-all placeholder-gray-600 sm:text-sm"
|
||||||
|
placeholder="Username" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="password" class="sr-only">Password</label>
|
||||||
|
<div class="relative">
|
||||||
|
<span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
|
||||||
|
<i class="bi bi-key-fill"></i>
|
||||||
|
</span>
|
||||||
|
<input id="password" name="password" type="password" required
|
||||||
|
class="appearance-none relative block w-full px-10 py-3 border border-gray-800 bg-cyber-darker/50 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-neon-pink/50 focus:border-neon-pink transition-all placeholder-gray-600 sm:text-sm"
|
||||||
|
placeholder="Password" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="error-message" class="hidden text-neon-pink text-xs font-mono text-center animate-bounce">
|
||||||
|
// ERROR: INVALID_CREDENTIALS
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button type="submit" id="submit-btn"
|
||||||
|
class="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-bold rounded-lg text-cyber-dark bg-gradient-to-r from-neon-cyan to-neon-pink hover:from-white hover:to-white transition-all duration-300 shadow-[0_0_15px_rgba(0,243,255,0.3)] hover:shadow-[0_0_25px_rgba(255,255,255,0.5)] focus:outline-none uppercase italic tracking-widest">
|
||||||
|
<span class="absolute left-0 inset-y-0 flex items-center pl-3">
|
||||||
|
<i class="bi bi-unlock-fill text-cyber-dark group-hover:animate-bounce"></i>
|
||||||
|
</span>
|
||||||
|
Authenticate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Layout>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const form = document.getElementById('login-form');
|
||||||
|
const errorMsg = document.getElementById('error-message');
|
||||||
|
const submitBtn = document.getElementById('submit-btn');
|
||||||
|
|
||||||
|
form?.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
errorMsg?.classList.add('hidden');
|
||||||
|
|
||||||
|
const formData = new FormData(form as HTMLFormElement);
|
||||||
|
const data = Object.fromEntries(formData.entries());
|
||||||
|
|
||||||
|
if (submitBtn) submitBtn.innerHTML = '<i class="bi bi-arrow-repeat animate-spin mr-2"></i> Processing...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
window.location.href = '/';
|
||||||
|
} else {
|
||||||
|
errorMsg?.classList.remove('hidden');
|
||||||
|
if (submitBtn) submitBtn.innerHTML = 'Authenticate';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
errorMsg?.classList.remove('hidden');
|
||||||
|
if (submitBtn) submitBtn.innerHTML = 'Authenticate';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
Loading…
Add table
Add a link
Reference in a new issue