This decorator should be used with views that need simple authentication
    against Django's authentication framework.
174046
def credentials_required(view_func):
    
    @wraps(view_func, assigned=available_attrs(view_func))
    def decorator(request, *args, **kwargs):
        if settings.LOCALSHOP_USE_PROXIED_IP:
            try:
                ip_addr = request.META['HTTP_X_FORWARDED_FOR']
            except KeyError:
                return HttpResponseForbidden('No permission')
            else:
                # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
                # The client's IP will be the first one.
                ip_addr = ip_addr.split(",")[0].strip()
        else:
            ip_addr = request.META['REMOTE_ADDR']

        if CIDR.objects.has_access(ip_addr, with_credentials=False):
            return view_func(request, *args, **kwargs)

        if not CIDR.objects.has_access(ip_addr, with_credentials=True):
            return HttpResponseForbidden('No permission')

        # Just return the original view because already logged in
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)

        user = authenticate_user(request)
        if user is not None:
            login(request, user)
            return view_func(request, *args, **kwargs)

        return HttpResponseUnauthorized(content='Authorization Required')
    return decorator
691578
def login_required(view_func):
    
    @wraps(view_func)
    def wrapper(bot, update, **kwargs):
        chat = Chat.objects.get(id=update.message.chat.id)
        if chat.is_authenticated():
            return view_func(bot, update, **kwargs)
        from telegrambot.bot_views.login import LoginBotView
        login_command_view = LoginBotView.as_command_view()
        bot_model = Bot.objects.get(token=bot.token)
        kwargs['link'] = reverse('telegrambot:auth', kwargs={'bot': bot_model.user_api.username}) 
        return login_command_view(bot, update, **kwargs)
    return wrapper
1160210
def authenticated(function):
    """"""
    def wrapped(session, *args, **kwargs):
        """Wrap function."""
        try:
            return function(session, *args, **kwargs)
        except VooblyError:
            with session.cache_disabled():
                _LOGGER.info("attempted to access page before login")
                login(session)
                return function(session, *args, **kwargs)
    return wrapped
756430
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs):
    
    def decorator(f):
        if url is not None:
            f = expose(url, methods=methods)(f)

        clsdict = {"name": name or f.__name__,
                   "actions": getattr(f, "actions", None),
                   "url_rules": url_rules or getattr(f, "urls", None)}

        if isinstance(f, WithActionsDecorator):
            f = f.func
        clsdict['func'] = f

        def constructor(self, **ctorkwargs):
            for k, v in kwargs.items():
                if k not in ctorkwargs or ctorkwargs[k] is None:
                    ctorkwargs[k] = v
            view_class.__init__(self, func=f, **ctorkwargs)

        clsdict["__init__"] = constructor
        return type(f.__name__, (view_class,), clsdict)

    return decorator
209368
def require_user(self, *users, user=None):
        """"""

        # accept old-style single user keyword-argument as well
        if user:
            users = (*users, user)

        def _require_auth(view_func):
            @wraps(view_func)
            def wrapper(*args, **kwargs):
                """ Effective wrapper """
                username, out_token = self.authenticate()
                if username and out_token:
                    b64_token = base64.b64encode(out_token).decode('utf-8')
                    auth_data = 'Negotiate {0}'.format(b64_token)
                    if not users or username in users:
                        response = make_response(view_func(*args,
                                                           username=username,
                                                           **kwargs))
                    else:
                        response = Response(status=403)
                    response.headers['WWW-Authenticate'] = auth_data
                    return response
                return Response(
                    status=401,
                    headers={'WWW-Authenticate': 'Negotiate'},
                )

            return wrapper
        return _require_auth
963113
def requires_basic_auth(f):
    """"""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated
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)
523229
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator
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
962613
def require_api_auth(allow_anonymous=False):
    
    def wrapper(f):
        """Wrap function with oauth require decorator."""
        f_oauth_required = oauth2.require_oauth()(f)

        @wraps(f)
        def decorated(*args, **kwargs):
            """Require OAuth 2.0 Authentication."""
            if not hasattr(current_user, 'login_via_oauth2'):
                if not current_user.is_authenticated:
                    if allow_anonymous:
                        return f(*args, **kwargs)
                    abort(401)
                if current_app.config['ACCOUNTS_JWT_ENABLE']:
                    # Verify the token
                    current_oauth2server.jwt_veryfication_factory(
                        request.headers)
                # fully logged in with normal session
                return f(*args, **kwargs)
            else:
                # otherwise, try oauth2
                return f_oauth_required(*args, **kwargs)
        return decorated
    return wrapper
107309
def should_require_authentication(self, url):
        
        return (not self.routes # require auth for all URLs
                or any(route.match(url) for route in self.routes))
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
1217129
def api_auth(func):
    
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        authentication = APIAuthentication(request)
        if authentication.authenticate():
            return func(request, *args, **kwargs)
        raise Http404
    return _decorator
512127
def auth_required(self, view_func):
        
        @wraps(view_func)
        def wrapped_view_func(*args, **kwargs):
            if current_app.config['HAWK_ENABLED']:
                if current_app.config['HAWK_ALLOW_COOKIE_AUTH'] and session:
                    self._auth_by_cookie()
                else:
                    self._auth_by_signature()
            return view_func(*args, **kwargs)

        return wrapped_view_func
889478
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except UPSError:
            _login(*args)
            return function(*args)
    return wrapped
502295
def tokens_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:
                tokens = Token.objects.filter(pk=token.pk)
                logger.debug("Returning new token.")
                return view_func(request, tokens, *args, **kwargs)

            if not new:
                # ensure user logged in to check existing tokens
                if not request.user.is_authenticated:
                    logger.debug(
                        "Session {0} is not logged in. Redirecting to login.".format(request.session.session_key[:5]))
                    from django.contrib.auth.views import redirect_to_login
                    return redirect_to_login(request.get_full_path())

                # collect tokens in db, check if still valid, return if any
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Retrieved {0} tokens for {1} session {2}".format(tokens.count(), request.user,
                                                                                   request.session.session_key[:5]))
                    return view_func(request, tokens, *args, **kwargs)

            # trigger creation of new token via sso
            logger.debug("No tokens identified for {0} session {1}. Redirecting 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
987097
def login_not_required(func):
    

    @functools.wraps(func)
    def decorated_view(*args, **kwargs):
        return func(*args, **kwargs)

    return decorated_view