views:

190

answers:

2

I'm playing around with django and built a small app where a user can access their info via the url http:///localhost:8000/username/info/ . I want to add the ability to edit that info through http:///localhost:8000/username/info/edit/, but also want to make sure the currently logged in user (using django.contrib.auth) can access only his information. I accomplished this by doing the following in the view (username in the view args is captured from the url):

@login_required
def edit_info(request, username=''):
    if request.user.username == username:
        # allow accessing and editing the info..
    else:
        # redirect to some error page

So, obviously, I don't want user 'johnny' to edit the info belonging to user 'jimmy' by simply pointing his browser to /jimmy/info/edit/. The above works, but my concern is that I'm missing something here as far as security goes. Is this the right way to go about this? Thanks.

+1  A: 

This should work for what you are trying to do without any glaring security risks.

But, why show their username if no one else can see at least a profile or something at this location though? Wouldn't this be more like a 'account' page? Then you wouldn't check against the username in the url, the only url you could go to would be account, and it would just load the logged in user's info.

Alex Sexton
I see. I thought about letting users view other people's info, but edit should be restricted only to personal data, of course.
sa125
A: 

With the @login_required and parsing the request.user they will never end up on anothers profile. My profile view

@login_required
def user_profile(request):
    """ User profile page """
    u = User.objects.get(pk=request.user.pk)

    return render_to_response('myapp/user_profile.html', {
                                'user': request.user,
                                })

Then in the template simply use stuff like:

Welcome <b>{{ user.first_name }} {{ user.last_name }}</b>
GerardJP