开发者

Django - what's the practice and most secure method of deleting or editing records for logged in users?

I have some sections on my web site where only logged in users can see their resources.

I also want to make absolutely sure that only that authorized user can modify and delete his/her records. What's the best practice and more secure way of accomp开发者_如何学JAVAlishing this in Django?

Real examples would be truly appreciated.


For my project, I created a Decorator that checked if the right user was logged in:

#decorator.py
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def same_user_required(func):
    def wrapper(request, user):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('login-view'))
        if not user == request.user.username:
            return HttpResponseRedirect(reverse('login-view'))
        return func(request, user)
    return wrapper

You then add it to any views that need checking:

#view_profile.py
from apps.utilities.decorators import same_user_required

@same_user_required
def edit_profile(request, user):

Note that my URL contains the username /profile/edit/<username>, which is where the parameter comes from, in the edit_profile view.

Another way is to use the Django built-in decorator, user_passes_test (see Django Book Chap 14 for an example of its usage. You then just have to write the test, not the decorator boilerplate code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜