Python django.contrib.auth.decorators.login_required() Examples

The following are 30 code examples of django.contrib.auth.decorators.login_required(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth.decorators , or try the search function .
Example #1
Source File: views.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
def project_admin_login_post_required(f):
    # Wrap the function to do authorization and change arguments.
    def g(request, project_id, *args):
        # Get project, check authorization.
        project = get_object_or_404(Project, id=project_id)
        has_owner_project_portfolio_permissions = request.user.has_perm('can_grant_portfolio_owner_permission', project.portfolio)
        if request.user not in project.get_admins() and not has_owner_project_portfolio_permissions:
            return HttpResponseForbidden()

        # Call function with changed argument.
        return f(request, project)

    # Apply the require_http_methods decorator.
    g = require_http_methods(["POST"])(g)

    # Apply the login_required decorator.
    g = login_required(g)

    return g 
Example #2
Source File: decorators.py    From tethys with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for Tethys App controllers that checks whether a user has a permission.
    """
    def decorator(controller_func):
        def wrapper(request, *args, **kwargs):

            if not getattr(settings, 'ENABLE_OPEN_PORTAL', False):
                from django.contrib.auth.decorators import login_required as lr
                dec = lr(function=function, redirect_field_name=redirect_field_name, login_url=login_url)
                controller = dec(controller_func)
                return controller(request, *args, **kwargs)
            else:
                return controller_func(request, *args, **kwargs)

        return wraps(controller_func)(wrapper)
    return decorator 
Example #3
Source File: views.py    From foialawya with Apache License 2.0 6 votes vote down vote up
def prepare_user(sender, instance, **kwargs):
    if instance._state.adding is True:

        ## Don't add users not from the nytimes.com email domain.
        ## or a few whitelisted emails for testing.

        if settings.USE_ALLAUTH:
            if instance.email and settings.ALLOWABLE_LOGIN_DOMAIN and not instance.email.split('@')[1] == settings.ALLOWABLE_LOGIN_DOMAIN:
                raise Http404('Please login with your {} email address.'.format(ALLOWABLE_LOGIN_DOMAIN))

        instance.is_staff = True
        instance.is_superuser = True

# you may want to have the front-page of the site (listing all the foias)
# require you to log in to see it.
# if so, just uncomment this.
# @login_required() 
Example #4
Source File: views.py    From website with MIT License 6 votes vote down vote up
def Article_detail(request,article_id):
    """
    文章详情页
    :param request:
    :param article_id:
    :return:
    """
    try:
        article=Article.objects.get(id=article_id)
        id = article.category.id
        article.click_nums+=1
        article.save()
    except Exception:
        return Http404

    content = Article.objects.filter(category_id=id).exclude(id=article_id).order_by('-click_nums')[:10]
    #print(content.annotate())
    return render(request,'pc/article_detail.html',{'article':article,'id':article_id,'content':content})


# 写博客上传图片
# @login_required(login_url='/login') 
Example #5
Source File: views.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
def portfolio_read_required(f):
    @login_required
    def g(request, pk):
        portfolio = get_object_or_404(Portfolio, pk=pk)

        # Check authorization.
        has_portfolio_permissions = request.user.has_perm('view_portfolio', portfolio)
        has_portfolio_project_permissions = False
        projects = Project.objects.filter(portfolio_id=portfolio.id)
        for project in projects:
            if request.user.has_perm('view_project', project):
                has_portfolio_project_permissions = True

        if not (has_portfolio_permissions or has_portfolio_project_permissions):
            return HttpResponseForbidden()
        return f(request, portfolio.id)
    return g 
Example #6
Source File: views.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
def project_read_required(f):
    @login_required
    def g(request, project_id, project_url_suffix):
        project = get_object_or_404(Project, id=project_id)

        # Check authorization.
        has_project_portfolio_permissions = request.user.has_perm('view_portfolio', project.portfolio)
        if not project.has_read_priv(request.user) and not has_project_portfolio_permissions:
            return HttpResponseForbidden()

        # Redirect if slug is not canonical. We do this after checking for
        # read privs so that we don't reveal the task's slug to unpriv'd users.
        if request.path != project.get_absolute_url()+project_url_suffix:
            return HttpResponseRedirect(project.get_absolute_url())

        return f(request, project)
    return g 
Example #7
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def rules(request):
    
    mimetype = 'application/json'
    data = {}
    
    return HttpResponse(json.dumps(data), mimetype)
    

#@permission_required('is_staff', login_url=reverse_lazy('login'))
#@login_required(login_url=reverse_lazy('login')) 
Example #8
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def check_config(request):        
        
    mimetype = 'application/json'   
    data = {}
    
    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':        
        client_name, check_name = request.POST['entity'].split(':')
        #check_name = 'check_gw_tomcat_errors_1h'
        #data = cache.get('check_' + check_name)
        data = cache.get('check_' + request.POST['entity'])
    
    
    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login')) 
Example #9
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def entity_notify_history(request):            
        
    data = []
    mimetype = 'application/json'   
    
    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
        
        entity = request.POST['entity']
        logger.debug("view entity_notify_history user: %s entity: %s" % (request.user.username, entity))
    
        for history_data in r.lrange('notifyhistory_entity_' + entity, 0, 100):
            data.append(pickle.loads(history_data))
    
    return HttpResponse(json.dumps(data), mimetype)




#@login_required(login_url=reverse_lazy('login')) 
Example #10
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def entity_history(request):            
        
    data = []
    mimetype = 'application/json'   
    
    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
        
        entity = request.POST['entity']
        logger.debug("view entity_history user: %s entity: %s" % (request.user.username, entity))
    
        for history_data in r.lrange('history_entity_' + entity, 0, 100):
            data.append(pickle.loads(history_data))
    
    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login')) 
Example #11
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def rmClient(request):

    mimetype = 'application/json'
    data = {}
    
    if request.method == 'POST' and 'client' in request.POST and request.POST['client'] != '':
        data['client'] = request.POST['client']        
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()
        
        if sensu_client_delete(data):
            data['result'] = 'okay'
        else:        
            data['result'] = 'failed deleting ' + data['client']
    
    return HttpResponse(json.dumps(data), mimetype)


#@login_required(login_url=reverse_lazy('login')) 
Example #12
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def resolve(request):

    mimetype = 'application/json'
    data = {}
    
    if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '':
        data['entity'] = request.POST['entity']        
        data['status'] = 0
        data['timestamp'] = datetime.datetime.now().timestamp()        
        data['output'] = "resolve request by %s" % (request.user.username)
        data['result'] = 'okay'
        
        sensu_event_resolve(data)
        Channel('background-alert').send(dict(data))
        
    
    return HttpResponse(json.dumps(data), mimetype)



#@login_required(login_url=reverse_lazy('login')) 
Example #13
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def subscriptions(request):        

    data = {}
    
    for word in r.keys("subscription_*"):
        subscription = re.sub(r'^subscription_', '', str(word.decode('utf-8')))
        try:
            
            subscription_data = r.lrange(word, 0, -1)
            data[subscription] = subscription_data 
            
        except:
            raise
    
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id))   
    
    return render(request, 'isubscribe/subscriptions.html', {'DATA':data, 'profile_form': profile_form})




#@login_required(login_url=reverse_lazy('login')) 
Example #14
Source File: middleware.py    From generator-django-rest with MIT License 6 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        # No need to process URLs if user already logged in
        if request.user.is_authenticated():
            return None

        # An exception match should immediately return None
        for url in self.exceptions:
            if url.match(request.path):
                return None

        # Requests matching a restricted URL pattern are returned
        # wrapped with the login_required decorator
        for url in self.required:
            if url.match(request.path):
                return login_required(view_func)(request, *view_args, **view_kwargs)

        # Explicitly return None for all non-matching requests
        return None 
Example #15
Source File: utils.py    From hknweb with MIT License 5 votes vote down vote up
def login_and_permission(permission_name):
    """ First requires log in, but if you're already logged in but don't have permission,
        displays more info. """
    def decorator(func):
        return wraps(func)( # preserves function attributes to the decorated function
                login_required(login_url='/accounts/login/')(
                    # raises 403 error which invokes our custom 403.html
                    permission_required(permission_name, login_url='/accounts/login/', raise_exception=True)(
                        func # decorates function with both login_required and permission_required
                    )
                )
            )
    return decorator 
Example #16
Source File: access.py    From django-plotly-dash with MIT License 5 votes vote down vote up
def login_required(view_function, **kwargs):
    'Wrap all DPD calls with login_required'
    return login_required_decorator(view_function) 
Example #17
Source File: decorators.py    From django-shopify-auth with MIT License 5 votes vote down vote up
def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication
    query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instead of just
    wrapping them up and encoding them in to the `next` parameter).

    This is useful for ensuring that users are automatically logged on when they first access a page through the Shopify
    Admin, which passes these parameters with every page request to an embedded app.
    """

    @wraps(f)
    def wrapper(request, *args, **kwargs):
        if is_authenticated(request.user):
            return f(request, *args, **kwargs)

        # Extract the Shopify-specific authentication parameters from the current request.
        shopify_params = {
            k: request.GET[k]
            for k in ['shop', 'timestamp', 'signature', 'hmac']
            if k in request.GET
        }

        # Get the login URL.
        resolved_login_url = force_str(resolve_url(login_url or settings.LOGIN_URL))

        # Add the Shopify authentication parameters to the login URL.
        updated_login_url = add_query_parameters_to_url(resolved_login_url, shopify_params)

        django_login_required_decorator = django_login_required(redirect_field_name=redirect_field_name,
                                                                login_url=updated_login_url)
        return django_login_required_decorator(f)(request, *args, **kwargs)

    return wrapper 
Example #18
Source File: decorators.py    From sal with Apache License 2.0 5 votes vote down vote up
def class_login_required(cls):
    """Class decorator for View subclasses to restrict to logged in."""
    decorator = method_decorator(login_required)
    cls.dispatch = decorator(cls.dispatch)
    return cls 
Example #19
Source File: views.py    From junction with MIT License 5 votes vote down vote up
def as_view(cls, **initkwargs):
        view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        return login_required(view) 
Example #20
Source File: mixin.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def as_view(cls, **initkwargs):
        # 调用View类中as_view
        view = super().as_view(**initkwargs)

        # 调用login_required装饰器函数
        return login_required(view) 
Example #21
Source File: mixin.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def as_view(cls, **initkwargs):
        # 使用super调用as_view
        view = super().as_view(**initkwargs)

        # 调用login_required装饰器函数
        return login_required(view) 
Example #22
Source File: views.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def as_view(cls, *args, **kwargs):
        view = super(LoginRequiredMixin, cls).as_view(*args, **kwargs)
        return login_required(view) 
Example #23
Source File: auth.py    From django-silk with MIT License 5 votes vote down vote up
def login_possibly_required(function=None, **kwargs):
    if SilkyConfig().SILKY_AUTHENTICATION:
        return login_required(function, **kwargs)
    return function 
Example #24
Source File: auth.py    From django-silk with MIT License 5 votes vote down vote up
def login_possibly_required(function=None, **kwargs):
    if SilkyConfig().SILKY_AUTHENTICATION:
        return login_required(function, **kwargs)
    return function 
Example #25
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_queryset(self, **kwargs):
        name = self.request.GET.get('name', '')    
        return Disease.objects.filter(Q(name__icontains=name)|Q(gene_names__icontains=name))

    # @method_decorator(login_required)
    # def dispatch(self, *args, **kwargs):
    #     return super(DiseaseListView, self).dispatch(*args, **kwargs) 
Example #26
Source File: views.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def as_view(cls, **initkwargs):
        view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        return login_required(view) 
Example #27
Source File: test_decorators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def testCallable(self):
        """
        login_required is assignable to callable objects.
        """
        class CallableView:
            def __call__(self, *args, **kwargs):
                pass
        login_required(CallableView()) 
Example #28
Source File: test_decorators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def testView(self):
        """
        login_required is assignable to normal views.
        """
        def normal_view(request):
            pass
        login_required(normal_view) 
Example #29
Source File: test_decorators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def testLoginRequired(self, view_url='/login_required/', login_url=None):
        """
        login_required works on a simple view wrapped in a login_required
        decorator.
        """
        if login_url is None:
            login_url = settings.LOGIN_URL
        response = self.client.get(view_url)
        self.assertEqual(response.status_code, 302)
        self.assertIn(login_url, response.url)
        self.login()
        response = self.client.get(view_url)
        self.assertEqual(response.status_code, 200) 
Example #30
Source File: test_decorators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def testLoginRequiredNextUrl(self):
        """
        login_required works on a simple view wrapped in a login_required
        decorator with a login_url set.
        """
        self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/')