2024-09-02 10:40:44 +02:00
|
|
|
from flask import Blueprint, request, jsonify, g
|
2024-09-02 10:32:26 +02:00
|
|
|
from models import db, User
|
|
|
|
from datetime import datetime
|
2024-09-02 10:43:07 +02:00
|
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
2024-09-02 10:32:26 +02:00
|
|
|
|
|
|
|
user_bp = Blueprint('user', __name__)
|
|
|
|
|
2024-09-02 10:40:44 +02:00
|
|
|
def authenticate():
|
|
|
|
username = request.headers.get('X-Username')
|
|
|
|
password = request.headers.get('X-Password')
|
|
|
|
if username and password:
|
2024-09-02 10:43:07 +02:00
|
|
|
user = User.query.filter_by(username=username).first()
|
|
|
|
if user and check_password_hash(user.password, password):
|
2024-09-02 10:40:44 +02:00
|
|
|
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
|
|
|
|
|
2024-09-02 10:32:26 +02:00
|
|
|
@user_bp.route('/users', methods=['POST'])
|
|
|
|
def create_user():
|
|
|
|
data = request.json
|
2024-09-02 10:43:07 +02:00
|
|
|
hashed_password = generate_password_hash(data['password'])
|
2024-09-02 10:32:26 +02:00
|
|
|
new_user = User(
|
|
|
|
username=data['username'],
|
2024-09-02 10:43:07 +02:00
|
|
|
password=hashed_password,
|
|
|
|
role=data.get('role', 'user'),
|
2024-09-02 10:32:26 +02:00
|
|
|
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
|
2024-09-02 10:43:07 +02:00
|
|
|
user = User.query.filter_by(username=data['username']).first()
|
|
|
|
if user and check_password_hash(user.password, data['password']):
|
2024-09-02 10:32:26 +02:00
|
|
|
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])
|