如何让登录用户只能访问Django通用视图?

时间:2016-09-30 10:40:29

标签: python django django-socialauth

我已经实现了Google的社交认证,供用户登录。如果他们没有使用social-auth登录,我无法理解如何限制访问者访问UpdateView,ListView或CreateView等通用视图系统。这是代码。

views.py

class AchievementCreate(CreateView):
    form_class = AchievementForm2
    model = Achievements
    def form_valid(self, form):
            achieves = form.save(commit=False)
            achieves.resume = Resume.objects.get(pk=2)
            return super(AchievementCreate, self).form_valid(form)

def home(request):
#logout(request)
    uname=""
    if request.method == 'POST' and 'submit' in request.POST:
        submit = request.POST['submit']
        if submit=="sign-out":
            logout(request)

    if '_auth_user_id' in request.session:
        uname=sm.UserSocialAuth.objects.get(
        user_id=int(request.session['_auth_user_id'])
        ).user
        request.session['uname']=str(uname)
    return render(request,'cv/home.html',{'uname': uname})

home.html的

 <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
        <title>Home</title>
    </head>
    <body>
        <form method="post" action="{% url 'cv:home' %}">{% csrf_token %}
            {% if uname %}
                Helo, {{uname}}<br>
                The user already signed in. He may need to sign out<br>
                <input type="submit" name="submit" value="sign-out">            
            {% else %}
                Please sign-in<br>
                <a href="{% url 'social:begin' 'google-oauth2' %}">Google login</a>
            {% endif %}  
        </form> 
    </body>
    </html>

urls.py

urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^achievements/(?P<pk>[0-9]+)/delete/$', views.AchievementDelete.as_view(), name='achievement-delete'),
url(r'^achievements/(?P<pk>[0-9]+)/$', views.AchievementUpdate.as_view(), name='achievement-update'),
url(r'^achievements/add/$', login_required(views.AchievementCreate.as_view()), name='achievement-add'),
url(r'^home/$', views.home, name='home'),]

我希望只有在用户登录后才能访问“AchievementCreate”类。但我不明白如何。是否可以使用会话?在这种情况下如何?

4 个答案:

答案 0 :(得分:0)

您需要导入login_required装饰器并在视图前面放置@login_reqired。此视图不仅可以在登录时访问。

示例:

    from django.contrib.auth.decorators import login_required
    @login_required
    #put your view here

答案 1 :(得分:0)

我们需要编写mixins来检查用户是否已登录。

Django 1.9引入了LoginRequiredMixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class UserProfile(LoginRequiredMixin, View):
    login_url = '/login/'

以下代码是自定义mixin,它将检查用户是处于活动状态还是非活动状态。如果用户处于非活动状态,它将注销会话。我们需要在mixins.py这样的单独文件中编写mixins,在视图中导入mixins

class UserMixin(object):
    def dispatch(self, request, *args, **kwargs):
        user = self.request.user
        if user:
            if user.is_active:
                return super(UserMixin, self).dispatch(request, *args, **kwargs)
            else:
                logout(self.request)
        return HttpResponseRedirect(reverse('cv:home'))

在Views.py

from mixins.py import UserMixin 

class UserEdit(UserMixin, View):
    model = UserProfile
    template_name = "dashboard/edit_user.html"

答案 2 :(得分:0)

所以你在登录系统中使用'social-auth'。在您的情况下,您将必须使用自定义功能。我假设您可以通过参考以下内容访问登录用户: request.SESSION

如果是这样,那么您可以覆盖CreateView的调度方法:

class AchievementCreate(CreateView):
   .....
   .....
   def dispatch(self, request, *args, **kwargs):
      user = request.session['_auth_user_id']
      # handle authentication

答案 3 :(得分:0)

def home(request):

    if request.user.is_authenticated:
        # Do something for authenticated users

    else:
        # Do something for anonymous users

https://docs.djangoproject.com/en/3.1/topics/auth/default/#authentication-in-web-requests