meisaicheck-api / database.py
vumichien's picture
change logic from sentence name to representative name
01ae535
import json
import os
from passlib.context import CryptContext
# Tạo thư mục data nếu chưa tồn tại
os.makedirs("data", exist_ok=True)
USERS_FILE = "data/users.json"
# Context để hash password
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Hàm để đọc users từ file JSON
def get_users():
if not os.path.exists(USERS_FILE):
# Tạo file với dữ liệu mặc định nếu chưa tồn tại
default_users = {
"chien_vm": {
"username": "chien_vm",
"full_name": "Chien VM",
"email": "[email protected]",
"hashed_password": "$2b$12$RtcKFk7B3hKd7vYkwxdFN.eBXSiryQIRUG.OoJ07Pl9lzHNUkugMi",
"disabled": False,
},
"hoi_nv": {
"username": "hoi_nv",
"full_name": "Hoi NV",
"email": "[email protected]",
"hashed_password": "$2b$12$RtcKFk7B3hKd7vYkwxdFN.eBXSiryQIRUG.OoJ07Pl9lzHNUkugMi",
"disabled": False,
},
}
save_users(default_users)
return default_users
with open(USERS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
# Hàm để lưu users vào file JSON
def save_users(users_data):
with open(USERS_FILE, "w", encoding="utf-8") as f:
json.dump(users_data, f, indent=4, ensure_ascii=False)
# Hàm để tạo tài khoản mới
def create_account(username, password):
# Kiểm tra xem username đã tồn tại chưa
users = get_users()
if username in users:
return False, "Username already exists"
# Hash password
hashed_password = pwd_context.hash(password)
# Tạo user mới
new_user = {
"username": username,
"full_name": username, # Mặc định full_name là username
"email": "", # Không yêu cầu email
"hashed_password": hashed_password,
"disabled": False,
}
# Thêm user mới vào database
users[username] = new_user
save_users(users)
return True, "Account created successfully"
# Để tương thích với code cũ
users_db = get_users()