husstanden/forms/login.py

109 lines
2.6 KiB
Python

from wtforms import Form, BooleanField, StringField, PasswordField, TextAreaField, validators
from wtforms.fields.html5 import DateField, DecimalField, IntegerField
from wtforms.widgets import TextArea
from flask_login import UserMixin
from flask_babel import gettext as _
from objects import glob
FORM_RENDER_KW = {
"class_": "form-control"
}
class BillForm(Form):
payment_to = StringField(_("Payment to"), [validators.DataRequired()])
description = TextAreaField(_("Description"), render_kw = {
"cols": 55,
"rows": 8
})
sum = DecimalField(_("Sum"))
kid = IntegerField(_("KID"))
date_due = DateField(_("Date due"))
class LoginForm(Form):
email = StringField(_("Email"), [
validators.DataRequired(),
validators.Length(min=6, max=254)
],
render_kw = FORM_RENDER_KW)
password = PasswordField(_("Password"), [
validators.DataRequired(),
validators.Length(min=4, max=127)
],
render_kw = FORM_RENDER_KW)
class RegisterForm(Form):
email = StringField(_("Email"), [
validators.DataRequired(),
validators.Length(min=6, max=254)
],
render_kw = FORM_RENDER_KW)
password = PasswordField(_("Password"), [
validators.DataRequired(),
validators.Length(min=4, max=127),
validators.EqualTo("confirm_password", message = _("Passwords must match"))
],
render_kw = FORM_RENDER_KW)
confirm_password = PasswordField(_("Repeat Password"), render_kw = FORM_RENDER_KW)
firstname = StringField(_("Firstname"), [
validators.DataRequired(),
validators.Length(min=2, max=30)
],
render_kw = FORM_RENDER_KW)
surname = StringField(_("Surname"), [
validators.DataRequired(),
validators.Length(min=2, max=30)
],
render_kw = FORM_RENDER_KW)
accept_tos = BooleanField(_("I accept the TOS"), [validators.DataRequired()])
class User(UserMixin):
id = -1
email = ""
password = ""
firstname = ""
surname = ""
def __init__(self, login):
self.fetch_from_db(login)
def fetch_from_db(self, login):
conn = glob.get_sql_connection()
cur = conn.cursor()
cur.execute("""
SELECT *
FROM Bruker
WHERE Epost = %s
LIMIT 1;
""", (login[0],))
user = cur.fetchone()
cur.close()
if user is None:
raise Exception(_("Invalid login"))
if not glob.check_password(login[1], user[2]):
raise Exception(_("Incorrect password"))
self.id, self.email, self.password, self.firstname, self.surname = user
def register_account(email, password, firstname, surname):
conn = glob.get_sql_connection()
cur = conn.cursor()
cur.execute("""
INSERT INTO
Bruker (Epost, Passord, Fornavn, Etternavn)
VALUES (%s, %s, %s, %s);
""", (email, glob.hash_password(password), firstname, surname))
conn.commit()
cur.close()