我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.auth.decorators.login_required()。
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'))
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'))
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'))
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'))
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'))
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'))
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()
def check_manager_dec(func): ''' ??????????????????????????????????? :param func: :return: ''' @login_required() @functools.wraps(func)#python????????????????????__name__????????????????? def wrapper(request, *args, **kwargs): shop = get_object_or_404(Shop, id=kwargs.get('shop_id')) user = request.user if shop.check_manager(user): return func(request, *args, **kwargs) else: messages.error(request, '?????????????????????????') return redirect(reverse('geekpoint:index')) return wrapper
def subscribe_toggle(request): mimetype = 'application/json' data = {} if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '' and 'status' in request.POST and request.POST['status'] != '': data['entity'] = request.POST['entity'] data['status'] = request.POST['status'] if Subscribe.objects.filter(entity=request.POST['entity'], status=int(request.POST['status'])).count() > 0: # change existing object obj = Subscribe.objects.get(entity=request.POST['entity'], status=int(request.POST['status'])) if request.user.pk not in obj.friends.values_list('pk', flat=True).all(): obj.friends.add(request.user.pk) data['result'] = "subscription added" logger.debug('%s subscribed to %s' % (request.user.username, request.POST['entity'])) else: obj.friends.remove(request.user.pk) data['result'] = "subscription removed" logger.debug('%s unsubscribed from %s' % (request.user.username, request.POST['entity'])) else: # create new object obj = Subscribe(entity=request.POST['entity'], status=int(request.POST['status'])) obj.save() obj.friends.add(request.user.pk) data['result'] = "subscription added" logger.debug('%s subscribed to new entity %s' % (request.user.username, request.POST['entity'])) Channel('background-build-entity-rules').send({'entity': request.POST['entity']}) return HttpResponse(json.dumps(data), mimetype) #@login_required(login_url=reverse_lazy('login'))
def ack(request): mimetype = 'application/json' data = {} if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '' and 'ack_interval' in request.POST and request.POST['ack_interval'] != '': data['entity'] = request.POST['entity'] data['ack_interval'] = request.POST['ack_interval'] data['status'] = request.POST['status'] data['timestamp'] = datetime.datetime.now().timestamp() data['ack_by'] = request.user.username data['ack'] = True data['output'] = "acknowledged by %s for %s hours" % (request.user.username, request.POST['ack_interval']) if 'ack_comment' in request.POST: data['ack_comment'] = request.user.username + ': ' + request.POST['ack_comment'] ack_data = { 'user_id': request.user.pk, 'user_name': request.user.username, 'timestamp': datetime.datetime.now().timestamp(), 'ack_interval': request.POST['ack_interval'], 'ack_comment': data['ack_comment'] } logger.debug('ack %s' % json.dumps(ack_data)) cache.set("ack_" + request.POST['entity'], ack_data, timeout=(float(data['ack_interval']) * 3600)) Channel('background-ack').send(data) return HttpResponse(json.dumps(data), mimetype) #@login_required(login_url=reverse_lazy('login'))
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'))
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)
def as_view(cls): return login_required(super(LoginRequiredMixin, cls).as_view())
def staff_required(view_func): def _is_staff(request, *args, **kwargs): if not request.user.is_authenticated: return login_required(view_func)(request, *args, **kwargs) elif is_staff(request, request.user): return view_func(request, *args, **kwargs) else: raise PermissionDenied return wraps(view_func)(_is_staff)
def http_basic_login(func): return http_basic_auth(login_required(func)) # class Encoder(DjangoJSONEncoder): # def default(self, obj): # if callable(obj): # return obj.__name__ # return json.JSONEncoder.default(self, obj)
def is_activated(f): """ A decorator to allow only logged in and activated accounts to enter """ @login_required(login_url='/') def wrapper(*args, **kwargs): if(args[0].user.profile.activated): return f(*args, **kwargs) return redirect(reverse('inout:login') + '?showSection=activate') return wrapper
def render_workflows(request): user = UserSerializer(request.user) initState = { 'user': user.data } return TemplateResponse(request, 'workflows.html', {'initState': json.dumps(initState)}) # not login_required as logged out users can view public workflows
def user_login(request): # Like before, obtain the context for the user's request. context = RequestContext(request) # If the request is a HTTP POST, try to pull out the relevant information. if request.method == 'POST': # Gather the username and password provided by the user. # This information is obtained from the login form. username = request.POST['username'] password = request.POST['password'] # Use Django's machinery to attempt to see if the username/password # combination is valid - a User object is returned if it is. user = authenticate(username=username, password=password) # If we have a User object, the details are correct. # If None (Python's way of representing the absence of a value), no user # with matching credentials was found. if user: # Is the account active? It could have been disabled. if user.is_active: # If the account is valid and active, we can log the user in. # We'll send the user back to the homepage. login(request, user) return HttpResponseRedirect('/frontpage/') else: # An inactive account was used - no logging in! return HttpResponse("Your Polls account is disabled.") else: # Bad login details were provided. So we can't log the user in. print "Invalid login details: {0}, {1}".format(username, password) return HttpResponse("Invalid login details supplied.") # The request is not a HTTP POST, so display the login form. # This scenario would most likely be a HTTP GET. else: # No context variables to pass to the template system, hence the # blank dictionary object... return render_to_response('frontpage/login.html', {}, context) # Use the login_required() decorator to ensure only those logged in can access the view.
def user_is_staff(func): return user_passes_test(lambda u: u.is_staff)(login_required(func))
def user_is_finance(func): return user_passes_test(lambda u: u.is_staff and u.groups.filter(name="finance"))(login_required(func))
def as_view(cls, **kwargs): view = super(LoginRequiredMixin, cls).as_view(**kwargs) return login_required(view)
def alter_org_status(request, pk): try: obj = Organization.objects.get(pk=int(pk)) # alter status method on custom user if obj.is_active: obj.is_active = False messages.info(request, 'Organization {0} Deactivated.'.format(obj.name)) else: obj.is_active = True messages.info(request, 'Organization {0} Activated.'.format(obj.name)) obj.save() except: messages.info(request, 'Organization {0} not found.'.format(obj.name)) return HttpResponseRedirect(reverse('fieldsight:organizations-list')) # # @login_required # @group_required('admin') # def add_org_admin_old(request, pk): # obj = get_object_or_404( # Organization, id=pk) # if request.method == 'POST': # form = SetOrgAdminForm(request.POST) # user = int(form.data.get('user')) # group = Group.objects.get(name__exact="Organization Admin") # role = UserRole(user_id=user, group=group, organization=obj) # role.save() # messages.add_message(request, messages.INFO, 'Organization Admin Added') # return HttpResponseRedirect(reverse('fieldsight:organizations-list')) # else: # form = SetOrgAdminForm(instance=obj) # return render(request, "fieldsight/add_admin.html", {'obj':obj,'form':form})
def as_view(cls, **initkwargs): view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view)
def user_login(request): # Like before, obtain the context for the user's request. context = RequestContext(request) # If the request is a HTTP POST, try to pull out the relevant information. if request.method == 'POST': # Gather the username and password provided by the user. # This information is obtained from the login form. username = request.POST['username'] password = request.POST['password'] # Use Django's machinery to attempt to see if the username/password # combination is valid - a User object is returned if it is. user = authenticate(username=username, password=password) # If we have a User object, the details are correct. # If None (Python's way of representing the absence of a value), no user # with matching credentials was found. if user: # Is the account active? It could have been disabled. if user.is_active: # If the account is valid and active, we can log the user in. # We'll send the user back to the homepage. login(request, user) return HttpResponseRedirect('/') else: # An inactive account was used - no logging in! return HttpResponse("Your Rango account is disabled.") else: # Bad login details were provided. So we can't log the user in. print "Invalid login details: {0}, {1}".format(username, password) return HttpResponse("Invalid login details supplied.") # The request is not a HTTP POST, so display the login form. # This scenario would most likely be a HTTP GET. else: # No context variables to pass to the template system, hence the # blank dictionary object... return render_to_response('login.html', {}, context) # Use the login_required() decorator to ensure only those logged in can access the view.
def admin_login(request: HttpRequest) -> HttpResponse: """ The admin site login is wrapped in the login_required decorator. This way we can link directly to admin pages, and non-authenticated users will be sent to settings.LOGIN_URL with an appropiate ?next=... parameter instead. Unfortunately, the django admin does not respect the query redirect parameter, so this view intercepts the view logic and redirects if the user has returned from a successful login. """ if request.user.is_authenticated and 'next' in request.GET: # The user has returned from the login provider return redirect(request.GET['next']) else: # The user has not yet performed the login return admin.site.login(request)
def tfa_required(auth_url='/tfa/auth', expires=0): def dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _view(request, *args, **kwargs): request.session.set_expiry(expires) code = request.session.get('auth_code', None) if code: return view_func(request, *args, **kwargs) send_auth_sms(request.user) next_url = '?next=' + request.path red_url = auth_url + next_url return HttpResponseRedirect(red_url) return login_required(_view) return dec
def verified_email_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified users to proceed. This decorator ensures the user is authenticated and has a verified email address. If the former is not the case then the behavior is identical to that of the standard `login_required` decorator. If the latter does not hold, email verification mails are automatically resend and the user is presented with a page informing them they needs to verify their email address. """ def decorator(view_func): @login_required(redirect_field_name=redirect_field_name, login_url=login_url) def _wrapped_view(request, *args, **kwargs): if not EmailAddress.objects.filter(user=request.user, verified=True).exists(): send_email_confirmation(request, request.user) return render(request, 'account/verified_email_required.html') return view_func(request, *args, **kwargs) return _wrapped_view if function: return decorator(function) return decorator
def index_test(request): # call the render function with the request and template name # as parameters to render a template. cache.set('testkey', 'test cache', 30) return render_to_response('index.html', {'name': cache.get('testkey')}) #@login_required(login_url='/login/')
def __init__(self): tnb = self.get_base_name() OCreateView = self.get_create_view() self.create = login_required(OCreateView.as_view( model=self.model, fields=self.fields, success_url=reverse_lazy(self.namespace + ':objectview_list'), template_name=tnb + "_form.html" )) OUpdateView = self.get_edit_view() self.edit = login_required(OUpdateView.as_view( model=self.model, fields=self.fields, success_url=reverse_lazy(self.namespace + ':objectview_list'), template_name=tnb + "_form.html" )) self.delete = login_required(DeleteView.as_view( model=self.model, success_url=reverse_lazy(self.namespace + ':objectview_list'), template_name=tnb + "_delete.html" )) OListView = self.get_list_view() self.list = login_required(OListView.as_view( model=self.model, paginate_by=10, template_name=tnb + "_list.html" ))
def batch_add(request): return render(request, 'batch_add.html', locals()) # @login_required(login_url='/accounts/login/') # @permission_required('myapp.can_see_mysqladmin', login_url='/') # def test_tb(request): # dbtag = request.GET['dbtag'] # if dbtag!='all': # mydata = {'dupresult':get_dupreport(dbtag,request.GET['email'])} # # return render(request, 'batch_add.html', locals()) # return JsonResponse(mydata)
def control_panel_view(func): @wraps(func) def wrapped_func(request, *args, **kwargs): if not request.user_permissions.control_panel: raise PermissionDenied return func(request, *args, **kwargs) return login_required(login_url='site.login')(wrapped_func)
def testCallable(self): """ Check that login_required is assignable to callable objects. """ class CallableView(object): def __call__(self, *args, **kwargs): pass login_required(CallableView())
def testView(self): """ Check that login_required is assignable to normal views. """ def normal_view(request): pass login_required(normal_view)
def testLoginRequired(self, view_url='/login_required/', login_url=None): """ Check that 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.assertTrue(login_url in response.url) self.login() response = self.client.get(view_url) self.assertEqual(response.status_code, 200)
def testLoginRequiredNextUrl(self): """ Check that 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/')
def my_view(request): settings.LOGIN_URL @login_required(login_url='/accounts/login/')
def as_view(cls): if getattr(cls, 'require_login', False): return login_required(cls()) else: return cls()
def as_view(self, *args, **kwargs): view = super(StaffRequiredMixin, self).as_view(*args, **kwargs) return login_required(view)
def as_view(self, *args, **kwargs): view = super(LoginRequiredMixin, self).as_view(*args, **kwargs) return login_required(view)
def reg(request): try: if request.method == "POST": reg_form = RegForm(request.POST) if reg_form.is_valid(): cd = reg_form.cleaned_data User.objects.create(username = cd['username'], password = make_password(cd['password']), email = cd['email'], mobile = cd['tel']) return HttpResponseRedirect('/login/') else: return render(request,'failure.html',{'reason':reg_form.errors}) else: reg_form = regForm() except Exception as e: print e return render(requeset,'reg.html',locals()) @login_required(login_url = '/login/') def login_test(request): return HttpResponse('????') def login(request): errors = [] if request.method == "POST": username = request.POST.get('username', '') password = request.POST.get('password', '') if not username: errors.append('Enter a username') if not password: errors.append('Enter a password') if not errors: if not request.user.is_authenticated(): user = auth.authenticate(username = username,password = password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: return HttpResponse('?????????') else: return HttpResponse("?????") return render(request, 'user_login.html',{'errors':errors})
def messages_to_all(request, code): #added by lxy from django.contrib.auth.models import Group from django.contrib.auth.models import User user = User.objects.get(id = 1) all_users = Group.objects.get(name="all") message_list = Message.objects.filter(recipient=user, group_recipient=all_users) return render_to_response("django_messages/messages_to_all.html", { 'message_list': message_list, }, context_instance=RequestContext(request)) # compose = login_required(compose)
def get_success_url(self): return reverse('home:listar_usuarios') # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(EditUser, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs): context = super(ListUsers, self).get_context_data(**kwargs) context['clientes'] = Cliente.objects.all() return context # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(ListUsers, self).dispatch(*args, **kwargs)
def comment_commit(request, revision): # can't use login_required because it's API call # @login_required redirects to login page with 302 result code if not request.user.is_authenticated(): raise PermissionDenied try: revision = int(revision) except ValueError: return HttpResponseBadRequest() commit = get_object_or_404(Commit, revision=revision) if request.method == 'DELETE': # Delete comment if text wasn't passed try: comment = CommitNote.objects.get(commit=commit, user=request.user) comment.delete() except CommitNote.DoesNotExist: pass elif request.method == 'POST': # Delete comment if text wasn't passed note, created = CommitNote.objects.get_or_create(commit=commit, user=request.user) note.text = request.POST.get('text', '') note.save() return HttpResponse(status=204)