2024-09-02 10:40:44 +02:00
|
|
|
from flask import Blueprint, request, jsonify, g
|
2024-09-02 11:42:20 +02:00
|
|
|
from models import db, User, Game
|
2024-09-02 10:51:50 +02:00
|
|
|
from datetime import datetime, timedelta
|
|
|
|
import jwt
|
2024-09-02 10:43:07 +02:00
|
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
2024-09-02 10:51:50 +02:00
|
|
|
import os
|
2024-09-02 10:32:26 +02:00
|
|
|
|
|
|
|
user_bp = Blueprint('user', __name__)
|
2024-09-02 10:51:50 +02:00
|
|
|
SECRET_KEY = os.environ.get('SECRET_KEY', 'your_secret_key') # Set a secret key for JWT
|
|
|
|
|
|
|
|
def generate_token(user):
|
|
|
|
payload = {
|
|
|
|
'user_id': user.id,
|
|
|
|
'exp': datetime.utcnow() + timedelta(days=1) # Token expires in 1 day
|
|
|
|
}
|
|
|
|
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
|
2024-09-02 10:32:26 +02:00
|
|
|
|
2024-09-02 10:40:44 +02:00
|
|
|
def authenticate():
|
2024-09-02 10:51:50 +02:00
|
|
|
token = request.headers.get('Authorization')
|
|
|
|
if token:
|
|
|
|
try:
|
|
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
|
|
|
|
g.user = User.query.get(payload['user_id'])
|
2024-09-02 10:40:44 +02:00
|
|
|
return True
|
2024-09-02 10:51:50 +02:00
|
|
|
except jwt.ExpiredSignatureError:
|
|
|
|
return False
|
|
|
|
except jwt.InvalidTokenError:
|
|
|
|
return False
|
2024-09-02 10:40:44 +02:00
|
|
|
return False
|
|
|
|
|
|
|
|
@user_bp.before_request
|
|
|
|
def before_request():
|
2024-09-02 10:51:50 +02:00
|
|
|
if request.endpoint not in ['user.login_user', 'user.create_user']:
|
2024-09-02 10:40:44 +02:00
|
|
|
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():
|
2024-09-02 11:09:26 +02:00
|
|
|
if not authenticate() or g.user.role != 'admin':
|
|
|
|
return jsonify({'message': 'Unauthorized access! Only admins can create users.'}), 401
|
2024-09-02 10:32:26 +02:00
|
|
|
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()
|
2024-09-02 10:51:50 +02:00
|
|
|
token = generate_token(user)
|
|
|
|
return jsonify({'message': 'Login successful!', 'token': token, 'role': user.role}), 200
|
2024-09-02 10:32:26 +02:00
|
|
|
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])
|
2024-09-02 11:12:18 +02:00
|
|
|
|
|
|
|
@user_bp.route('/users/<int:user_id>', methods=['PUT'])
|
|
|
|
def edit_user(user_id):
|
|
|
|
if not authenticate() or g.user.role != 'admin':
|
|
|
|
return jsonify({'message': 'Unauthorized access! Only admins can edit users.'}), 401
|
|
|
|
data = request.json
|
|
|
|
user = User.query.get(user_id)
|
|
|
|
if not user:
|
|
|
|
return jsonify({'message': 'User not found!'}), 404
|
|
|
|
user.username = data.get('username', user.username)
|
|
|
|
user.role = data.get('role', user.role)
|
2024-09-02 11:14:15 +02:00
|
|
|
|
|
|
|
# Update password if provided
|
|
|
|
if 'password' in data:
|
|
|
|
user.password = generate_password_hash(data['password'])
|
|
|
|
|
2024-09-02 11:12:18 +02:00
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'User updated!'}), 200
|
|
|
|
|
|
|
|
@user_bp.route('/users/<int:user_id>', methods=['DELETE'])
|
|
|
|
def delete_user(user_id):
|
|
|
|
if not authenticate() or g.user.role != 'admin':
|
|
|
|
return jsonify({'message': 'Unauthorized access! Only admins can delete users.'}), 401
|
|
|
|
user = User.query.get(user_id)
|
|
|
|
if not user:
|
|
|
|
return jsonify({'message': 'User not found!'}), 404
|
|
|
|
db.session.delete(user)
|
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'User deleted!'}), 200
|
2024-09-02 11:42:20 +02:00
|
|
|
|
|
|
|
@user_bp.route('/games/<int:game_id>', methods=['PUT'])
|
|
|
|
def edit_game(game_id):
|
|
|
|
if not authenticate():
|
|
|
|
return jsonify({'message': 'Unauthorized access!'}), 401
|
|
|
|
data = request.json
|
|
|
|
game = Game.query.get(game_id)
|
|
|
|
if not game:
|
|
|
|
return jsonify({'message': 'Game not found!'}), 404
|
|
|
|
game.title = data.get('title', game.title)
|
|
|
|
game.image = data.get('image', game.image)
|
2024-09-02 11:43:41 +02:00
|
|
|
game.owned = data.get('owned', game.owned) # Update owned status if provided
|
2024-09-02 11:42:20 +02:00
|
|
|
|
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'Game updated!'}), 200
|
2024-09-02 11:42:55 +02:00
|
|
|
|
|
|
|
@user_bp.route('/games/<int:game_id>', methods=['DELETE'])
|
|
|
|
def delete_game(game_id):
|
|
|
|
if not authenticate() or g.user.role != 'admin':
|
|
|
|
return jsonify({'message': 'Unauthorized access! Only admins can delete games.'}), 401
|
|
|
|
game = Game.query.get(game_id)
|
|
|
|
if not game:
|
|
|
|
return jsonify({'message': 'Game not found!'}), 404
|
|
|
|
db.session.delete(game)
|
|
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'Game deleted!'}), 200
|