Skip to content

Commit

Permalink
Fix and rework auth
Browse files Browse the repository at this point in the history
  • Loading branch information
leechwort committed Nov 30, 2023
1 parent 4ded6dc commit de6062e
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 44 deletions.
56 changes: 18 additions & 38 deletions app/application.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, render_template, request, redirect, url_for
from flask_login import (
LoginManager,
UserMixin,
login_user,
logout_user,
login_required,
current_user,
)

from flask import Flask, render_template, jsonify, request, redirect, url_for

import logging
import threading
import time
from logging.handlers import RotatingFileHandler


from api.device_api import device_api
from api.web_api import web_api
from models.admin_user import AdminUser
# New
from models.device import Device
from models.user import User
from models.access_log import AccessLog

from api.web_api import web_api
from api.device_api import device_api

app = Flask(__name__)
app.register_blueprint(web_api)
app.register_blueprint(device_api)


app.config["SECRET_KEY"] = "secret_key"
logger = logging.getLogger(__name__)

Expand All @@ -49,6 +41,7 @@
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)


# noinspection PyBroadException
# @login_manager.user_loader
# def loader_user(user_id):
Expand All @@ -74,22 +67,9 @@
# Admin routes


class User(UserMixin):
def __init__(self, username, password):
self.username = ""
self.password = ""
self.id = 1

def check_password(self, password):
return True

def is_authenticated(self):
return True


@login_manager.user_loader
def load_user(user_id):
return User("", "")
return AdminUser("", "")


@app.route("/init_app", methods=["GET", "POST"])
Expand All @@ -99,15 +79,16 @@ def init_app_route():

username = request.form["username"]
password = request.form["password"]
slat = request.form["slat"]
if "file" in request.files:
file = request.files["file"]
else:
file = None
AdminUser(username, password).create_user()

# if "file" in request.files:
# file = request.files["file"]
# else:
# file = None

# init_app(username, password, slat, file)

return redirect(url_for("admin.login"))
return redirect(url_for("login"))


@app.route("/login", methods=["GET", "POST"])
Expand All @@ -121,7 +102,7 @@ def login():
username = request.form["username"]
password = request.form["password"]

user = User(username, password)
user = AdminUser(username)
if user is None or not user.check_password(password):
return render_template("auth/login.html", error="Invalid username or password")

Expand All @@ -132,7 +113,7 @@ def login():
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for("admin.login"))
return redirect(url_for("login"))


# App routes
Expand All @@ -150,7 +131,6 @@ def index():
@app.route("/users", methods=["GET"])
@login_required
def users():

# Latest triggered key is used for new users registration.
latest_triggered_key = Device.get_latest_key()
logger.info("Latest triggered key: %s", latest_triggered_key)
Expand Down
40 changes: 40 additions & 0 deletions app/models/admin_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import sqlite3

import argon2
from flask_login import UserMixin


class AdminUser(UserMixin):
def __init__(self, username, password=None):
self.username = username
if password:
self.hashed_password = argon2.PasswordHasher().hash(password)
self.id = 1

def check_password(self, password):
connection = sqlite3.connect("database.db")
cursor = connection.cursor()

cursor.execute("SELECT password FROM admins WHERE username = ?", (self.username,))
result = cursor.fetchone()
connection.close()
if not result:
print("USERNAME IS NOT FOUND")
return False
try:
print("Verify hash result:", argon2.PasswordHasher().verify(result[0], password))
return True
except argon2.exceptions.VerifyMismatchError:
print("PASSWORD IS INCORRECT")
return False

def create_user(self):
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
cursor.execute("INSERT OR REPLACE INTO admins (id, username, password) VALUES (1, ?, ?)",
(self.username, self.hashed_password))
connection.commit()
connection.close()

def is_authenticated(self):
return True
6 changes: 1 addition & 5 deletions app/templates/auth/init_app.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ <h2>Create your admin user</h2>

<label for="password">Admin Password:</label>
<input type="password" id="password" name="password" required>

<label for="slat">Slat, the secure string using for hash the admin password</label>
<label for="slat">We recommend to generate random string for the field, and keep it save</label>
<input type="text" id="slat" name="slat" required>


<input type="checkbox" id="toggleCheckbox">
<label for="toggleCheckbox">Restore from database backup</label>

Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ flask-login
schedule
pylint
pycodestyle
gunicorn==20.0.4
gunicorn==20.0.4
argon2-cffi

0 comments on commit de6062e

Please sign in to comment.