import logging


def token_required(token):
    """
    Verifies token sent in request in `X-Auth-Token` header.
    If token is correct decorated method is executed. Otherwise request raises 401 HTTP error.

    :param (str) token: Secret token used to authorization.
    """

    def wrap(func):

        def func_wrapper(self, *args, **kwargs):
            auth_token = self.request.headers.get('X-Auth-Token') or self.request.get('token')

            if auth_token != token:
                logging.error('401: {}'.format(auth_token))
                return self.abort(401, 'Unauthorized')

            return func(self, *args, **kwargs)

        return func_wrapper

    return wrap