Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
4.0 kB
0
Indexable
Never
from flask import Flask, request, jsonify
import uuid
import datetime
import jwt
from functools import wraps

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

# Mock database to store product details
products = []

# Mock user database for authentication
users = [
    {"id": 1, "username": "user1", "password": "password1"},
    {"id": 2, "username": "user2", "password": "password2"}
]

# JWT token generation function
def generate_token(user_id):
    token_payload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
    }
    token = jwt.encode(token_payload, app.config['SECRET_KEY'], algorithm='HS256')
    return token.decode('utf-8')

# Authentication decorator
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')

        if not token:
            return jsonify({'message': 'Token is missing!'}), 401

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
            current_user = next((user for user in users if user["id"] == data["user_id"]), None)
        except:
            return jsonify({'message': 'Token is invalid!'}), 401

        return f(current_user, *args, **kwargs)

    return decorated

# User signup API
@app.route('/signup', methods=['POST'])
def signup():
    data = request.get_json()

    # Mock implementation for simplicity
    user = {"id": len(users) + 1, "username": data['username'], "password": data['password']}
    users.append(user)

    return jsonify({'message': 'User created successfully!'})

# User login API
@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    user = next((user for user in users if user['username'] == username and user['password'] == password), None)

    if user:
        access_token = generate_token(user['id'])
        return jsonify({'access_token': access_token})
    else:
        return jsonify({'message': 'Invalid credentials!'}), 401

# Product CRUD operations
@app.route('/products', methods=['POST'])
@token_required
def create_product(current_user):
    data = request.get_json()
    product = {
        'id': str(uuid.uuid4()),
        'name': data['name'],
        'price': data['price'],
        'product_image': str(uuid.uuid4()),  # Use this UUID as a placeholder for the image file
        'created_on': datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
    }
    products.append(product)
    return jsonify({'message': 'Product created successfully!', 'product': product})

@app.route('/products/<product_id>', methods=['PUT'])
@token_required
def update_product(current_user, product_id):
    product = next((product for product in products if product['id'] == product_id), None)
    if product:
        data = request.get_json()
        product.update(data)
        return jsonify({'message': 'Product updated successfully!', 'product': product})
    else:
        return jsonify({'message': 'Product not found!'}), 404

@app.route('/products/<product_id>', methods=['DELETE'])
@token_required
def delete_product(current_user, product_id):
    global products
    products = [product for product in products if product['id'] != product_id]
    return jsonify({'message': 'Product deleted successfully!'})

@app.route('/products', methods=['GET'])
@token_required
def get_products(current_user):
    # Pagination
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    start = (page - 1) * per_page
    end = start + per_page

    # Filter and search by name
    name_filter = request.args.get('name')
    filtered_products = [product for product in products if name_filter.lower() in product['name'].lower()] if name_filter else products

    return jsonify({'products': filtered_products[start:end]})

if __name__ == '__main__':
    app.run(debug=True)
Leave a Comment