mirror of
https://github.com/csd4ni3l/loginween.git
synced 2026-01-01 04:23:48 +01:00
Add working register and login with database, add a register page, make a new pattern file for handling it
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -181,3 +181,4 @@ logs/
|
||||
logs
|
||||
settings.json
|
||||
data.json
|
||||
data.db
|
||||
@@ -1,8 +1,10 @@
|
||||
from flask import Flask, render_template, redirect, url_for, g
|
||||
from flask import Flask, Response, render_template, redirect, url_for, g, request
|
||||
|
||||
from flask_login import LoginManager, login_required
|
||||
|
||||
import sqlite3, os, flask_login, dotenv, secrets
|
||||
from loginween.pattern import Pattern
|
||||
|
||||
import sqlite3, os, flask_login, dotenv, secrets, json
|
||||
|
||||
if os.path.exists(".env"):
|
||||
dotenv.load_dotenv(".env")
|
||||
@@ -23,7 +25,7 @@ def get_db():
|
||||
db.execute("""
|
||||
CREATE TABLE IF NOT EXISTS Users (
|
||||
username TEXT PRIMARY KEY,
|
||||
pumpkin_carving TEXT PRIMARY KEY
|
||||
pattern TEXT UNIQUE
|
||||
)
|
||||
""")
|
||||
|
||||
@@ -53,12 +55,60 @@ def unathorized_handler():
|
||||
def main():
|
||||
return render_template("index.jinja2")
|
||||
|
||||
@app.route("/login")
|
||||
@app.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
return render_template("login.jinja2")
|
||||
if request.method == "GET":
|
||||
if flask_login.current_user.is_authenticated:
|
||||
return redirect(url_for("main"))
|
||||
|
||||
@app.route("/register")
|
||||
return render_template("login.jinja2", grid_size=os.getenv("GRID_SIZE", 25))
|
||||
|
||||
elif request.method == "POST":
|
||||
username = request.form["username"]
|
||||
pattern = Pattern.from_str(request.form["pattern"])
|
||||
|
||||
cur = get_db().cursor()
|
||||
|
||||
cur.execute("SELECT pattern from Users WHERE username = ?", (username, ))
|
||||
|
||||
required_pattern = cur.fetchone()
|
||||
if not required_pattern:
|
||||
cur.close()
|
||||
return Response("An account with this username doesn't exist.", 400)
|
||||
|
||||
if pattern == Pattern.from_json_str(required_pattern[0]):
|
||||
cur.close()
|
||||
|
||||
user = User()
|
||||
user.id = username
|
||||
flask_login.login_user(user, remember=True)
|
||||
|
||||
return redirect(url_for("main"))
|
||||
|
||||
@app.route("/register", methods=["GET", "POST"])
|
||||
def register():
|
||||
return render_template("register.jinja2")
|
||||
if request.method == "GET":
|
||||
if flask_login.current_user.is_authenticated:
|
||||
return redirect(url_for("main"))
|
||||
|
||||
return render_template("register.jinja2", grid_size=os.getenv("GRID_SIZE", 25))
|
||||
|
||||
elif request.method == "POST":
|
||||
username = request.form["username"]
|
||||
pattern = Pattern.from_str(request.form["pattern"])
|
||||
|
||||
cur = get_db().cursor()
|
||||
|
||||
cur.execute("SELECT username from Users WHERE username = ?", (username, ))
|
||||
|
||||
if cur.fetchone():
|
||||
cur.close()
|
||||
return Response("An account with this username already exists.", 400)
|
||||
|
||||
cur.execute("INSERT INTO Users (username, pattern) VALUES (?, ?)", (username, pattern.to_json_str()))
|
||||
get_db().commit()
|
||||
cur.close()
|
||||
|
||||
return redirect(url_for("login"))
|
||||
|
||||
app.run(host=os.getenv("HOST", "0.0.0.0"), port=os.getenv("PORT", 8080), debug=os.getenv("DEBUG_MODE", False))
|
||||
22
loginween/pattern.py
Normal file
22
loginween/pattern.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import json
|
||||
|
||||
class Pattern():
|
||||
def __init__(self, data: list[tuple]):
|
||||
self.data: list[tuple] = data
|
||||
|
||||
@classmethod
|
||||
def from_str(cls, string):
|
||||
return cls([tuple(map(int, pos.split(","))) for pos in json.loads(string)])
|
||||
|
||||
@classmethod
|
||||
def from_json_str(cls, data):
|
||||
return cls(list(map(tuple, json.loads(data))))
|
||||
|
||||
def to_json_str(self):
|
||||
return json.dumps(self.data)
|
||||
|
||||
def __eq__(self, value):
|
||||
if not isinstance(value, Pattern):
|
||||
return False
|
||||
|
||||
return set(self.data) == set(value.data)
|
||||
@@ -15,14 +15,20 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form id="login_form" method="post" target="/login">
|
||||
<div class="position-absolute top-50 start-50 translate-middle text-center">
|
||||
<h1>LoginWeen: Draw your carving to log in!</h1>
|
||||
<h1>Draw a carving to login!</h1>
|
||||
<input type="hidden" name="pattern" id="pattern_field">
|
||||
<canvas id="pumpkin_canvas" width="600" height="600" class="my-3"></canvas>
|
||||
<div class="input-group mb-3">
|
||||
<input id="username_field" name="username" type="text" class="form-control" placeholder="Username" aria-label="Username">
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<button type="button" class="btn btn-primary me-2" id="loginBtn">Login</button>
|
||||
<button type="submit" class="btn btn-primary me-2" id="loginBtn">Login</button>
|
||||
<button id="clearBtn" class="btn btn-danger">Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
const canvas = document.getElementById('pumpkin_canvas');
|
||||
@@ -30,7 +36,7 @@ const ctx = canvas.getContext('2d');
|
||||
const img = new Image();
|
||||
img.src = '/static/pumpkin.png';
|
||||
|
||||
const GRID_SIZE = 25;
|
||||
const GRID_SIZE = {{ grid_size }};
|
||||
const CELL_SIZE = canvas.width / GRID_SIZE;
|
||||
|
||||
img.onload = () => {
|
||||
@@ -60,7 +66,7 @@ function draw(e) {
|
||||
|
||||
var pixel = ctx.getImageData(cellX, cellY, 1, 1).data;
|
||||
|
||||
if (pixel[0] == 255 && pixel[1] == 126) {
|
||||
if (pixel[0] >= 254 && (pixel[1] >= 124 && pixel[1] <= 126)) {
|
||||
var key = `${gridX},${gridY}`;
|
||||
|
||||
if (!currentPattern.includes(key)) {
|
||||
@@ -93,9 +99,10 @@ function drawGrid() {
|
||||
}
|
||||
}
|
||||
|
||||
{# document.getElementById('loginBtn').addEventListener('click', () => {
|
||||
...
|
||||
}); #}
|
||||
document.getElementById("login_form").addEventListener('submit', function(event) {
|
||||
document.getElementById('pattern_field').value = JSON.stringify(currentPattern);
|
||||
});
|
||||
|
||||
|
||||
document.getElementById('clearBtn').addEventListener('click', clearCanvas);
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{% extends "base.jinja2" %}
|
||||
|
||||
{% block title %}RegiWeen{% endblock %}
|
||||
{% block title %}Loginween Register{% endblock %}
|
||||
|
||||
{% block nav %}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/login">Login</a>
|
||||
<a class="nav-link active" aria-current="page" href="/login">Login</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link active" aria-current="page" href="/register">Register</a>
|
||||
<a class="nav-link" href="/register">Register</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/logout">Logout</a>
|
||||
@@ -15,4 +15,102 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form id="register_form" method="post" target="/register">
|
||||
<div class="position-absolute top-50 start-50 translate-middle text-center">
|
||||
<h1>Draw a carving to register!</h1>
|
||||
<input type="hidden" name="pattern" id="pattern_field">
|
||||
<canvas id="pumpkin_canvas" width="600" height="600" class="my-3"></canvas>
|
||||
<div class="input-group mb-3">
|
||||
<input id="username_field" name="username" type="text" class="form-control" placeholder="Username" aria-label="Username">
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<button type="submit" class="btn btn-primary me-2" id="registerBtn">Register</button>
|
||||
<button id="clearBtn" class="btn btn-danger">Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
const canvas = document.getElementById('pumpkin_canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
const img = new Image();
|
||||
img.src = '/static/pumpkin.png';
|
||||
|
||||
const GRID_SIZE = {{ grid_size }};
|
||||
const CELL_SIZE = canvas.width / GRID_SIZE;
|
||||
|
||||
img.onload = () => {
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
drawGrid();
|
||||
};
|
||||
|
||||
let drawing = false;
|
||||
let currentPattern = [];
|
||||
let savedPattern = null;
|
||||
|
||||
canvas.addEventListener('mousedown', () => { drawing = true; });
|
||||
canvas.addEventListener('mouseup', () => { drawing = false; });
|
||||
canvas.addEventListener('mousemove', draw);
|
||||
|
||||
function draw(e) {
|
||||
if (!drawing) return;
|
||||
var rect = canvas.getBoundingClientRect();
|
||||
var x = e.clientX - rect.left;
|
||||
var y = e.clientY - rect.top;
|
||||
|
||||
var gridX = Math.floor(x / CELL_SIZE);
|
||||
var gridY = Math.floor(y / CELL_SIZE);
|
||||
|
||||
var cellX = gridX * CELL_SIZE + CELL_SIZE / 3;
|
||||
var cellY = gridY * CELL_SIZE + CELL_SIZE / 3;
|
||||
|
||||
var pixel = ctx.getImageData(cellX, cellY, 1, 1).data;
|
||||
|
||||
if (pixel[0] >= 254 && (pixel[1] >= 124 && pixel[1] <= 126)) {
|
||||
var key = `${gridX},${gridY}`;
|
||||
|
||||
if (!currentPattern.includes(key)) {
|
||||
currentPattern.push(key);
|
||||
ctx.fillStyle = 'black';
|
||||
ctx.fillRect(cellX - CELL_SIZE / 3, cellY - CELL_SIZE / 3, CELL_SIZE, CELL_SIZE);
|
||||
}
|
||||
}
|
||||
else {
|
||||
console.log(pixel);
|
||||
}
|
||||
}
|
||||
|
||||
function drawGrid() {
|
||||
ctx.strokeStyle = 'rgba(0, 0, 0, 0.6)';
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
for (let i = 0; i <= GRID_SIZE; i++) {
|
||||
const pos = i * CELL_SIZE;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(pos, 0);
|
||||
ctx.lineTo(pos, canvas.height);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(0, pos);
|
||||
ctx.lineTo(canvas.width, pos);
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("register_form").addEventListener('submit', function(event) {
|
||||
document.getElementById('pattern_field').value = JSON.stringify(currentPattern);
|
||||
});
|
||||
|
||||
document.getElementById('clearBtn').addEventListener('click', clearCanvas);
|
||||
|
||||
function clearCanvas() {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
drawGrid()
|
||||
currentPattern = [];
|
||||
}
|
||||
|
||||
</script>
|
||||
{% endblock body %}
|
||||
Reference in New Issue
Block a user