ciclos

ref: responsive

src/blueprints/auth.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from flask import Blueprint, render_template, url_for, redirect, request, flash
from ..types.user import User
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, current_user, logout_user

auth = Blueprint('auth', __name__, url_prefix = "/auth")

@auth.route('/login', methods = ['GET', 'POST'])
def login():
    if request.method == 'GET':
        if current_user.is_authenticated:
            return redirect(url_for('basic.main'))
        else:
            return render_template('login.html', title = "Entrar - Feira Virtual Bem da Terra")
    else:
        email = request.form.get('email')
        password = request.form.get('password')

        user = User.query.filter_by(email = email).first()
        
        if not user or not check_password_hash(user.password, password):
            flash('User not found or credentials does not match our records...')
            
            return redirect(url_for('auth.login'))

        # User exists and works!
        login_user(user, remember = False)
        return redirect(url_for('basic.index'))

@auth.route('/sign_up', methods = ['GET', 'POST'])
def sign_up():
    if request.method == 'GET':
        return render_template('sign_up.html', title = "Cadastrar - Feira Virtual Bem da Terra")
    else:
        email = request.form.get('email')
        user = User.query.filter_by(email = email).first()
        
        if user:
            flash('You already have an account, perhaps log in?')
            return redirect(url_for('auth.login'))
        else:
            username   = request.form.get('username')
            password   = request.form.get('password')
            first_name = request.form.get('first_name')
            last_name  = request.form.get('last_name')
            
            new_user = User(
                    email,
                    generate_password_hash(password, method = 'sha256'),
                    username,
                    first_name,
                    last_name
            )

            new_user.create()
            
            flash('Account created successfully')
            return redirect(url_for('auth.login'))

@auth.route('/logout')
def logout():
    logout_user()

    return redirect(url_for('basic.index'))