85 lines
2.4 KiB
Python
85 lines
2.4 KiB
Python
import json
|
|
import bcrypt
|
|
from flask_login import UserMixin
|
|
import os
|
|
|
|
class User(UserMixin):
|
|
def __init__(self, username):
|
|
self.id = username
|
|
self.username = username
|
|
|
|
@staticmethod
|
|
def get(user_id):
|
|
users = load_users()
|
|
if user_id in users:
|
|
return User(user_id)
|
|
return None
|
|
|
|
def init_auth_file():
|
|
"""Initialize auth.json if it doesn't exist"""
|
|
if not os.path.exists('auth.json'):
|
|
with open('auth.json', 'w') as f:
|
|
json.dump({}, f)
|
|
|
|
def load_users():
|
|
"""Load users from auth.json"""
|
|
init_auth_file()
|
|
with open('auth.json', 'r') as f:
|
|
return json.load(f)
|
|
|
|
def save_users(users):
|
|
"""Save users to auth.json"""
|
|
with open('auth.json', 'w') as f:
|
|
json.dump(users, f, indent=2)
|
|
|
|
def hash_password(password):
|
|
"""Hash a password using bcrypt"""
|
|
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
|
|
|
def verify_password(stored_password_hash, provided_password):
|
|
"""Verify a password against its hash"""
|
|
return bcrypt.checkpw(
|
|
provided_password.encode('utf-8'),
|
|
stored_password_hash.encode('utf-8')
|
|
)
|
|
|
|
def create_user(username, password):
|
|
"""Create a new user with hashed password"""
|
|
users = load_users()
|
|
if username not in users:
|
|
users[username] = {
|
|
'password_hash': hash_password(password)
|
|
}
|
|
save_users(users)
|
|
return True
|
|
return False
|
|
|
|
def verify_user(username, password):
|
|
"""Verify user credentials"""
|
|
users = load_users()
|
|
if username in users:
|
|
stored_hash = users[username]['password_hash']
|
|
return verify_password(stored_hash, password)
|
|
return False
|
|
|
|
def change_password(username, current_password, new_password):
|
|
"""Change user password if current password is correct"""
|
|
if verify_user(username, current_password):
|
|
users = load_users()
|
|
users[username]['password_hash'] = hash_password(new_password)
|
|
save_users(users)
|
|
return True
|
|
return False
|
|
|
|
# Initialize default users with secure passwords
|
|
def init_default_users():
|
|
"""Initialize default users if they don't exist"""
|
|
init_auth_file()
|
|
users = load_users()
|
|
|
|
default_users = ['chaulmark', 'ekragh']
|
|
default_password = 'changeme123' # Temporary password that users should change
|
|
|
|
for username in default_users:
|
|
if username not in users:
|
|
create_user(username, default_password)
|