decorate with this function in order to require a valid token for any view

     If no token is present you will be sent to a login page
969511
def login_required(func, permission=None):
    
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if not check_token():
            return login()
        elif not nago.core.has_access(session.get('token')):
            return http403()
        return func(*args, **kwargs)
    return decorated_function
1153949
def as_view(cls, **initkwargs):
        
        # sanitize keyword arguments
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (
                                    cls.__name__, key))

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            self.authed_view = initkwargs.get('authed_view')
            self.authed_view_kwargs = initkwargs.get('authed_view_kwargs')
            self.anonymous_view = initkwargs.get('anonymous_view')
            self.anonymous_view_kwargs = initkwargs.get(
                'anonymous_view_kwargs')
            return self.dispatch(request, *args, **kwargs)
        # take name and docstring from class
        update_wrapper(view, cls, updated=())
        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view
762283
def required(self, func):
        
        @wraps(func)
        def decorated(*args, **kwargs):
            """
            Actual wrapper to run the auth checks.
            """
            is_valid, user = self.authenticate()
            if not is_valid:
                return self.auth_failed()
            kwargs['user'] = user
            return func(*args, **kwargs)
        return decorated
448381
def jwt_refresh_token_required(fn):
    
    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_refresh_token_in_request()
        return fn(*args, **kwargs)
    return wrapper
920627
def superuser_required(view_func):
    
    @wraps(view_func)
    def _checklogin(request, *args, **kwargs):
        if request.user.is_active and request.user.is_superuser:
            # The user is valid. Continue to the admin page.
            return view_func(request, *args, **kwargs)

        assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
        defaults = {
            'template_name': 'admin/login.html',
            'redirect_field_name': request.get_full_path(),
            'authentication_form': AdminAuthenticationForm,
            'extra_context': {
                'title': _('Log in'),
                'app_path': request.get_full_path()
                }
            }
        return LoginView(request, **defaults)
    return _checklogin
659709
def terms_required(view_func):
    

    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view(request, *args, **kwargs):
        """Method to wrap the view passed in"""
        # If user has not logged in, or if they have logged in and already agreed to the terms, let the view through
        if DJANGO_VERSION <= (2, 0, 0):
            user_authenticated = request.user.is_authenticated()
        else:
            user_authenticated = request.user.is_authenticated

        if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user):
            return view_func(request, *args, **kwargs)

        # Otherwise, redirect to terms accept
        current_path = request.path
        login_url_parts = list(urlparse(ACCEPT_TERMS_PATH))
        querystring = QueryDict(login_url_parts[4], mutable=True)
        querystring['returnTo'] = current_path
        login_url_parts[4] = querystring.urlencode(safe='/')
        return HttpResponseRedirect(urlunparse(login_url_parts))

    return _wrapped_view
793745
def ajax_login_required(view_func):
    """"""

    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view(request, *args, **kwargs):
        if request.is_ajax():
            if request.user.is_authenticated():
                return view_func(request, *args, **kwargs)
            else:
                response = http.HttpResponse()
                response['X-Django-Requires-Auth'] = True
                response['X-Django-Login-Url'] = settings.LOGIN_URL
                return response
        else:
            return login_required(view_func)(request, *args, **kwargs)
    return _wrapped_view
1365045
def restclient_admin_required(view_func):
    
    def wrapper(request, *args, **kwargs):
        template = 'access_denied.html'
        if hasattr(settings, 'RESTCLIENTS_ADMIN_AUTH_MODULE'):
            auth_func = import_string(settings.RESTCLIENTS_ADMIN_AUTH_MODULE)
        else:
            context = {'error_msg': (
                "Your application must define an authorization function as "
                "RESTCLIENTS_ADMIN_AUTH_MODULE in settings.py.")}
            return render(request, template, context=context, status=401)

        service = args[0] if len(args) > 0 else None
        url = args[1] if len(args) > 1 else None
        if auth_func(request, service, url):
            return view_func(request, *args, **kwargs)

        return render(request, template, status=401)

    return login_required(function=wrapper)
998111
def token_required(scopes='', new=False):
    

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            # if we're coming back from SSO for a new token, return it
            token = _check_callback(request)
            if token and new:
                logger.debug("Got new token from {0} session {1}. Returning to view.".format(request.user, request.session.session_key[:5]))
                return view_func(request, token, *args, **kwargs)

            # if we're selecting a token, return it
            if request.method == 'POST':
                if request.POST.get("_add", False):
                    logger.debug("{0} has selected to add new token. Redirecting to SSO.".format(request.user))
                    # user has selected to add a new token
                    from esi.views import sso_redirect
                    return sso_redirect(request, scopes=scopes)

                token_pk = request.POST.get('_token', None)
                if token_pk:
                    logger.debug("{0} has selected token {1}".format(request.user, token_pk))
                    try:
                        token = Token.objects.get(pk=token_pk)
                        # ensure token belongs to this user and has required scopes
                        if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter(
                                pk=token_pk).require_scopes(scopes).require_valid().exists():
                            logger.debug("Selected token fulfills requirements of view. Returning.")
                            return view_func(request, token, *args, **kwargs)
                    except Token.DoesNotExist:
                        logger.debug("Token {0} not found.".format(token_pk))
                        pass

            if not new:
                # present the user with token choices
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Returning list of available tokens for {0}.".format(request.user))
                    from esi.views import select_token
                    return select_token(request, scopes=scopes, new=new)
                else:
                    logger.debug("No tokens found for {0} session {1} with scopes {2}".format(request.user, request.session.session_key[:5], scopes))

            # prompt the user to add a new token
            logger.debug("Redirecting {0} session {1} to SSO.".format(request.user, request.session.session_key[:5]))
            from esi.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view

    return decorator
536160
def token(self, token):
        
        self._token = token
        if token:
            self.current_user = self.query_login_user()
136717
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME):
    
    if required:
        if django.VERSION < (1, 11):
            actual_decorator = user_passes_test(
                lambda u: u.is_authenticated(),
                redirect_field_name=redirect_field_name
            )
        else:
            actual_decorator = user_passes_test(
                lambda u: u.is_authenticated,
                redirect_field_name=redirect_field_name
            )
        if function:
            return actual_decorator(function)
        return actual_decorator
    # login not required
    def decorator(view_func):
        def _wrapper(request, *args, **kwargs):
            return function(request, *args, **kwargs)
        return wraps(function)(_wrapper)
    return method_decorator(decorator)
15937
def require_admin(func):
    

    @wraps(func)
    @require_login
    def decorated(*args, **kwargs):
        user = current_user()
        if user and user.is_admin:
            return func(*args, **kwargs)
        else:
            return Response(
                'Forbidden', 403
            )

    return decorated
1290434
def token(function):
    """"""
    def wrapped(session, *args):
        """Wrap function."""
        resp = session.get(TOKEN_URL).json()
        session.headers.update({'mopar-csrf-salt': resp['token']})
        return function(session, *args)
    return wrapped
169975
def requires_auth(self, func):
        '''
        
        '''
        @wraps(func)
        def decorated(*args, **kwargs):
            ''' Wrapper '''
            auth = request.authorization
            if not auth or not self.check_auth(auth.username, auth.password):
                return self.authenticate()
            return func(*args, **kwargs)
        return decorated
491418
def page_view(url):
    

    def decorator(func):
        @wraps(func)
        async def wrapper(self: BaseState, *args, **kwargs):
            user_id = self.request.user.id

            try:
                user_lang = await self.request.user.get_locale()
            except NotImplementedError:
                user_lang = ''

            title = self.__class__.__name__

            # noinspection PyTypeChecker
            async for p in providers():
                await p.page_view(url, title, user_id, user_lang)

            return await func(self, *args, **kwargs)
        return wrapper
    return decorator
260113
def as_view(self, view, cacheable=False, extra_permission=None):
        
        def inner(request, *args, **kwargs):
            if not self.has_permission(request, extra_permission):
                # show login pane
                return self.login(request)
            return view(request, *args, **kwargs)

        # Mark it as never_cache
        if not cacheable:
            inner = never_cache(inner)

        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)

        inner = ensure_csrf_cookie(inner)

        return update_wrapper(inner, view)
663483
def require_openid(f):
    """"""
    @wraps(f)
    def decorator(*args, **kwargs):
        if g.user is None:
            next_url = url_for("login") + "?next=" + request.url
            return redirect(next_url)
        else:
            return f(*args, **kwargs)
    return decorator