from flask import Blueprint, request, jsonify, g from models import db, User from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash user_bp = Blueprint('user', __name__) def authenticate(): username = request.headers.get('X-Username') password = request.headers.get('X-Password') if username and password: user = User.query.filter_by(username=username).first() if user and check_password_hash(user.password, password): g.user = user return True return False @user_bp.before_request def before_request(): if request.endpoint not in ['user.login_user']: if not authenticate(): return jsonify({'message': 'Unauthorized access!'}), 401 @user_bp.route('/users', methods=['POST']) def create_user(): data = request.json hashed_password = generate_password_hash(data['password']) new_user = User( username=data['username'], password=hashed_password, role=data.get('role', 'user'), last_login=None ) db.session.add(new_user) db.session.commit() return jsonify({'message': 'User created!'}), 201 @user_bp.route('/users/login', methods=['POST']) def login_user(): data = request.json user = User.query.filter_by(username=data['username']).first() if user and check_password_hash(user.password, data['password']): user.last_login = datetime.now().strftime('%Y-%m-%d %H:%M:%S') db.session.commit() return jsonify({'message': 'Login successful!', 'role': user.role}), 200 return jsonify({'message': 'Invalid credentials!'}), 401 @user_bp.route('/users', methods=['GET']) def get_users(): users = User.query.all() return jsonify([{ 'id': user.id, 'username': user.username, 'role': user.role, 'last_login': user.last_login } for user in users])