Decorator for views that checks that the user is logged in, redirecting
    to the log in page if necessary.
549743
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if is_authenticated(request.user):
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator
698760
def get_view_response(self, request, page, view_func, view_args, view_kwargs):
        
        return view_func(request, page, *view_args, **view_kwargs)
473765
def logged_in(f):
    

    @wraps(f)
    def wrapped_method(self, *args, **kwargs):
        if not self.reddit.is_oauth_session():
            self.term.show_notification('Not logged in')
            return None
        return f(self, *args, **kwargs)
    return wrapped_method
1177035
def process_view(self, request, view_func, view_args, view_kwargs):
        

        if view_func == login:
            return cas_login(request, *view_args, **view_kwargs)
        elif view_func == logout:
            return cas_logout(request, *view_args, **view_kwargs)

        if settings.CAS_ADMIN_PREFIX:
            if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
                return None
        elif not view_func.__module__.startswith('django.contrib.admin.'):
            return None

        try:
            # use callable for pre-django 2.0
            is_authenticated = request.user.is_authenticated()
        except TypeError:
            is_authenticated = request.user.is_authenticated

        if is_authenticated:
            if request.user.is_staff:
                return None
            else:
                error = ('<h1>Forbidden</h1><p>You do not have staff '
                         'privileges.</p>')
                return HttpResponseForbidden(error)

        params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
        return HttpResponseRedirect(reverse(cas_login) + '?' + params)
338383
def _check_logged_user(self):
        """"""
        if not self._env or not self._password or not self._login:
            raise error.InternalError("Login required")
168333
def login(request, next_page=None, required=False, gateway=False):
    

    if not next_page:
        next_page = _redirect_url(request)

    try:
        # use callable for pre-django 2.0
        is_authenticated = request.user.is_authenticated()
    except TypeError:
        is_authenticated = request.user.is_authenticated

    if is_authenticated:
        return HttpResponseRedirect(next_page)

    ticket = request.GET.get('ticket')

    if gateway:
        service = _service_url(request, next_page, True)
    else:
        service = _service_url(request, next_page, False)

    if ticket:
        user = auth.authenticate(ticket=ticket, service=service)

        if user is not None:

            auth.login(request, user)

            if settings.CAS_PROXY_CALLBACK:
                proxy_callback(request)

            return HttpResponseRedirect(next_page)
        elif settings.CAS_RETRY_LOGIN or required:
            if gateway:
                return HttpResponseRedirect(_login_url(service, ticket, True))
            else:
                return HttpResponseRedirect(_login_url(service, ticket, False))
        else:
            logger.warning('User has a valid ticket but not a valid session')
            # Has ticket, not session

            if gateway:
                # Gatewayed responses should nto redirect.
                return False

            if getattr(settings, 'CAS_CUSTOM_FORBIDDEN'):
                return HttpResponseRedirect(reverse(settings.CAS_CUSTOM_FORBIDDEN) + "?" + request.META['QUERY_STRING'])
            else:
                error = "<h1>Forbidden</h1><p>Login failed.</p>"
                return HttpResponseForbidden(error)
    else:
        if gateway:
            return HttpResponseRedirect(_login_url(service, ticket, True))
        else:
            return HttpResponseRedirect(_login_url(service, ticket, False))
76076
def oauth2callback(self, view_func):
        

        @wraps(view_func)
        def decorated(*args, **kwargs):
            params = {}

            # Check sig
            if 'state' in request.args:
                params.update(**self.parse_state(request.args.get('state')))
                if params.pop('sig', None) != make_secure_token(**params):
                    return self.login_manager.unauthorized()

            code = request.args.get('code')

            # Web server flow
            if code:
                token = self.exchange_code(
                    code,
                    url_for(
                        request.endpoint,
                        _external=True,
                        _scheme=self.redirect_scheme,
                    ),
                )
                userinfo = self.get_userinfo(token['access_token'])
                params.update(token=token, userinfo=userinfo)

            # Browser flow
            else:
                if params:
                    params.update(dict(request.args.items()))
                else:
                    return '''
                    <script>
                      window.onload = function() {
                        location.href = '?' + window.location.hash.substr(1);
                      };
                    </script>
                    '''

            return view_func(**params)

        return decorated
76678
def login_required(request):
    ""
    user = getattr(request, 'user', None)
    if user is None or not user.is_authenticated:
        return HttpResponse(status=401)
875394
def login_required(f):
    '''
    
    '''
    def _wrapper(self, *args, **kwargs):
        '''
        Function to be applied on top of all decorated methods
        '''
        if self._token_age:
            timediff = self._token_age - datetime.datetime.now()
            if timediff.total_seconds() / 60 > TOKEN_TIMEOUT:
                self.logout()  # Log out to invalidate previous token
                self.login()  # Request new token
        else:  # haven't logged in yet
            self.login()
        return f(self, *args, **kwargs)
    return _wrapper
384029
def auth_required(*auth_methods):
    
    login_mechanisms = {
        'token': lambda: _check_token(),
        'basic': lambda: _check_http_auth(),
        'session': lambda: current_user.is_authenticated
    }

    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            h = {}
            mechanisms = [(method, login_mechanisms.get(method))
                          for method in auth_methods]
            for method, mechanism in mechanisms:
                if mechanism and mechanism():
                    return fn(*args, **kwargs)
                elif method == 'basic':
                    r = _security.default_http_auth_realm
                    h['WWW-Authenticate'] = 'Basic realm="%s"' % r
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                return _get_unauthorized_response(headers=h)
        return decorated_view
    return wrapper
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
1069404
def anonymous_required(function=None, redirect_url=None):
    
    if not redirect_url:
        redirect_url = settings.LOGIN_REDIRECT_URL

    actual_decorator = user_passes_test(
        is_anonymous,
        login_url=redirect_url,
        redirect_field_name=None
    )

    if function:
        return actual_decorator(function)
    return actual_decorator
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
269469
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper
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
1207209
def _requires_login(func: Callable) -> Callable:
    """"""
    @wraps(func)
    def call(instaloader, *args, **kwargs):
        if not instaloader.context.is_logged_in:
            raise LoginRequiredException("--login=USERNAME required.")
        return func(instaloader, *args, **kwargs)
    # pylint:disable=no-member
    call.__doc__ += ":raises LoginRequiredException: If called without being logged in.\n"
    return call
1131611
def anonymous_required(func=None, url=None):
    """"""

    url = url or "/"

    def _dec(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated():
                return redirect(url)
            else:
                return view_func(request, *args, **kwargs)
        return _wrapped_view

    if func is None:
        return _dec
    else:
        return _dec(func)