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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
|
from flask import Flask, render_template, request, redirect, url_for, session, flash
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
import pyodbc
from datetime import datetime
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['SESSION_TYPE'] = 'filesystem'
DB_CONFIG = {
'server': 'dc01.eighteen.htb',
'database': 'financial_planner',
'username': 'appdev',
'password': 'MissThisElite$90',
'driver': '{ODBC Driver 17 for SQL Server}',
'TrustServerCertificate': 'True'
}
def get_db_connection():
conn_str = f"DRIVER={DB_CONFIG['driver']};SERVER={DB_CONFIG['server']};DATABASE={DB_CONFIG['database']};UID={DB_CONFIG['username']};PWD={DB_CONFIG['password']}"
return pyodbc.connect(conn_str)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash('Please log in to access this page.', 'warning')
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
flash('Please log in to access this page.', 'warning')
return redirect(url_for('login'))
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT is_admin FROM users WHERE id = ?", (session['user_id'],))
user = cursor.fetchone()
conn.close()
if not user or not user[0]:
flash('Access denied. Admin privileges required.', 'danger')
return redirect(url_for('dashboard'))
return f(*args, **kwargs)
return decorated_function
def track_visit(page):
try:
conn = get_db_connection()
cursor = conn.cursor()
user_agent = request.headers.get('User-Agent', 'Unknown')
cursor.execute(
"INSERT INTO visits (user_agent, visited_page, timestamp) VALUES (?, ?, ?)",
(user_agent, page, datetime.now())
)
conn.commit()
conn.close()
except:
pass
@app.route('/')
def index():
track_visit('/')
return render_template('index.html')
@app.route('/features')
def features():
track_visit('/features')
return render_template('features.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
track_visit('/register')
if request.method == 'POST':
full_name = request.form['full_name']
username = request.form['username']
email = request.form['email']
password = request.form['password']
password_hash = generate_password_hash(password, 'pbkdf2')
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO users (full_name, username, email, password_hash, is_admin, created_at) VALUES (?, ?, ?, ?, 0, ?)",
(full_name, username, email, password_hash, datetime.now())
)
conn.commit()
conn.close()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
except Exception as e:
flash(f'Registration failed. Username or email may already exist. {e}', 'danger')
return redirect(url_for('register'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
track_visit('/login')
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT id, password_hash, full_name FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
if user and check_password_hash(user[1], password):
session['user_id'] = user[0]
session['username'] = username
session['full_name'] = user[2]
flash(f'Welcome back, {user[2]}!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password.', 'danger')
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
flash('You have been logged out.', 'info')
return redirect(url_for('index'))
@app.route('/dashboard')
@login_required
def dashboard():
track_visit('/dashboard')
user_id = session['user_id']
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT monthly_salary, yearly_salary FROM incomes WHERE user_id = ? ORDER BY created_at DESC", (user_id,))
income = cursor.fetchone()
cursor.execute("SELECT id, category, type, value FROM expenses WHERE user_id = ?", (user_id,))
expenses = cursor.fetchall()
cursor.execute("SELECT savings, investments FROM allocations WHERE user_id = ? ORDER BY created_at DESC", (user_id,))
allocation = cursor.fetchone()
conn.close()
monthly_salary = income[0] if income else 0
yearly_salary = income[1] if income else 0
total_expenses = 0
expense_list = []
for exp in expenses:
exp_id, category, exp_type, value = exp
if exp_type == 'fixed':
amount = value
else:
amount = (value / 100) * monthly_salary
total_expenses += amount
expense_list.append({
'id': exp_id,
'category': category,
'type': exp_type,
'value': value,
'amount': amount
})
remaining = monthly_salary - total_expenses
savings = allocation[0] if allocation else 0
investments = allocation[1] if allocation else 0
return render_template('dashboard.html',
monthly_salary=monthly_salary,
yearly_salary=yearly_salary,
expenses=expense_list,
total_expenses=total_expenses,
remaining=remaining,
savings=savings,
investments=investments)
@app.route('/update_income', methods=['POST'])
@login_required
def update_income():
user_id = session['user_id']
monthly_salary = float(request.form['monthly_salary'])
yearly_salary = monthly_salary * 12
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT id FROM incomes WHERE user_id = ?", (user_id,))
existing = cursor.fetchone()
if existing:
cursor.execute(
"UPDATE incomes SET monthly_salary = ?, yearly_salary = ? WHERE user_id = ?",
(monthly_salary, yearly_salary, user_id)
)
else:
cursor.execute(
"INSERT INTO incomes (user_id, monthly_salary, yearly_salary, created_at) VALUES (?, ?, ?, ?)",
(user_id, monthly_salary, yearly_salary, datetime.now())
)
conn.commit()
conn.close()
flash('Income updated successfully!', 'success')
return redirect(url_for('dashboard'))
@app.route('/add_expense', methods=['POST'])
@login_required
def add_expense():
user_id = session['user_id']
category = request.form['category']
exp_type = request.form['type']
value = float(request.form['value'])
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO expenses (user_id, category, type, value, created_at) VALUES (?, ?, ?, ?, ?)",
(user_id, category, exp_type, value, datetime.now())
)
conn.commit()
conn.close()
flash('Expense added successfully!', 'success')
return redirect(url_for('dashboard'))
@app.route('/delete_expense/<int:expense_id>', methods=['POST'])
@login_required
def delete_expense(expense_id):
user_id = session['user_id']
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("DELETE FROM expenses WHERE id = ? AND user_id = ?", (expense_id, user_id))
conn.commit()
conn.close()
flash('Expense deleted successfully!', 'success')
return redirect(url_for('dashboard'))
@app.route('/update_allocation', methods=['POST'])
@login_required
def update_allocation():
user_id = session['user_id']
savings = float(request.form['savings'])
investments = float(request.form['investments'])
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT id FROM allocations WHERE user_id = ?", (user_id,))
existing = cursor.fetchone()
if existing:
cursor.execute(
"UPDATE allocations SET savings = ?, investments = ? WHERE user_id = ?",
(savings, investments, user_id)
)
else:
cursor.execute(
"INSERT INTO allocations (user_id, savings, investments, created_at) VALUES (?, ?, ?, ?)",
(user_id, savings, investments, datetime.now())
)
conn.commit()
conn.close()
flash('Allocation updated successfully!', 'success')
return redirect(url_for('dashboard'))
@app.route('/admin')
@admin_required
def admin():
track_visit('/admin')
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM users")
total_users = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM visits")
total_visits = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM expenses")
total_expenses_count = cursor.fetchone()[0]
avg_expenses = total_expenses_count / total_users if total_users > 0 else 0
cursor.execute("SELECT AVG(savings), AVG(investments) FROM allocations")
allocation_avg = cursor.fetchone()
avg_savings = allocation_avg[0] if allocation_avg[0] else 0
avg_investments = allocation_avg[1] if allocation_avg[1] else 0
cursor.execute("SELECT category, COUNT(*) as count FROM expenses GROUP BY category ORDER BY count DESC")
top_categories = cursor.fetchall()[:5]
cursor.execute("SELECT full_name, username, email, created_at FROM users ORDER BY created_at DESC")
recent_users = cursor.fetchall()[:5]
conn.close()
return render_template('admin.html',
total_users=total_users,
total_visits=total_visits,
avg_expenses=avg_expenses,
avg_savings=avg_savings,
avg_investments=avg_investments,
top_categories=top_categories,
recent_users=recent_users)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
|