-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.py
76 lines (56 loc) · 2.34 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
from flask import render_template, request, session, redirect, flash, get_flashed_messages, Blueprint
from db_utils import get_connection
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
auth_bp = Blueprint('auth_bp', __name__)
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
messages = get_flashed_messages()
return render_template('login.html', messages=messages)
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = get_connection()
c = conn.cursor()
result = c.execute('SELECT * FROM users WHERE username = ?', (username,))
user_data = result.fetchone()
if user_data:
hashed_password = user_data['password']
if check_password_hash(hashed_password, password):
session['username'] = user_data['username']
return redirect('/')
flash('Wrong login or password. Please try again.')
return redirect('/login')
@auth_bp.route('/logout')
def logout():
session.clear()
return redirect('/login')
@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
messages = get_flashed_messages()
return render_template('register.html', messages=messages)
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
hashed_password = generate_password_hash(password)
password = hashed_password
conn = get_connection()
c = conn.cursor()
c.execute('INSERT INTO users VALUES (NULL, ?, ?)', (username, password,))
data_username = c.execute('SELECT username FROM users')
conn.commit()
if username == '' or password == '' or username in data_username:
flash('Please try again. Enter your username and password.')
return redirect('/register')
else:
return redirect('/')
def login_required(view):
@wraps(view)
def wrapped_view(*args, **kwargs):
if session:
return view(*args, **kwargs)
else:
return redirect('/login')
return wrapped_view