Skip to content

Commit

Permalink
basic flask login implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
codeperfectplus committed Aug 29, 2024
1 parent 555d768 commit 22267da
Show file tree
Hide file tree
Showing 14 changed files with 333 additions and 34 deletions.
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ Flask==2.3.3
psutil==5.9.5
gunicorn
speetest-cli
flask-sqlalchemy
flask-sqlalchemy
flask-login
24 changes: 20 additions & 4 deletions src/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from src.config import db, app

Expand All @@ -17,7 +19,7 @@ def __repr__(self):
)


class DashoardSettings(db.Model):
class DashboardSettings(db.Model):
__tablename__ = "DashboardSettings"
id = db.Column(db.Integer, primary_key=True)
speedtest_cooldown = db.Column(db.Integer, default=1)
Expand Down Expand Up @@ -50,12 +52,26 @@ class SystemInfo(db.Model):
def __repr__(self):
return f"<SystemInfo {self.username}, {self.cpu_percent}, {self.memory_percent}, {self.disk_usage}, {self.battery_percent}, {self.cpu_core}, {self.boot_time}, {self.network_sent}, {self.network_received}, {self.process_count}, {self.swap_memory}, {self.uptime}, {self.ipv4_connections}, {self.ipv6_connections}, {self.dashboard_memory_usage}>"

class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(150), nullable=False)
user_level = db.Column(db.String(50), nullable=False, default='user')


# initialize the database
with app.app_context():
print("Creating tables")
db.create_all()
settings = DashoardSettings.query.first()

# Initialize default settings
settings = DashboardSettings.query.first()
if not settings:
db.session.add(DashoardSettings())
db.session.add(DashboardSettings())
db.session.commit()

# Create admin user if not exists
if not User.query.filter_by(username='admin').first():
hashed_password = generate_password_hash('adminpassword')
admin_user = User(username='admin', password=hashed_password, user_level='admin')
db.session.add(admin_user)
db.session.commit()
1 change: 1 addition & 0 deletions src/routes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
from src.routes.speedtest import speedtest_bp
from src.routes.system_health import system_health_bp
from src.routes.process import process_bp
from src.routes.auth import auth_bp
90 changes: 90 additions & 0 deletions src/routes/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from flask import Flask, render_template, redirect, url_for, request, blueprints, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash

from src.config import app, db
from src.models import User

auth_bp = blueprints.Blueprint('auth', __name__)

# Configure Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# Define the User model

@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
if user and check_password_hash(user.password, password):
login_user(user)
return redirect(url_for('dashboard'))
flash('Invalid username or password')
return render_template('login.html')

@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
confirm_password = request.form['confirm_password']

if password != confirm_password:
flash('Passwords do not match')
return redirect(url_for('signup'))

existing_user = User.query.filter_by(username=username).first()
if existing_user:
flash('Username already exists')
return redirect(url_for('signup'))

hashed_password = generate_password_hash(password)
new_user = User(username=username, password=hashed_password)
db.session.add(new_user)
db.session.commit()
flash('Account created successfully, please log in.')
return redirect(url_for('login'))

return render_template('signup.html')

@app.route('/protected')
@login_required
def protected():
if current_user.user_level == 'admin':
return f'Hello, Admin {current_user.username}! This is a protected page.'
return f'Hello, {current_user.username}! This is a protected page.'

@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('login'))


# def admin_required(f):
# """Decorator to ensure the current user is an admin."""
# @wraps(f)
# def decorated_function(*args, **kwargs):
# if not current_user.is_authenticated or current_user.user_level != 'admin':
# flash('Access denied. Admins only.')
# return redirect(url_for('login'))
# return f(*args, **kwargs)
# return decorated_function

# def user_required(f):
# """Decorator to ensure the current user is a regular user."""
# @wraps(f)
# def decorated_function(*args, **kwargs):
# if not current_user.is_authenticated or current_user.user_level != 'user':
# flash('Access denied. Users only.')
# return redirect(url_for('login'))
# return f(*args, **kwargs)
# return decorated_function
4 changes: 2 additions & 2 deletions src/routes/homepage.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
from flask import render_template, blueprints

from src.config import app
from src.models import SpeedTestResult, DashoardSettings
from src.models import SpeedTestResult, DashboardSettings
from src.utils import datetimeformat, get_system_info

homepage_bp = blueprints.Blueprint("homepage", __name__)

@app.route("/")
def dashboard():
settings = DashoardSettings.query.first()
settings = DashboardSettings.query.first()
SPEEDTEST_COOLDOWN_IN_HOURS = settings.speedtest_cooldown
system_info = get_system_info()

Expand Down
6 changes: 6 additions & 0 deletions src/routes/process.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import os
from flask import request, render_template, blueprints, redirect, url_for, flash
from flask_login import login_required, current_user

from src.config import app
from src.utils import get_top_processes

process_bp = blueprints.Blueprint("process", __name__)

@app.route("/process", methods=["GET", "POST"])
@login_required
def process():
if current_user.user_level != "admin":
flash("You do not have permission to view this page.", "danger")
return redirect(url_for("dashboard"))

number_of_processes = 5 # Default number

if request.method == "POST":
Expand Down
4 changes: 2 additions & 2 deletions src/routes/settings.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from flask import render_template, request, flash, blueprints

from src.config import app, db
from src.models import DashoardSettings
from src.models import DashboardSettings

settings_bp = blueprints.Blueprint("settings", __name__)

@app.route("/settings", methods=["GET", "POST"])
def settings():
# Fetch the settings from the database and update them
settings = DashoardSettings.query.first()
settings = DashboardSettings.query.first()
if settings:
if request.method == "POST":
settings.speedtest_cooldown = int(request.form["speedtest_cooldown"])
Expand Down
4 changes: 2 additions & 2 deletions src/routes/speedtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
from flask import render_template, blueprints

from src.config import app, db
from src.models import DashoardSettings, SpeedTestResult
from src.models import DashboardSettings, SpeedTestResult
from src.utils import run_speedtest

speedtest_bp = blueprints.Blueprint("speedtest", __name__)

@app.route("/speedtest")
def speedtest():
settings = DashoardSettings.query.first()
settings = DashboardSettings.query.first()
SPEEDTEST_COOLDOWN_IN_HOURS = settings.speedtest_cooldown
NUMBER_OF_SPEEDTESTS = settings.number_of_speedtests
n_hour_ago = datetime.datetime.now() - datetime.timedelta(
Expand Down
43 changes: 43 additions & 0 deletions src/static/css/login.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* static/css/login.css */


h2 {
color: #333;
}

form {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 100%;
}

label {
display: block;
margin: 10px 0 5px;
}

input[type="text"],
input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}

input[type="submit"] {
background-color: #28a745;
color: #fff;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}

input[type="submit"]:hover {
background-color: #218838;
}
48 changes: 48 additions & 0 deletions src/static/css/signup.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* static/css/signup.css */



h2 {
color: #333;
}

form {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 100%;
}

label {
display: block;
margin: 10px 0 5px;
}

input[type="text"],
input[type="password"] {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}

input[type="submit"] {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}

input[type="submit"]:hover {
background-color: #0056b3;
}

p {
margin-top: 10px;
}
10 changes: 9 additions & 1 deletion src/templates/dashboard.html
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
{% extends 'base.html' %}{% block title %}Server Dashboard{% endblock %}{% block content %}<div class="container mt-4"><div class="row">{% include 'dasbhboard_comp/other/username.html' %} {% include 'dasbhboard_comp/other/boot_time.html' %} {% include 'dasbhboard_comp/battery/percentage.html' %} {% include 'dasbhboard_comp/cpu/core.html' %} {% include 'dasbhboard_comp/cpu/usages.html' %} {% include 'dasbhboard_comp/cpu/current_temp.html' %} {% include 'dasbhboard_comp/memory/dashboard_memory.html' %} {% include 'dasbhboard_comp/memory/usage.html' %} {% include 'dasbhboard_comp/disk/usage.html' %} {% include 'dasbhboard_comp/other/uptime.html' %} {% include 'dasbhboard_comp/network/stats.html' %} {% include 'dasbhboard_comp/other/speedtest.html' %} </div></div>{% endblock %}
{% extends 'base.html' %}{% block title %}Server Dashboard{% endblock %}{% block content %}<div class="container mt-4">
<div class="row">{% include 'dasbhboard_comp/other/username.html' %}{% include
'dasbhboard_comp/other/boot_time.html' %}{% include 'dasbhboard_comp/battery/percentage.html' %}{% include
'dasbhboard_comp/cpu/core.html' %}{% include 'dasbhboard_comp/cpu/usages.html' %}{% include
'dasbhboard_comp/cpu/current_temp.html' %}{% include 'dasbhboard_comp/memory/dashboard_memory.html' %}{% include
'dasbhboard_comp/memory/usage.html' %}{% include 'dasbhboard_comp/disk/usage.html' %}{% include
'dasbhboard_comp/other/uptime.html' %}{% include 'dasbhboard_comp/network/stats.html' %}{% include
'dasbhboard_comp/other/speedtest.html' %} </div>
</div>{% endblock %}
Loading

0 comments on commit 22267da

Please sign in to comment.