-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
474 lines (422 loc) · 16.4 KB
/
Copy pathmain.py
File metadata and controls
474 lines (422 loc) · 16.4 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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# imports from flask
import json
import os
from urllib.parse import urljoin, urlparse
from flask import abort, redirect, render_template, request, send_from_directory, url_for, jsonify
from flask_login import current_user, login_user, logout_user
from flask.cli import AppGroup
from flask_login import current_user, login_required
from flask import current_app
from werkzeug.security import generate_password_hash
import shutil
from flask import Flask
from flask_cors import CORS
import logging
# import "objects" from "this" project
from __init__ import app, db, login_manager
# Security helpers: RBAC, IP allowlist, audit logging, rate limiting.
# Imported defensively: if a security dependency is missing in some environment,
# fall back to no-op shims so the app still boots (degraded) instead of 502.
try:
from utils.security import admin_required, ip_allowlist, audit, limiter
except Exception as _sec_err: # noqa: BLE001
logging.getLogger(__name__).error(
"Security helpers unavailable (%s); running WITHOUT RBAC/rate-limit "
"decorators. Install deps: pip install -r requirements.txt", _sec_err,
)
def admin_required(func):
return func
def ip_allowlist(*_args, **_kwargs):
def decorator(func):
return func
return decorator
def audit(*_args, **_kwargs):
return None
class _NoopLimiter:
def limit(self, *_args, **_kwargs):
def decorator(func):
return func
return decorator
limiter = _NoopLimiter()
# API endpoints
from api.user import user_api
from api.pfp import pfp_api
from api.nestImg import nestImg_api
from api.post import post_api
from api.channel import channel_api
from api.group import group_api
from api.mod import section_api
from api.nestPost import nestPost_api
from api.messages_api import messages_api
from api.carphoto import car_api
from api.student import student_api
from api.preferences import preferences_api
from api.chat import chat_api
from api.vote import vote_api
from api.sections import sections_bp
from api.route import routes_api
from api.traffic import traffic_api
from api.savedLocations import savedLocations_api
from api.verify import verify_api
from api.live import incident_api
from api.subscription import subscription_api
from api.stripe_api import stripe_api
from api.businesses import businesses_api
from api.mfa import mfa_api
from api.webauthn import webauthn_api
from api.mtc_511 import mtc_511_api
# database Initialization functions
from model.carChat import CarChat
from model.user import User, initUsers
from model.mod import Section, initSections
from model.group import Group, initGroups
from model.channel import Channel, initChannels
from model.post import Post, initPosts
from model.nestPost import NestPost, initNestPosts
from model.vote import Vote, initVotes
from model.savedLocations import SavedLocations, initSavedLocations
from model.subscription import Subscription, SubscriptionRequest, PaymentHistory, RouteUsage, initSubscriptions
from model.business import BusinessSubmission, initBusinessSubmissions
from model.mfa import UserMFA, initUserMFA
from model.passkey import UserPasskey, initUserPasskeys
from model.backup_codes import UserBackupCode, initUserBackupCodes
# server only View
# register URIs for api endpoints
app.register_blueprint(messages_api)
app.register_blueprint(pfp_api)
app.register_blueprint(user_api)
app.register_blueprint(channel_api)
app.register_blueprint(group_api)
app.register_blueprint(sections_bp)
app.register_blueprint(nestPost_api)
app.register_blueprint(nestImg_api)
app.register_blueprint(vote_api)
app.register_blueprint(car_api)
app.register_blueprint(student_api)
app.register_blueprint(preferences_api)
app.register_blueprint(post_api, url_prefix='/api')
app.register_blueprint(routes_api, url_prefix='/api')
app.register_blueprint(traffic_api, url_prefix='/api')
app.register_blueprint(chat_api, url_prefix='/api')
app.register_blueprint(savedLocations_api) # Registering favoriteBooks API
app.register_blueprint(verify_api)
app.register_blueprint(incident_api)
app.register_blueprint(subscription_api)
app.register_blueprint(stripe_api)
app.register_blueprint(businesses_api)
app.register_blueprint(mfa_api)
app.register_blueprint(webauthn_api)
app.register_blueprint(mtc_511_api)
# Tell Flask-Login the view function name of your login route
login_manager.login_view = "login"
@login_manager.unauthorized_handler
def unauthorized_callback():
return redirect(url_for('login', next=request.path))
# register URIs for server pages
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.context_processor
def inject_user():
return dict(current_user=current_user)
# Helper function to check if the URL is safe for redirects
def is_safe_url(target):
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
@app.route('/login', methods=['GET', 'POST'])
@limiter.limit("10 per minute", methods=["POST"]) # throttle brute-force attempts
def login():
error = None
next_page = request.args.get('next', '') or request.form.get('next', '')
if request.method == 'POST':
username = request.form.get('username', '')
user = User.query.filter_by(_uid=username).first()
if user and user.is_password(request.form.get('password', '')):
login_user(user)
audit("login_success", username=username)
if not is_safe_url(next_page):
return abort(400)
return redirect(next_page or url_for('index'))
else:
audit("login_failure", username=username)
error = 'Invalid username or password.'
return render_template("login.html", error=error, next=next_page)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.errorhandler(404) # catch for URL not found
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/') # connects default URL to index() function
def index():
print("Home:", current_user)
return render_template("index.html")
@app.route('/users/table')
@login_required
@admin_required
@ip_allowlist()
def utable():
users = User.query.all()
# Build a plan/tier map so the unified UI can show each user's plan without
# extra queries in the template. Admins are shown as 'admin'.
tiers = {}
for u in users:
try:
sub = Subscription.query.filter_by(_user_id=u.id).first()
except Exception:
sub = None
if getattr(u, 'role', 'User') == 'Admin':
tiers[u.id] = 'admin'
elif sub and getattr(sub, 'status', None) == 'active':
tiers[u.id] = sub.tier or 'free'
else:
tiers[u.id] = 'free'
return render_template("utable.html", user_data=users, tiers=tiers)
@app.route('/users/table2')
@login_required
@admin_required
@ip_allowlist()
def u2table():
# Consolidated into a single management console; keep the route working by
# redirecting so old links/bookmarks don't break.
return redirect(url_for('utable'))
# Helper function to extract uploads for a user
@app.route('/uploads/<path:filename>')
def uploaded_file(filename):
return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)
@app.route('/users/delete/<int:user_id>', methods=['DELETE'])
@login_required
@admin_required
@ip_allowlist()
def delete_user(user_id):
user = User.query.get(user_id)
if user:
user.delete()
audit("user_deleted", target_user_id=user_id)
return jsonify({'message': 'User deleted successfully'}), 200
return jsonify({'error': 'User not found'}), 404
@app.route('/users/reset_password/<int:user_id>', methods=['POST'])
@login_required
@admin_required
@ip_allowlist()
def reset_password(user_id):
user = User.query.get(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404
# Set the new password
if user.update({"password": app.config['DEFAULT_PASSWORD']}):
audit("password_reset", target_user_id=user_id)
return jsonify({'message': 'Password reset successfully'}), 200
audit("password_reset_failed", target_user_id=user_id)
return jsonify({'error': 'Password reset failed'}), 500
@app.route('/users/set_role/<int:user_id>', methods=['POST'])
@login_required
@admin_required
@ip_allowlist()
def set_user_role(user_id):
"""Promote/demote a user between 'Admin' and 'User' (admin only)."""
user = User.query.get(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404
data = request.get_json(silent=True) or {}
role = (data.get('role') or '').strip()
if role not in ('Admin', 'User'):
return jsonify({'error': 'Invalid role. Must be "Admin" or "User".'}), 400
# Guard: don't let an admin remove their own admin (avoid self lock-out).
if user.id == current_user.id and role != 'Admin':
return jsonify({'error': "You can't remove your own admin role."}), 400
try:
user.role = role
db.session.commit()
audit("role_changed", target_user_id=user_id, new_role=role)
return jsonify({'message': f'Role updated to {role}', 'role': role}), 200
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/users/set_tier/<int:user_id>', methods=['POST'])
@login_required
@admin_required
@ip_allowlist()
def set_user_tier(user_id):
"""Set a user's subscription plan/tier (admin only). Mirrors the API's
admin set-tier logic so behavior is identical to the app dashboard."""
from datetime import datetime, timedelta
user = User.query.get(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404
data = request.get_json(silent=True) or {}
tier = (data.get('tier') or 'free').strip()
billing_interval = data.get('billing_interval', 'monthly')
if tier not in ('free', 'plus', 'pro'):
return jsonify({'error': 'Invalid tier. Must be "free", "plus", or "pro".'}), 400
days = 30 if billing_interval == 'monthly' else 365
try:
subscription = Subscription.query.filter_by(_user_id=user_id).first()
if not subscription:
subscription = Subscription(
user_id=user_id,
tier=tier,
status='active',
billing_interval=billing_interval if tier != 'free' else None,
)
db.session.add(subscription)
else:
subscription.tier = tier
subscription.status = 'active'
subscription.billing_interval = billing_interval if tier != 'free' else None
subscription.expires_at = (datetime.utcnow() + timedelta(days=days)) if tier != 'free' else None
db.session.commit()
audit("tier_changed", target_user_id=user_id, new_tier=tier)
return jsonify({'message': f'Plan updated to {tier}', 'tier': tier}), 200
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
# Create an AppGroup for custom commands
custom_cli = AppGroup('custom', help='Custom commands')
# Define a command to run the data generation functions
@custom_cli.command('generate_data')
def generate_data():
try:
initUsers()
except Exception as e:
print(f"Error in initUsers: {e}")
try:
initSections()
except Exception as e:
print(f"Error in initSections: {e}")
try:
initGroups()
except Exception as e:
print(f"Error in initGroups: {e}")
try:
initChannels()
except Exception as e:
print(f"Error in initChannels: {e}")
try:
initPosts()
except Exception as e:
print(f"Error in initPosts: {e}")
try:
initNestPosts()
except Exception as e:
print(f"Error in initNestPosts: {e}")
try:
initVotes()
except Exception as e:
print(f"Error in initVotes: {e}")
try:
initSavedLocations()
except Exception as e:
print(f"Error in initSavedLocations: {e}")
try:
initSubscriptions()
except Exception as e:
print(f"Error in initSubscriptions: {e}")
try:
initBusinessSubmissions()
except Exception as e:
print(f"Error in initBusinessSubmissions: {e}")
try:
initUserMFA()
except Exception as e:
print(f"Error in initUserMFA: {e}")
try:
initUserPasskeys()
except Exception as e:
print(f"Error in initUserPasskeys: {e}")
try:
initUserBackupCodes()
except Exception as e:
print(f"Error in initUserBackupCodes: {e}")
# Backup the old database
def backup_database(db_uri, backup_uri):
"""Backup the current database."""
if backup_uri:
db_path = db_uri.replace('sqlite:///', 'instance/')
backup_path = backup_uri.replace('sqlite:///', 'instance/')
shutil.copyfile(db_path, backup_path)
print(f"Database backed up to {backup_path}")
else:
print("Backup not supported for production database.")
# Extract data from the existing database
def extract_data():
data = {}
with app.app_context():
data['users'] = [user.read() for user in User.query.all()]
data['sections'] = [section.read() for section in Section.query.all()]
data['groups'] = [group.read() for group in Group.query.all()]
data['channels'] = [channel.read() for channel in Channel.query.all()]
data['posts'] = [post.read() for post in Post.query.all()]
data['locations'] = [post.read() for post in SavedLocations.query.all()]
return data
# Save extracted data to JSON files
def save_data_to_json(data, directory='backup'):
if not os.path.exists(directory):
os.makedirs(directory)
for table, records in data.items():
with open(os.path.join(directory, f'{table}.json'), 'w') as f:
json.dump(records, f)
print(f"Data backed up to {directory} directory.")
# Load data from JSON files
def load_data_from_json(directory='backup'):
data = {}
for table in ['users', 'sections', 'groups', 'channels', 'posts', 'locations']: # New entry
try:
with open(os.path.join(directory, f'{table}.json'), 'r') as f:
data[table] = json.load(f)
except FileNotFoundError:
print(f"Warning: {table}.json not found, skipping...")
return data
# Restore data to the new database
def restore_data(data):
with app.app_context():
users = User.restore(data.get('users', []))
_ = Section.restore(data.get('sections', []))
_ = Group.restore(data.get('groups', []), users)
_ = Channel.restore(data.get('channels', []))
_ = Post.restore(data.get('posts', []))
_ = SavedLocations.restore(data.get('locations', []))
print("Data restored to the new database.")
# Define a command to backup data
@custom_cli.command('backup_data')
def backup_data():
data = extract_data()
save_data_to_json(data)
backup_database(app.config['SQLALCHEMY_DATABASE_URI'], app.config['SQLALCHEMY_BACKUP_URI'])
# Define a command to restore data
@custom_cli.command('restore_data')
def restore_data_command():
data = load_data_from_json()
restore_data(data)
# Register the custom command group with the Flask application
app.cli.add_command(custom_cli)
# Startup: ensure the business_submissions table exists and load any previously
# approved community submissions into the in-memory businesses list so they
# survive restarts. Targeted + best-effort so it never blocks app startup.
with app.app_context():
try:
BusinessSubmission.__table__.create(db.engine, checkfirst=True)
except Exception as e:
print(f"business_submissions table init: {e}")
try:
UserMFA.__table__.create(db.engine, checkfirst=True)
except Exception as e:
print(f"user_mfa table init: {e}")
try:
UserPasskey.__table__.create(db.engine, checkfirst=True)
except Exception as e:
print(f"user_passkeys table init: {e}")
try:
UserBackupCode.__table__.create(db.engine, checkfirst=True)
except Exception as e:
print(f"user_backup_codes table init: {e}")
try:
from api.businesses import load_approved_into_memory
load_approved_into_memory()
except Exception as e:
print(f"load_approved_into_memory at startup: {e}")
# this runs the flask application on the development server
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=8888)