MikaList/game_collection/user_management.py

39 lines
1.2 KiB
Python
Raw Normal View History

from flask import Blueprint, request, jsonify
from models import db, User
from datetime import datetime
user_bp = Blueprint('user', __name__)
@user_bp.route('/users', methods=['POST'])
def create_user():
data = request.json
new_user = User(
username=data['username'],
password=data['password'],
role=data.get('role', 'user'), # Default role is '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'], password=data['password']).first()
if user:
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])