-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
74 lines (59 loc) · 2.15 KB
/
app.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
from flask import Flask, render_template, request, redirect, url_for, session
import mysql.connector
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = 'secret_key'
# Database connection
def get_db_connection():
conn = mysql.connector.connect(
host='localhost',
user='root',
password='root',
database='userauth'
)
return conn
@app.route('/')
def home():
return render_template('home.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
user = cursor.fetchone()
conn.close()
if user and check_password_hash(user['password'], password):
session['user_id'] = user['id']
session['username'] = user['username']
return redirect(url_for('dashboard'))
else:
return 'Incorrect username or password'
return render_template('login.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
hashed_password = generate_password_hash(password)
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, hashed_password))
conn.commit()
conn.close()
return redirect(url_for('login'))
return render_template('signup.html')
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('login'))
return f"Welcome {session['username']}!"
@app.route('/logout')
def logout():
session.pop('user_id', None)
session.pop('username', None)
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)