Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
120 lines (111 loc) · 4.46 KB
/
Copy pathapp.py
File metadata and controls
120 lines (111 loc) · 4.46 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
from flask import Flask, request, render_template, redirect, url_for, session, flash
from flask_bcrypt import Bcrypt
import sqlite3
import os
app = Flask(__name__)
app.secret_key = '78789898' # Secret key for session management
bcrypt = Bcrypt(app) # Initialize Bcrypt for password hashing
""""
# Create database if it doesn't exist , but i have created seperate db_script.py for this purpose
if not os.path.exists('users.db'):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
status TEXT
)
''')
conn.commit()
conn.close()
"""
# Function to get a database connection
def get_db_connection():
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row # This allows us to access columns by name
return conn
# Main route that renders the home page
@app.route('/')
def home():
return render_template('index.html')
# Route for registering users
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
password_hash = bcrypt.generate_password_hash(password).decode('utf-8') # Converts password to hash for security
try:
# Insert new user into the database
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('INSERT INTO users (username, password_hash) VALUES (?, ?)', (username, password_hash))
conn.commit()
conn.close()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
except sqlite3.IntegrityError: # This error occurs if the username already exists
conn.close()
flash('Username already exists.', 'error')
return render_template('register.html')
return render_template('register.html')
# Login process
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Fetch user from the database
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
conn.close()
# Check if user exists and password matches
if user and bcrypt.check_password_hash(user['password_hash'], password):
session['user_id'] = user['id'] # Session used to remember user id, like cookies do
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password.', 'error')
return render_template('login.html')
return render_template('login.html')
# Dashboard route
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session: # Check if user is logged in
flash('Please log in to access the dashboard.', 'error')
return redirect(url_for('login'))
# Fetch user status from the database
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SELECT status FROM users WHERE id = ?', (session['user_id'],)) # Fetches the status of the logged-in user
status = cursor.fetchone()
conn.close()
status = status[0] if status else 'Not set' # Default status if not set
return render_template('dashboard.html', status=status)
# Route to update user status , extra feature for dashboard status update
@app.route('/update_status', methods=['POST'])
def update_status():
if 'user_id' not in session:
flash('Please log in to update status.', 'error')
return redirect(url_for('login'))
# Get the new status from the form
new_status = request.form['status']
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('UPDATE users SET status = ? WHERE id = ?', (new_status, session['user_id']))
conn.commit()
conn.close()
flash('Status updated successfully!', 'success')
return redirect(url_for('dashboard'))
# Logout route
@app.route('/logout')
def logout():
session.pop('user_id', None) # Erases the user_id from the session
flash('Logged out successfully.', 'success')
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)