from flask import request, g, jsonify
from functools import wraps
import accounts


def auth(route_function):
    @wraps(route_function)
    def decorated_function(*args, **kwargs):
        if "Authorization" not in request.headers:
            return jsonify(
                {"success": False, "message": "This resource requires authentication"}
            ), 401
        g.user = accounts.get_user_context(
            request, request.headers["Authorization"].replace("Bearer ", "")
        )
        if g.user is None:
            return jsonify(
                {"success": False, "message": "Invalid authorisation token"}
            ), 401
        return route_function(*args, **kwargs)

    return decorated_function
