-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
84 lines (61 loc) · 2.56 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from flask import Blueprint, render_template, redirect, url_for, request, flash, session
from sqlalchemy.exc import PendingRollbackError
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, login_required, logout_user
from models import User
from flask import current_app
db = current_app.config['SQLALCHEMY_DATABASE']
auth = Blueprint('auth', __name__)
def check_login(email):
check = False
for try_ in range(100):
if not check:
try:
user = User.query.filter_by(email=email).first()
check = True
return user
except PendingRollbackError:
db.session.rollback()
@auth.route('/login')
def login():
return render_template('login.html')
@auth.route('/login', methods=['POST'])
def login_post():
# login code goes here
email = request.form.get('email')
password = request.form.get('password')
remember = True if request.form.get('remember') else False
# check if connection still active
user = check_login(email=email)
# check if the user actually exists
# take the user-supplied password, hash it, and compare it to the hashed password in the database
if not user or not user.password.strip() == password:
flash('Please check your login details and try again.')
return redirect(url_for('auth.login')) # if the user doesn't exist or password is wrong, reload the page
# if the above check passes, then we know the user has the right credentials
login_user(user, remember=remember)
return redirect(url_for('dataset.index_ds'))
@auth.route('/signup')
def signup():
return render_template('signup.html')
@auth.route('/signup', methods=['POST'])
def signup_post():
# code to validate and add user to database goes here
email = request.form.get('email')
name = request.form.get('name')
password = request.form.get('password')
user = check_login(email=email)
if user: # if a user is found, we want to redirect back to signup page so user can try again
flash('Email address already exists')
return redirect(url_for('auth.signup'))
# create a new user with the form data. Hash the password so the plaintext version isn't saved.
new_user = User(email=email, name=name, password=password)
# add the new user to the database
db.session.add(new_user)
db.session.commit()
return redirect(url_for('auth.login'))
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('main.index'))