-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.py
68 lines (57 loc) · 2.43 KB
/
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
65
66
67
68
from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from flask_login import login_user, login_required, logout_user, current_user
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
user = User.query.filter_by(email=email).first()
if user:
if check_password_hash(user.password, password):
flash('Logged in successfully.', category='success')
login_user(user, remember=True)
return redirect(url_for('views.index'))
else:
flash('Wrong password.', category='error')
else:
flash('This user does not exist', category='error')
return render_template('login.html', user=current_user)
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.login'))
@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
if request.method == 'POST':
email = request.form['email']
name = request.form['name']
password = request.form['password']
confirm_password = request.form['cpass']
user = User.query.filter_by(email=email).first()
if user:
flash('This email is already registered, try other email.', category='error')
elif len(email) < 4:
flash('Email must greather then 4 characters.', category='error')
elif len(name) < 2:
flash('First name must greather then 2 characters.', category='error')
elif password != confirm_password:
flash('The password does not match.', category='error')
elif len(password) < 8:
flash('Password must greather then 8 characters.', category='error')
else:
new_user = User(
email = email,
password = generate_password_hash(password, method='sha256'),
name = name
)
db.session.add(new_user)
db.session.commit()
login_user(user, remember=True)
flash('Account created.', category='success')
return redirect(url_for('views.index'))
return render_template('sign_up.html', user=current_user)