make forms less problematic

This commit is contained in:
user 2023-06-22 11:54:15 +00:00
parent f2ee0279f0
commit b19dedc568
9 changed files with 42 additions and 43 deletions

View file

@ -4,10 +4,10 @@ from flask import Flask, render_template, abort
from flask_assets import Bundle from flask_assets import Bundle
from werkzeug.exceptions import HTTPException from werkzeug.exceptions import HTTPException
from server.extensions import db, migrate, cache, assets, login_manager from .config import MIGRATION_DIR, INSTANCE_DIR
from server.models import Users from .extensions import db, migrate, cache, assets, login_manager
from server.config import MIGRATION_DIR, INSTANCE_DIR from .models import Users
from server import views, auth, api, filters from . import views, auth, api, filters
app = Flask(__name__, instance_path=INSTANCE_DIR) app = Flask(__name__, instance_path=INSTANCE_DIR)

View file

@ -5,13 +5,10 @@ from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user from flask_login import login_required, current_user
from werkzeug.security import check_password_hash from werkzeug.security import check_password_hash
from server.models import Scores, Sessions, Users from .models import Scores, Sessions, Users
from server.extensions import db from .extensions import db
from server.config import ( from .config import (
GAME_VERSION,
GAME_VERSIONS,
GAME_DIFFICULTIES, GAME_DIFFICULTIES,
USER_MAX_TOKENS,
MAX_SEARCH_RESULTS, MAX_SEARCH_RESULTS,
USER_REGEX, USER_REGEX,
) )
@ -82,7 +79,7 @@ def post():
@blueprint.route("/search", methods=["GET"]) @blueprint.route("/search", methods=["GET"])
def search(): def search():
search_arg = request.args.get("q") search_arg = request.args.get("q").strip()
if not search_arg: if not search_arg:
return "No search query provided!", 400 return "No search query provided!", 400
@ -98,16 +95,15 @@ def search():
@blueprint.route("/login", methods=["POST"]) @blueprint.route("/login", methods=["POST"])
def login(): def login():
username = request.form["username"].strip() username = request.form.get("username", None).strip()
password = request.form["password"].strip() password = request.form.get("password", None).strip()
device = request.form["device"].strip() device = request.form.get("device", "Unknown").strip()
username_regex = re.compile(USER_REGEX) username_regex = re.compile(USER_REGEX)
if not username or not username_regex.match(username) or not password: if not username or not username_regex.match(username) or not password:
return "Username or Password is incorrect!", 400 return "Username or Password is incorrect!", 400
user = Users.query.filter_by(username=username).first() user = Users.query.filter_by(username=username).first()
if not user or not check_password_hash(user.password, password): if not user or not check_password_hash(user.password, password):
return "Username or Password is incorrect!", 400 return "Username or Password is incorrect!", 400
@ -125,10 +121,9 @@ def login():
@blueprint.route("/authenticate", methods=["POST"]) @blueprint.route("/authenticate", methods=["POST"])
def authenticate(): def authenticate():
auth_key = request.form["auth_key"].strip() auth_key = request.form.get("session", None).strip()
session = Sessions.query.filter_by(auth_key=auth_key).first() session = Sessions.query.filter_by(auth_key=auth_key).first()
if not session: if not session:
return "Invalid session", 400 return "Invalid session", 400

View file

@ -2,12 +2,12 @@ import re
import uuid import uuid
from flask import Blueprint, render_template, request, flash, redirect, url_for from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required, login_user, logout_user, current_user from flask_login import login_user
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from server.extensions import db from .extensions import db
from server.models import Users, Sessions from .models import Users
from server.config import USER_REGEX, USER_EMAIL_REGEX from .config import USER_REGEX
blueprint = Blueprint("auth", __name__) blueprint = Blueprint("auth", __name__)
@ -21,23 +21,20 @@ def auth():
@blueprint.route("/register", methods=["POST"]) @blueprint.route("/register", methods=["POST"])
def register(): def register():
# Get the form data # Get the form data
username = request.form["username"].strip() username = request.form.get("username", None).strip()
email = request.form["email"].strip() password = request.form.get("password", None).strip()
password = request.form["password"].strip() confirm = request.form.get("confirm", None).strip()
username_regex = re.compile(USER_REGEX) username_regex = re.compile(USER_REGEX)
email_regex = re.compile(USER_EMAIL_REGEX)
error = [] error = []
# Validate the form # Validate the form
if not username or not username_regex.match(username): if not username or not username_regex.match(username):
error.append("Username is invalid! Must be alphanumeric, and can contain ._-") error.append("Username is invalid! Must be alphanumeric, and can contain ._-")
if not email or not email_regex.match(email): if not password or len(password) < 8:
error.append("Email is invalid! Must be email format")
if not password:
error.append("Password is empty!")
elif len(password) < 8:
error.append("Password is too short! Must be at least 8 characters long.") error.append("Password is too short! Must be at least 8 characters long.")
if not confirm or password != confirm:
error.append("Passwords do not match!")
if Users.query.filter_by(username=username).first(): if Users.query.filter_by(username=username).first():
error.append("Username already exists!") error.append("Username already exists!")
@ -50,7 +47,6 @@ def register():
register_user = Users( register_user = Users(
alt_id=str(uuid.uuid4()), alt_id=str(uuid.uuid4()),
username=username, username=username,
email=generate_password_hash(email, method="scrypt"),
password=generate_password_hash(password, method="scrypt"), password=generate_password_hash(password, method="scrypt"),
) )
db.session.add(register_user) db.session.add(register_user)

View file

@ -5,7 +5,6 @@ GAME_VERSION = "alpha"
GAME_VERSIONS = ["alpha"] GAME_VERSIONS = ["alpha"]
GAME_DIFFICULTIES = [0, 1, 2, 3, 4] GAME_DIFFICULTIES = [0, 1, 2, 3, 4]
USER_MAX_TOKENS = 3
USER_REGEX = r"\b[A-Za-z0-9._-]+\b" USER_REGEX = r"\b[A-Za-z0-9._-]+\b"
USER_EMAIL_REGEX = r"[^@]+@[^@]+\.[^@]+" USER_EMAIL_REGEX = r"[^@]+@[^@]+\.[^@]+"

View file

@ -1,10 +1,9 @@
""" """
Database models for the server Database models for the server
""" """
import uuid
from flask_login import UserMixin from flask_login import UserMixin
from server.extensions import db from .extensions import db
from server.config import GAME_VERSION from .config import GAME_VERSION
class Scores(db.Model): class Scores(db.Model):
@ -115,7 +114,7 @@ class Users(db.Model, UserMixin):
alt_id = db.Column(db.String, nullable=False, unique=True) alt_id = db.Column(db.String, nullable=False, unique=True)
username = db.Column(db.String(32), unique=True, nullable=False) username = db.Column(db.String(32), unique=True, nullable=False)
email = db.Column(db.String, unique=True, nullable=False) email = db.Column(db.String)
password = db.Column(db.String, nullable=False) password = db.Column(db.String, nullable=False)
joined_at = db.Column( joined_at = db.Column(

View file

@ -28,13 +28,13 @@
</span> </span>
<span class="text-input"> <span class="text-input">
<label for="register-email">Email</label> <label for="register-password">Password</label>
<input type="text" name="email" id="register-email" required> <input type="password" name="password" id="register-password" minlength="8" required>
</span> </span>
<span class="text-input"> <span class="text-input">
<label for="register-password">Password</label> <label for="register-confirm">Confirm</label>
<input type="password" name="password" id="register-password" required> <input type="password" name="confirm" id="register-confirm" minlength="8" required>
</span> </span>
<button type="submit" class="button primary">Register</button> <button type="submit" class="button primary">Register</button>

View file

@ -50,7 +50,10 @@
<span class="spacer"></span> <span class="spacer"></span>
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<a href="{{ url_for('views.settings') }}" class="button primary">{{ current_user.username }}</a> <a href="{{ url_for('views.settings') }}" class="button primary">
{{ current_user.username }}
{% if not current_user.email %}<i class="ph ph-warning"></i>{% endif %}
</a>
{% else %} {% else %}
<a href="{{ url_for('auth.auth') }}" class="button primary"><i class="ph ph-user-circle"></i></a> <a href="{{ url_for('auth.auth') }}" class="button primary"><i class="ph ph-user-circle"></i></a>
{% endif %} {% endif %}

View file

@ -1,5 +1,12 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
{% if not current_user.email %}
<div class="block secondary">
<h2>No Email set</h2>
<p>If you forget your password, you will not be able to recover your account.</p>
</div>
{% endif %}
<div class="block"> <div class="block">
<h2>Hello, {{ current_user.username }}!</h2> <h2>Hello, {{ current_user.username }}!</h2>
<p>Sample text</p> <p>Sample text</p>

View file

@ -1,7 +1,7 @@
from flask import Blueprint, request, render_template, abort, flash, redirect, url_for from flask import Blueprint, request, render_template, abort, flash, redirect, url_for
from flask_login import login_required, current_user, logout_user from flask_login import login_required, current_user, logout_user
from server.models import Scores, Users, Sessions from .models import Scores, Users, Sessions
from server.config import GAME_VERSION, MAX_TOP_SCORES from .config import GAME_VERSION, MAX_TOP_SCORES
blueprint = Blueprint("views", __name__) blueprint = Blueprint("views", __name__)