Commit 424b4b33 authored by Petr Babic's avatar Petr Babic
Browse files

Enable login

* create login page
* create database
* verify user login
parent 93681b18
Loading
Loading
Loading
Loading

app.py

0 → 100644
+26 −0
Original line number Diff line number Diff line
from flask import Flask, render_template, request, redirect, url_for
import src.database as db


app = Flask(__name__, static_folder='static')


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


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if db.validate_login(request.form['email'],
                             request.form['password']):
            return 'success!'
        else:
            error = 'Invalid email/password'
    return render_template('login.html', error=error)


if __name__ == '__main__':
    app.run()

data/.gitignore

0 → 100644
+2 −0
Original line number Diff line number Diff line
*
!.gitignore
 No newline at end of file

src/database.py

0 → 100644
+69 −0
Original line number Diff line number Diff line
import sqlite3
import re
import hashlib
from typing import Tuple, Optional


DATABASE = 'data/data.db'


class Customer:
    def __init__(self, row: Tuple[str, str]) -> None:
        self.email, self.pass_hash = row

    @classmethod
    def get(cls, email: str) -> Optional['Customer']:
        con = sqlite3.connect(DATABASE)
        cur = con.cursor()
        res = cur.execute(f"SELECT * FROM customer WHERE email = '{email}'").fetchall()
        return cls(res[0]) if res else None

    def write(self) -> None:
        con = sqlite3.connect(DATABASE)
        cur = con.cursor()
        cur.execute(f'INSERT INTO customer VALUES(\'{self.email}\', \'{self.pass_hash}\')')
        con.commit()


def validate_login(email: str, password: str) -> bool:
    if not re.match('^[\w\-.]+@([\w-]+\.)+[\w-]{2,4}$', email) or not password:
        return False

    pass_hash = hashlib.sha256(bytes(password, 'utf-8'),
                               usedforsecurity=True).hexdigest()
    cust = Customer.get(email)
    if cust:
        return cust.pass_hash == pass_hash

    Customer((email, pass_hash)).write()
    return True


def setup():
    con = sqlite3.connect(DATABASE)
    cur = con.cursor()

    res = cur.execute('SELECT name FROM sqlite_master')
    tables = [t[0] for t in res.fetchall()]

    if 'customer' not in tables:
        cur.execute('CREATE TABLE customer(email TEXT, password_hash TEXT)')
    if 'order_' not in tables:
        cur.execute('CREATE TABLE order_(status TEXT, time_created INTEGER, customer_id INTEGER)')
    if 'menu_item' not in tables:
        cur.execute('CREATE TABLE menu_item(name TEXT, description TEXT, price INTEGER)')


def clear():
    con = sqlite3.connect(DATABASE)
    cur = con.cursor()
    for table in ['customer', 'order_', 'menu_item']:
        cur.execute(f'DROP TABLE {table}')
    con.commit()


if __name__ == '__main__':
    clear()
    setup()
else:
    setup()

static/css/login.css

0 → 100644
+50 −0
Original line number Diff line number Diff line
.rectangle-1 {
	width: 391px;
	height: 305px;
	padding: 8px 8px 8px 8px;
	background: #ffffff;
	border-color: #000000;
	border-width: 1px;
	border-style: solid;
	border-radius: 14px 14px 14px 14px;
	margin: 0 auto;
}
.text-input {
	width: 180px;
	height: 32px;
	padding: 4px 8px 4px 8px;
	background: #ffffff;
	color: black;
	border-color: #232323;
	border-width: 1px;
	border-style: solid;
	border-radius: 6px 6px 6px 6px;
	font-family: "Helvetica";
	font-weight: 400;
	font-size: 14px;
	text-align: left;
	display: flex;
	align-items: center;
	margin: 0 auto;
}

.button {
	width: 120px;
	height: 25px;
	padding: 0px 10px 0px 10px;
	background: #aedd94;
	color: #232323;
	border-color: #232323;
	border-width: 1px;
	border-style: solid;
	border-radius: 5px 5px 5px 5px;
	font-family: "Helvetica";
	font-weight: 400;
	font-size: 14px;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 auto;
}
.button:hover { background: limegreen }

templates/login.html

0 → 100644
+17 −0
Original line number Diff line number Diff line
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../static/css/login.css">
    <title>My Flask App</title>
</head>
<body>
    <div class="rectangle-1">
    <form action="{{ url_for('login') }}" method="post">
        <input type="text" class="text-input" id="email" name="email" style="margin-top: 50px" placeholder="email">
        <input type="password" class="text-input" id="password" name="password" style="margin-top: 10px" placeholder="password">
        <button class="button" type="submit" style="margin-top: 20px">Log In</button>
    </form>
    </div>
</body>
</html>
 No newline at end of file