from functools import wraps
from flask import g, request
from utils.jwt import decode_jwt
from db.user import User
from flask import jsonify


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        auth = request.headers.get('Authorization')
        token = auth.split(' ')[1]
        try:
            payload = decode_jwt(token)
            user = User.find_by_id(payload['user_id'])
            if user is None:
                return jsonify({"Error": "Not authorized"}), 401
            g.user = user
        except:
            return jsonify({"Error": "Not authorized"}), 401
        return f(*args, **kwargs)
    return decorated_function
