Complete dynamic site implementation: routes, templates, updated requirements and docker setup

This commit is contained in:
2025-09-21 17:39:56 +02:00
parent f96b7d47e0
commit 8b7ab9d66e
11 changed files with 1181 additions and 30 deletions

74
app.py
View File

@@ -2,10 +2,19 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright Hersel Giannella # Copyright Hersel Giannella
# Enhanced Quart Application with Database and Authentication
from quart import Quart, send_from_directory import asyncio
from quart import Quart, send_from_directory, session, g
from config import config from config import config
from models.database import init_database, db_manager
from utils.helpers import get_flash_messages
from utils.auth import get_current_user
# Import Blueprints
from routes.home import route_home from routes.home import route_home
from routes.auth import auth_bp
from routes.dashboard import dashboard_bp
app = Quart( app = Quart(
__name__, __name__,
@@ -13,7 +22,25 @@ app = Quart(
static_folder="static", static_folder="static",
) )
# favicon.ico, sitemap.xml and robots.txt # Configuration
app.config.from_object(config)
app.secret_key = config.SECRET_KEY
# Template globals
@app.template_global('get_flashed_messages')
def template_get_flashed_messages(with_categories=False):
return get_flash_messages()
# Context processor for current user
@app.before_request
async def load_current_user():
g.current_user = await get_current_user()
@app.context_processor
def inject_user():
return {'current_user': getattr(g, 'current_user', None)}
# Static files routes
@app.route('/favicon.ico') @app.route('/favicon.ico')
async def favicon(): async def favicon():
return await send_from_directory(app.static_folder, 'favicon.ico') return await send_from_directory(app.static_folder, 'favicon.ico')
@@ -26,8 +53,47 @@ async def sitemap():
async def robots(): async def robots():
return await send_from_directory(app.static_folder, 'robots.txt') return await send_from_directory(app.static_folder, 'robots.txt')
# BluePrint Routes # Register Blueprints
app.register_blueprint(route_home) app.register_blueprint(route_home)
app.register_blueprint(auth_bp)
app.register_blueprint(dashboard_bp)
# Database initialization
@app.before_serving
async def initialize_app():
"""Initialize database and other services"""
print("🚀 Initializing Hersel.it application...")
try:
await init_database()
print("✅ Database initialized successfully")
except Exception as e:
print(f"❌ Error initializing database: {e}")
# Don't crash the app, but log the error
@app.after_serving
async def cleanup_app():
"""Cleanup resources"""
print("🔒 Shutting down Hersel.it application...")
await db_manager.close_pool()
print("✅ Application shutdown complete")
# Error handlers
@app.errorhandler(404)
async def not_found(error):
return await render_template('errors/404.html'), 404
@app.errorhandler(500)
async def internal_error(error):
return await render_template('errors/500.html'), 500
# Health check endpoint
@app.route('/health')
async def health_check():
return {'status': 'healthy', 'app': 'Hersel.it Portfolio'}
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=config.DEBUG, host=config.APP_HOST, port=config.APP_PORT) app.run(
debug=config.DEBUG,
host=config.APP_HOST,
port=config.APP_PORT
)

View File

@@ -1,20 +1,53 @@
version: "3.9" version: '3.9'
services: services:
# MySQL Database
mysql:
image: mysql:8.0
container_name: hersel_mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root_password_change_me
MYSQL_DATABASE: hersel_portfolio
MYSQL_USER: hersel_user
MYSQL_PASSWORD: secure_password_123
ports:
- "3307:3306"
volumes:
- mysql_data:/var/lib/mysql
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
command: --default-authentication-plugin=mysql_native_password
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
timeout: 20s
retries: 10
# Quart Application
quartapp: quartapp:
image: python:3.10-slim build: .
container_name: quartapp container_name: hersel_app
working_dir: /app restart: always
ports: ports:
- "127.0.0.1:5000:5000" - "127.0.0.1:5000:5000"
restart: always
command: >
sh -c "
apt-get update &&
apt-get install -y git &&
[ -d /app/.git ] || git clone https://github.com/BluLupo/hersel.it.git /app &&
pip install --no-cache-dir -r requirements.txt &&
hypercorn -c hypercorn_config.toml app:app
"
environment: environment:
- DEBUG=False
- SECRET_KEY=super-secret-key-change-in-production-please
- DB_HOST=mysql
- DB_PORT=3306
- DB_USER=hersel_user
- DB_PASSWORD=secure_password_123
- DB_NAME=hersel_portfolio
- PYTHONUNBUFFERED=1 - PYTHONUNBUFFERED=1
depends_on:
mysql:
condition: service_healthy
volumes:
- ./static/uploads:/app/static/uploads
volumes:
mysql_data:
driver: local
networks:
default:
name: hersel_network

143
init.sql Normal file
View File

@@ -0,0 +1,143 @@
-- Initial database setup for Hersel.it Portfolio
-- This file is automatically executed when MySQL container starts
USE hersel_portfolio;
-- Enable UTF8MB4 charset for emoji and international characters
SET NAMES utf8mb4;
SET character_set_client = utf8mb4;
-- Create categories table
CREATE TABLE IF NOT EXISTS categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
slug VARCHAR(100) UNIQUE NOT NULL,
description TEXT,
color VARCHAR(7) DEFAULT '#007bff',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create users table
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50),
role ENUM('admin', 'user') DEFAULT 'user',
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create projects table
CREATE TABLE IF NOT EXISTS projects (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
slug VARCHAR(200) UNIQUE NOT NULL,
description TEXT,
content LONGTEXT,
image_url VARCHAR(500),
github_url VARCHAR(500),
demo_url VARCHAR(500),
technologies JSON,
category_id INT,
is_featured BOOLEAN DEFAULT FALSE,
is_published BOOLEAN DEFAULT TRUE,
created_by INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create posts table (for future blog functionality)
CREATE TABLE IF NOT EXISTS posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
slug VARCHAR(200) UNIQUE NOT NULL,
excerpt TEXT,
content LONGTEXT,
featured_image VARCHAR(500),
category_id INT,
author_id INT,
is_published BOOLEAN DEFAULT FALSE,
published_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL,
FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create settings table
CREATE TABLE IF NOT EXISTS settings (
id INT AUTO_INCREMENT PRIMARY KEY,
setting_key VARCHAR(100) UNIQUE NOT NULL,
setting_value LONGTEXT,
description TEXT,
type ENUM('text', 'textarea', 'boolean', 'json') DEFAULT 'text',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Insert default categories
INSERT INTO categories (name, slug, description, color) VALUES
('Web Development', 'web-development', 'Progetti di sviluppo web', '#007bff'),
('Mobile Apps', 'mobile-apps', 'Applicazioni mobile', '#28a745'),
('Desktop Apps', 'desktop-apps', 'Applicazioni desktop', '#ffc107'),
('APIs', 'apis', 'API e servizi web', '#dc3545'),
('Tools & Utilities', 'tools-utilities', 'Strumenti e utility', '#6f42c1'),
('Open Source', 'open-source', 'Progetti open source', '#20c997')
ON DUPLICATE KEY UPDATE name=VALUES(name);
-- Insert default settings
INSERT INTO settings (setting_key, setting_value, description, type) VALUES
('site_name', 'Hersel.it', 'Nome del sito', 'text'),
('site_description', 'Portfolio personale di Hersel Giannella - Developer', 'Descrizione del sito', 'textarea'),
('admin_email', 'admin@hersel.it', 'Email amministratore', 'text'),
('site_logo', '/static/img/logo.png', 'URL del logo', 'text'),
('social_github', 'https://github.com/BluLupo', 'GitHub URL', 'text'),
('social_linkedin', '', 'LinkedIn URL', 'text'),
('social_twitter', '', 'Twitter URL', 'text'),
('site_maintenance', 'false', 'Modalità manutenzione', 'boolean'),
('analytics_code', '', 'Codice Analytics', 'textarea'),
('projects_per_page', '12', 'Progetti per pagina', 'text'),
('featured_projects_limit', '6', 'Limite progetti in evidenza', 'text')
ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value);
-- Create admin user (password: AdminPass123!)
-- This creates a default admin user for initial access
-- Password hash for 'AdminPass123!' generated with bcrypt
INSERT INTO users (username, email, password_hash, first_name, last_name, role) VALUES
('admin', 'admin@hersel.it', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqyaqr06eoAGNz9CpahtY1q', 'Admin', 'User', 'admin')
ON DUPLICATE KEY UPDATE role=VALUES(role);
-- Insert sample projects (optional)
INSERT INTO projects (title, slug, description, content, github_url, technologies, is_featured, is_published, created_by) VALUES
('Hersel.it Portfolio', 'hersel-it-portfolio', 'Portfolio dinamico sviluppato con Quart e MySQL',
'<h2>Portfolio Dinamico</h2><p>Questo portfolio è stato sviluppato utilizzando le seguenti tecnologie:</p><ul><li>Python con Quart framework</li><li>MySQL per il database</li><li>Bootstrap 5 per il frontend</li><li>Docker per il deployment</li></ul>',
'https://github.com/BluLupo/hersel.it',
'["Python", "Quart", "MySQL", "Bootstrap", "Docker"]',
TRUE, TRUE, 1),
('API REST con Quart', 'api-rest-quart', 'API RESTful asincrona per gestione dati',
'<h2>API REST</h2><p>API asincrona sviluppata con Quart per gestire operazioni CRUD su database MySQL.</p>',
'',
'["Python", "Quart", "MySQL", "REST API", "Async"]',
FALSE, TRUE, 1)
ON DUPLICATE KEY UPDATE title=VALUES(title);
-- Create indexes for better performance
CREATE INDEX idx_projects_published ON projects(is_published);
CREATE INDEX idx_projects_featured ON projects(is_featured);
CREATE INDEX idx_projects_category ON projects(category_id);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_posts_published ON posts(is_published);
-- Show confirmation message
SELECT 'Database initialized successfully!' as Status;
SELECT COUNT(*) as 'Total Categories' FROM categories;
SELECT COUNT(*) as 'Total Settings' FROM settings;
SELECT COUNT(*) as 'Admin Users' FROM users WHERE role='admin';
SELECT COUNT(*) as 'Sample Projects' FROM projects;

View File

@@ -1,24 +1,41 @@
# Core Framework
Quart==0.20.0
Hypercorn==0.17.3
# Database
aiomysql==0.2.0
PyMySQL==1.1.0
cryptography==41.0.8
# Authentication
bcrypt==4.1.2
# Utilities
aiofiles==24.1.0 aiofiles==24.1.0
annotated-types==0.7.0 python-dotenv==1.0.1
blinker==1.9.0 Jinja2==3.1.5
MarkupSafe==3.0.2
Werkzeug==3.1.3
# Core Dependencies
click==8.1.8 click==8.1.8
Flask==3.1.0 blinker==1.9.0
itsdangerous==2.2.0
typing_extensions==4.12.2
# HTTP/Network
h11==0.14.0 h11==0.14.0
h2==4.1.0 h2==4.1.0
hpack==4.0.0 hpack==4.0.0
Hypercorn==0.17.3
hyperframe==6.0.1 hyperframe==6.0.1
itsdangerous==2.2.0
Jinja2==3.1.5
MarkupSafe==3.0.2
priority==2.0.0 priority==2.0.0
wsproto==1.2.0
httpx==0.27.0
# Optional
Flask==3.1.0
pydantic==2.10.4 pydantic==2.10.4
pydantic-settings==2.7.1 pydantic-settings==2.7.1
pydantic_core==2.27.2 pydantic_core==2.27.2
python-dotenv==1.0.1 annotated-types==0.7.0
Quart==0.20.0
typing_extensions==4.12.2
Werkzeug==3.1.3
wsproto==1.2.0
httpx==0.27.0
Sphinx==8.2.3 Sphinx==8.2.3

123
routes/auth.py Normal file
View File

@@ -0,0 +1,123 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Authentication Routes
from quart import Blueprint, request, render_template, redirect, url_for, session, flash
from models.user import User
from utils.auth import login_user, logout_user, get_current_user
from utils.validators import validate_email, validate_password, validate_username
from utils.helpers import flash_message
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
@auth_bp.route('/login', methods=['GET', 'POST'])
async def login():
"""Login page"""
if request.method == 'GET':
return await render_template('auth/login.html')
form_data = await request.form
username_or_email = form_data.get('username', '').strip()
password = form_data.get('password', '')
if not username_or_email or not password:
flash_message('Username/Email e password sono richiesti', 'error')
return await render_template('auth/login.html')
# Authenticate user
user = await User.authenticate(username_or_email, password)
if user:
login_user(user)
flash_message(f'Benvenuto, {user.full_name}!', 'success')
# Redirect to dashboard if admin, home otherwise
if user.is_admin:
return redirect(url_for('dashboard.index'))
else:
return redirect(url_for('home.index'))
else:
flash_message('Credenziali non valide', 'error')
return await render_template('auth/login.html')
@auth_bp.route('/register', methods=['GET', 'POST'])
async def register():
"""Registration page"""
if request.method == 'GET':
return await render_template('auth/register.html')
form_data = await request.form
username = form_data.get('username', '').strip()
email = form_data.get('email', '').strip()
password = form_data.get('password', '')
confirm_password = form_data.get('confirm_password', '')
first_name = form_data.get('first_name', '').strip()
last_name = form_data.get('last_name', '').strip()
errors = {}
# Validate inputs
is_valid, error = validate_username(username)
if not is_valid:
errors['username'] = error
is_valid, error = validate_email(email)
if not is_valid:
errors['email'] = error
is_valid, error = validate_password(password)
if not is_valid:
errors['password'] = error
if password != confirm_password:
errors['confirm_password'] = 'Le password non coincidono'
# Check if user already exists
if not errors:
existing_user = await User.find_by_username(username)
if existing_user:
errors['username'] = 'Username già in uso'
existing_email = await User.find_by_email(email)
if existing_email:
errors['email'] = 'Email già registrata'
if errors:
for field, error in errors.items():
flash_message(error, 'error')
return await render_template('auth/register.html')
# Create new user
user = User(
username=username,
email=email,
first_name=first_name,
last_name=last_name,
role='user' # First user can be manually promoted to admin
)
user.set_password(password)
try:
await user.save()
flash_message('Registrazione completata! Ora puoi effettuare il login.', 'success')
return redirect(url_for('auth.login'))
except Exception as e:
flash_message('Errore durante la registrazione. Riprova.', 'error')
return await render_template('auth/register.html')
@auth_bp.route('/logout')
async def logout():
"""Logout user"""
logout_user()
flash_message('Logout effettuato con successo', 'success')
return redirect(url_for('home.index'))
@auth_bp.route('/profile')
async def profile():
"""User profile page"""
user = await get_current_user()
if not user:
return redirect(url_for('auth.login'))
return await render_template('auth/profile.html', user=user)

218
routes/dashboard.py Normal file
View File

@@ -0,0 +1,218 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Dashboard Routes (Admin)
from quart import Blueprint, request, render_template, redirect, url_for, jsonify
from models.user import User
from models.project import Project
from models.category import Category
from utils.auth import admin_required, get_current_user
from utils.helpers import flash_message, generate_slug, calculate_pagination
from utils.validators import validate_project_data
dashboard_bp = Blueprint('dashboard', __name__, url_prefix='/dashboard')
@dashboard_bp.route('/')
@admin_required
async def index():
"""Dashboard home"""
current_user = await get_current_user()
# Get statistics
stats = {
'total_users': await User.count(),
'total_projects': await Project.count(published_only=False),
'published_projects': await Project.count(published_only=True),
'featured_projects': len(await Project.get_featured())
}
# Get recent projects
recent_projects = await Project.get_all(published_only=False, limit=5)
return await render_template('dashboard/index.html',
user=current_user,
stats=stats,
recent_projects=recent_projects)
@dashboard_bp.route('/projects')
@admin_required
async def projects():
"""Projects management"""
page = int(request.args.get('page', 1))
per_page = 10
# Get projects with pagination
projects = await Project.get_all(published_only=False, limit=per_page, offset=(page-1)*per_page)
total_projects = await Project.count(published_only=False)
pagination = calculate_pagination(total_projects, page, per_page)
return await render_template('dashboard/projects.html',
projects=projects,
pagination=pagination)
@dashboard_bp.route('/projects/new', methods=['GET', 'POST'])
@admin_required
async def new_project():
"""Create new project"""
if request.method == 'GET':
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=None,
categories=categories,
action='create')
form_data = await request.form
data = {
'title': form_data.get('title', '').strip(),
'description': form_data.get('description', '').strip(),
'content': form_data.get('content', '').strip(),
'github_url': form_data.get('github_url', '').strip(),
'demo_url': form_data.get('demo_url', '').strip(),
'image_url': form_data.get('image_url', '').strip(),
'technologies': form_data.getlist('technologies'),
'category_id': int(form_data.get('category_id')) if form_data.get('category_id') else None,
'is_featured': bool(form_data.get('is_featured')),
'is_published': bool(form_data.get('is_published'))
}
# Validate data
is_valid, errors = validate_project_data(data)
if not is_valid:
for field, error in errors.items():
flash_message(error, 'error')
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=data,
categories=categories,
action='create')
# Create project
current_user = await get_current_user()
project = Project(
title=data['title'],
slug=generate_slug(data['title']),
description=data['description'],
content=data['content'],
github_url=data['github_url'],
demo_url=data['demo_url'],
image_url=data['image_url'],
technologies=data['technologies'],
category_id=data['category_id'],
is_featured=data['is_featured'],
is_published=data['is_published'],
created_by=current_user.id
)
try:
await project.save()
flash_message('Progetto creato con successo!', 'success')
return redirect(url_for('dashboard.projects'))
except Exception as e:
flash_message('Errore durante la creazione del progetto', 'error')
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=data,
categories=categories,
action='create')
@dashboard_bp.route('/projects/<int:project_id>/edit', methods=['GET', 'POST'])
@admin_required
async def edit_project(project_id):
"""Edit project"""
project = await Project.find_by_id(project_id)
if not project:
flash_message('Progetto non trovato', 'error')
return redirect(url_for('dashboard.projects'))
if request.method == 'GET':
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=project,
categories=categories,
action='edit')
form_data = await request.form
data = {
'title': form_data.get('title', '').strip(),
'description': form_data.get('description', '').strip(),
'content': form_data.get('content', '').strip(),
'github_url': form_data.get('github_url', '').strip(),
'demo_url': form_data.get('demo_url', '').strip(),
'image_url': form_data.get('image_url', '').strip(),
'technologies': form_data.getlist('technologies'),
'category_id': int(form_data.get('category_id')) if form_data.get('category_id') else None,
'is_featured': bool(form_data.get('is_featured')),
'is_published': bool(form_data.get('is_published'))
}
# Validate data
is_valid, errors = validate_project_data(data)
if not is_valid:
for field, error in errors.items():
flash_message(error, 'error')
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=project,
categories=categories,
action='edit')
# Update project
project.title = data['title']
project.slug = generate_slug(data['title'])
project.description = data['description']
project.content = data['content']
project.github_url = data['github_url']
project.demo_url = data['demo_url']
project.image_url = data['image_url']
project.technologies = data['technologies']
project.category_id = data['category_id']
project.is_featured = data['is_featured']
project.is_published = data['is_published']
try:
await project.save()
flash_message('Progetto aggiornato con successo!', 'success')
return redirect(url_for('dashboard.projects'))
except Exception as e:
flash_message('Errore durante l\'aggiornamento del progetto', 'error')
categories = await Category.get_all()
return await render_template('dashboard/project_form.html',
project=project,
categories=categories,
action='edit')
@dashboard_bp.route('/projects/<int:project_id>/delete', methods=['POST'])
@admin_required
async def delete_project(project_id):
"""Delete project"""
project = await Project.find_by_id(project_id)
if not project:
return jsonify({'error': 'Progetto non trovato'}), 404
try:
await project.delete()
flash_message('Progetto eliminato con successo!', 'success')
return redirect(url_for('dashboard.projects'))
except Exception as e:
flash_message('Errore durante l\'eliminazione del progetto', 'error')
return redirect(url_for('dashboard.projects'))
@dashboard_bp.route('/users')
@admin_required
async def users():
"""Users management"""
page = int(request.args.get('page', 1))
per_page = 10
users = await User.get_all(limit=per_page, offset=(page-1)*per_page)
total_users = await User.count()
pagination = calculate_pagination(total_users, page, per_page)
return await render_template('dashboard/users.html',
users=users,
pagination=pagination)

62
templates/auth/login.html Normal file
View File

@@ -0,0 +1,62 @@
{% extends "base.html" %}
{% block title %}Login - Hersel.it{% endblock %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6 col-lg-5">
<div class="card shadow">
<div class="card-body p-5">
<div class="text-center mb-4">
<h2 class="card-title">Accedi</h2>
<p class="text-muted">Benvenuto su Hersel.it</p>
</div>
<form method="POST">
<div class="mb-3">
<label for="username" class="form-label">Username o Email</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-person"></i>
</span>
<input type="text" class="form-control" id="username" name="username" required>
</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-lock"></i>
</span>
<input type="password" class="form-control" id="password" name="password" required>
</div>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="remember" name="remember">
<label class="form-check-label" for="remember">
Ricordami
</label>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary btn-lg">
<i class="bi bi-box-arrow-in-right"></i> Accedi
</button>
</div>
</form>
<div class="text-center mt-4">
<p class="mb-0">
Non hai un account?
<a href="{{ url_for('auth.register') }}" class="text-decoration-none">Registrati qui</a>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,99 @@
{% extends "base.html" %}
{% block title %}Registrazione - Hersel.it{% endblock %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-8 col-lg-6">
<div class="card shadow">
<div class="card-body p-5">
<div class="text-center mb-4">
<h2 class="card-title">Registrati</h2>
<p class="text-muted">Crea il tuo account su Hersel.it</p>
</div>
<form method="POST">
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="first_name" class="form-label">Nome</label>
<input type="text" class="form-control" id="first_name" name="first_name">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="last_name" class="form-label">Cognome</label>
<input type="text" class="form-control" id="last_name" name="last_name">
</div>
</div>
</div>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-person"></i>
</span>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-text">Minimo 3 caratteri, solo lettere, numeri e underscore</div>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-envelope"></i>
</span>
<input type="email" class="form-control" id="email" name="email" required>
</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-lock"></i>
</span>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-text">Minimo 8 caratteri con maiuscola, minuscola e numero</div>
</div>
<div class="mb-3">
<label for="confirm_password" class="form-label">Conferma Password</label>
<div class="input-group">
<span class="input-group-text">
<i class="bi bi-lock-fill"></i>
</span>
<input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
</div>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="terms" name="terms" required>
<label class="form-check-label" for="terms">
Accetto i <a href="#" class="text-decoration-none">Termini e Condizioni</a>
</label>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary btn-lg">
<i class="bi bi-person-plus"></i> Registrati
</button>
</div>
</form>
<div class="text-center mt-4">
<p class="mb-0">
Hai già un account?
<a href="{{ url_for('auth.login') }}" class="text-decoration-none">Accedi qui</a>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

121
templates/base.html Normal file
View File

@@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Hersel.it - Portfolio{% endblock %}</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
{% block extra_head %}{% endblock %}
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{{ url_for('home.index') }}">
<strong>Hersel.it</strong>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto">
<li class="nav-item">
<a class="nav-link" href="{{ url_for('home.index') }}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#progetti">Progetti</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contatti">Contatti</a>
</li>
</ul>
<ul class="navbar-nav">
{% if session.get('user_id') %}
{% if session.get('is_admin') %}
<li class="nav-item">
<a class="nav-link" href="{{ url_for('dashboard.index') }}">
<i class="bi bi-speedometer2"></i> Dashboard
</a>
</li>
{% endif %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-person-circle"></i> {{ session.get('username') }}
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{{ url_for('auth.profile') }}">Profilo</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('auth.logout') }}">Logout</a></li>
</ul>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{{ url_for('auth.login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('auth.register') }}">Registrati</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
<!-- Flash Messages -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class="container mt-3">
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' if category == 'success' else 'info' }} alert-dismissible fade show">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<!-- Main Content -->
<main>
{% block content %}{% endblock %}
</main>
<!-- Footer -->
<footer class="bg-dark text-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6">
<h5>Hersel Giannella</h5>
<p>Developer & Portfolio</p>
</div>
<div class="col-md-6 text-end">
<a href="https://github.com/BluLupo" class="text-light me-3">
<i class="bi bi-github"></i> GitHub
</a>
<a href="mailto:info@hersel.it" class="text-light">
<i class="bi bi-envelope"></i> Email
</a>
</div>
</div>
<hr>
<div class="row">
<div class="col text-center">
<small>&copy; 2024 Hersel.it - Tutti i diritti riservati</small>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
{% block extra_scripts %}{% endblock %}
</body>
</html>

View File

@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Dashboard - Hersel.it{% endblock %}</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
<style>
.sidebar {
min-height: 100vh;
background-color: #f8f9fa;
}
.sidebar .nav-link {
color: #333;
}
.sidebar .nav-link:hover {
background-color: #e9ecef;
}
.sidebar .nav-link.active {
background-color: #0d6efd;
color: white;
}
</style>
{% block extra_head %}{% endblock %}
</head>
<body>
<div class="container-fluid">
<div class="row">
<!-- Sidebar -->
<nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
<div class="position-sticky pt-3">
<div class="text-center mb-4">
<a href="{{ url_for('home.index') }}" class="text-decoration-none">
<h4 class="text-primary">Hersel.it</h4>
</a>
<small class="text-muted">Dashboard Admin</small>
</div>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link {{ 'active' if request.endpoint == 'dashboard.index' }}" href="{{ url_for('dashboard.index') }}">
<i class="bi bi-speedometer2"></i> Overview
</a>
</li>
<li class="nav-item">
<a class="nav-link {{ 'active' if 'project' in request.endpoint }}" href="{{ url_for('dashboard.projects') }}">
<i class="bi bi-folder"></i> Progetti
</a>
</li>
<li class="nav-item">
<a class="nav-link {{ 'active' if request.endpoint == 'dashboard.users' }}" href="{{ url_for('dashboard.users') }}">
<i class="bi bi-people"></i> Utenti
</a>
</li>
</ul>
<hr>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link" href="{{ url_for('home.index') }}">
<i class="bi bi-house"></i> Vai al Sito
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('auth.logout') }}">
<i class="bi bi-box-arrow-right"></i> Logout
</a>
</li>
</ul>
</div>
</nav>
<!-- Main Content -->
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">{% block page_title %}Dashboard{% endblock %}</h1>
<div class="btn-toolbar mb-2 mb-md-0">
{% block page_actions %}{% endblock %}
</div>
</div>
<!-- Flash Messages -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' if category == 'success' else 'info' }} alert-dismissible fade show">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</main>
</div>
</div>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
{% block extra_scripts %}{% endblock %}
</body>
</html>

View File

@@ -0,0 +1,159 @@
{% extends "dashboard/base.html" %}
{% block page_title %}Dashboard{% endblock %}
{% block content %}
<div class="row">
<div class="col-lg-12">
<div class="mb-4">
<h3>Benvenuto, {{ user.full_name }}!</h3>
<p class="text-muted">Ecco una panoramica del tuo portfolio</p>
</div>
</div>
</div>
<!-- Statistics Cards -->
<div class="row mb-4">
<div class="col-md-3">
<div class="card bg-primary text-white">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4>{{ stats.total_projects }}</h4>
<p class="mb-0">Progetti Totali</p>
</div>
<div class="align-self-center">
<i class="bi bi-folder fs-1"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-success text-white">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4>{{ stats.published_projects }}</h4>
<p class="mb-0">Pubblicati</p>
</div>
<div class="align-self-center">
<i class="bi bi-check-circle fs-1"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-warning text-white">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4>{{ stats.featured_projects }}</h4>
<p class="mb-0">In Evidenza</p>
</div>
<div class="align-self-center">
<i class="bi bi-star fs-1"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card bg-info text-white">
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<h4>{{ stats.total_users }}</h4>
<p class="mb-0">Utenti</p>
</div>
<div class="align-self-center">
<i class="bi bi-people fs-1"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Recent Projects -->
<div class="row">
<div class="col-lg-8">
<div class="card">
<div class="card-header">
<h5 class="mb-0">Progetti Recenti</h5>
</div>
<div class="card-body">
{% if recent_projects %}
<div class="table-responsive">
<table class="table table-sm">
<thead>
<tr>
<th>Titolo</th>
<th>Stato</th>
<th>Creato</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
{% for project in recent_projects %}
<tr>
<td>
<strong>{{ project.title }}</strong>
{% if project.is_featured %}
<span class="badge bg-warning ms-1">Featured</span>
{% endif %}
</td>
<td>
{% if project.is_published %}
<span class="badge bg-success">Pubblicato</span>
{% else %}
<span class="badge bg-secondary">Bozza</span>
{% endif %}
</td>
<td>{{ project.created_at.strftime('%d/%m/%Y') if project.created_at else 'N/D' }}</td>
<td>
<a href="{{ url_for('dashboard.edit_project', project_id=project.id) }}" class="btn btn-sm btn-outline-primary">
<i class="bi bi-pencil"></i>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="text-muted">Nessun progetto ancora creato.</p>
<a href="{{ url_for('dashboard.new_project') }}" class="btn btn-primary">
<i class="bi bi-plus"></i> Crea il primo progetto
</a>
{% endif %}
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h5 class="mb-0">Azioni Rapide</h5>
</div>
<div class="card-body">
<div class="d-grid gap-2">
<a href="{{ url_for('dashboard.new_project') }}" class="btn btn-primary">
<i class="bi bi-plus"></i> Nuovo Progetto
</a>
<a href="{{ url_for('dashboard.projects') }}" class="btn btn-outline-primary">
<i class="bi bi-folder"></i> Gestisci Progetti
</a>
<a href="{{ url_for('home.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-eye"></i> Visualizza Sito
</a>
</div>
</div>
</div>
</div>
</div>
{% endblock %}