1
- from flask import Blueprint , redirect , url_for , flash , render_template , request , make_response , session , current_app as app
1
+ from flask import Blueprint , redirect , url_for , flash , render_template , request , make_response , session
2
2
from flask_login import LoginManager , UserMixin , login_user , login_required , logout_user , current_user
3
3
from flask_sqlalchemy import SQLAlchemy
4
4
from werkzeug .security import generate_password_hash , check_password_hash
11
11
from .utils import is_user_system_enabled
12
12
import random
13
13
import string
14
- from sqlalchemy import inspect
15
14
16
15
auth_bp = Blueprint ('auth' , __name__ , url_prefix = '/auth' )
17
16
@@ -57,86 +56,11 @@ class User(UserMixin, db.Model):
57
56
role = db .Column (db .String (20 ), nullable = False )
58
57
is_default = db .Column (db .Boolean , default = False )
59
58
onboarding_complete = db .Column (db .Boolean , default = False )
60
- registration_key = db .Column (db .String (120 ), nullable = True )
61
- registration_key_limit = db .Column (db .Integer , nullable = True ) # New column for key usage limit
62
- registration_key_used = db .Column (db .Integer , default = 0 ) # New column for current usage count
63
-
64
- @staticmethod
65
- def get_registration_key ():
66
- admin_user = User .query .filter_by (role = 'admin' ).first ()
67
- if admin_user :
68
- return {
69
- 'key' : admin_user .registration_key ,
70
- 'limit' : admin_user .registration_key_limit ,
71
- 'used' : admin_user .registration_key_used
72
- }
73
- return None
74
-
75
- @staticmethod
76
- def set_registration_key (key , limit = None ):
77
- admin_user = User .query .filter_by (role = 'admin' ).first ()
78
- if admin_user :
79
- admin_user .registration_key = key
80
- if limit is not None :
81
- admin_user .registration_key_limit = limit
82
- admin_user .registration_key_used = 0 # Reset usage count when key/limit changes
83
- db .session .commit ()
84
- return True
85
- return False
86
-
87
- @staticmethod
88
- def increment_key_usage ():
89
- admin_user = User .query .filter_by (role = 'admin' ).first ()
90
- if admin_user :
91
- admin_user .registration_key_used += 1
92
- db .session .commit ()
93
- return True
94
- return False
95
-
96
- def recreate_database ():
97
- """Recreate the database with the new schema."""
98
- # Drop all tables
99
- db .drop_all ()
100
- # Create all tables with new schema
101
- db .create_all ()
102
- # Create default admin if no users exist
103
- create_default_admin ()
104
59
105
60
def init_db (app ):
106
61
db .init_app (app )
107
62
with app .app_context ():
108
- # Create tables if they don't exist
109
63
db .create_all ()
110
-
111
- # Check if the columns exist
112
- inspector = inspect (db .engine )
113
- if 'user' in inspector .get_table_names ():
114
- columns = [col ['name' ] for col in inspector .get_columns ('user' )]
115
-
116
- # Add registration_key column if it doesn't exist
117
- if 'registration_key' not in columns :
118
- with db .engine .connect () as conn :
119
- conn .execute (db .text ('ALTER TABLE user ADD COLUMN registration_key VARCHAR(120)' ))
120
- db .session .commit ()
121
- logging .info ("Added registration_key column to user table" )
122
-
123
- # Add registration_key_limit column if it doesn't exist
124
- if 'registration_key_limit' not in columns :
125
- with db .engine .connect () as conn :
126
- conn .execute (db .text ('ALTER TABLE user ADD COLUMN registration_key_limit INTEGER' ))
127
- db .session .commit ()
128
- logging .info ("Added registration_key_limit column to user table" )
129
-
130
- # Add registration_key_used column if it doesn't exist
131
- if 'registration_key_used' not in columns :
132
- with db .engine .connect () as conn :
133
- conn .execute (db .text ('ALTER TABLE user ADD COLUMN registration_key_used INTEGER DEFAULT 0' ))
134
- db .session .commit ()
135
- logging .info ("Added registration_key_used column to user table" )
136
-
137
- # Create default admin if no users exist
138
- if User .query .count () == 0 :
139
- create_default_admin ()
140
64
141
65
@login_manager .user_loader
142
66
def load_user (user_id ):
@@ -166,16 +90,15 @@ def login():
166
90
password = request .form .get ('password' )
167
91
remember = bool (request .form .get ('remember_me' ))
168
92
93
+
169
94
user = User .query .filter_by (username = username ).first ()
170
95
if user :
96
+
171
97
if check_password_hash (user .password , password ):
172
- # Set session as permanent if remember me is checked
173
- if remember :
174
- session .permanent = True # This will use the PERMANENT_SESSION_LIFETIME value
175
- else :
176
- session .permanent = False # Session will expire when browser closes
177
98
178
- # Login the user with the remember flag
99
+ # Always set session as permanent
100
+ session .permanent = True
101
+
179
102
login_user (user , remember = remember )
180
103
181
104
# Force session save
@@ -219,86 +142,4 @@ def logout():
219
142
@auth_bp .route ('/unauthorized' )
220
143
def unauthorized ():
221
144
flash ('You are not authorized to access this page.' , 'error' )
222
- return redirect (url_for ('auth.login' ))
223
-
224
- @auth_bp .route ('/register' , methods = ['GET' , 'POST' ])
225
- def register ():
226
- if not is_user_system_enabled ():
227
- return redirect (url_for ('root.root' ))
228
-
229
- if current_user .is_authenticated :
230
- return redirect (url_for ('root.root' ))
231
-
232
- if request .method == 'POST' :
233
- username = request .form ['username' ]
234
- password = request .form ['password' ]
235
- registration_key = request .form ['registration_key' ]
236
-
237
- # Validate registration key
238
- key_info = User .get_registration_key ()
239
- if not key_info or registration_key != key_info ['key' ]:
240
- flash ('Invalid registration key.' , 'error' )
241
- return redirect (url_for ('auth.login' ))
242
-
243
- # Check key usage limit
244
- if key_info ['limit' ] is not None and key_info ['used' ] >= key_info ['limit' ]:
245
- flash ('Registration key has reached its usage limit.' , 'error' )
246
- return redirect (url_for ('auth.login' ))
247
-
248
- existing_user = User .query .filter_by (username = username ).first ()
249
- if existing_user :
250
- flash ('Username already exists.' , 'error' )
251
- return redirect (url_for ('auth.login' ))
252
-
253
- hashed_password = generate_password_hash (password )
254
- new_user = User (
255
- username = username ,
256
- password = hashed_password ,
257
- role = 'user' , # New users are always regular users
258
- onboarding_complete = True
259
- )
260
- db .session .add (new_user )
261
-
262
- # Increment key usage count
263
- User .increment_key_usage ()
264
-
265
- db .session .commit ()
266
- login_user (new_user )
267
- flash ('Registered successfully.' , 'success' )
268
- return redirect (url_for ('root.root' ))
269
- return redirect (url_for ('auth.login' ))
270
-
271
- @auth_bp .route ('/account' )
272
- @login_required
273
- def account ():
274
- if current_user .role == 'admin' :
275
- return redirect (url_for ('root.root' ))
276
- return render_template ('account.html' )
277
-
278
- @auth_bp .route ('/change_password' , methods = ['POST' ])
279
- @login_required
280
- def change_password ():
281
- if current_user .role == 'admin' :
282
- return redirect (url_for ('root.root' ))
283
-
284
- current_password = request .form .get ('current_password' )
285
- new_password = request .form .get ('new_password' )
286
- confirm_password = request .form .get ('confirm_password' )
287
-
288
- # Verify current password
289
- if not check_password_hash (current_user .password , current_password ):
290
- flash ('Current password is incorrect.' , 'error' )
291
- return redirect (url_for ('auth.account' ))
292
-
293
- # Verify new password match
294
- if new_password != confirm_password :
295
- flash ('New passwords do not match.' , 'error' )
296
- return redirect (url_for ('auth.account' ))
297
-
298
- # Update password
299
- current_user .password = generate_password_hash (new_password )
300
- current_user .is_default = False
301
- db .session .commit ()
302
-
303
- flash ('Password changed successfully.' , 'success' )
304
- return redirect (url_for ('auth.account' ))
145
+ return redirect (url_for ('auth.login' ))
0 commit comments