Dimitris
Dimitris

Reputation: 413

User authentication to specific users

Hello i use @login_required to restrict access to some pages that stores bookmarks for users, but in some cases i want the user to access only his bookmarks and must be stopped if he try to enter a url that edits a bookmark that belongs to another user. how can i do that?

Upvotes: 1

Views: 98

Answers (1)

dm03514
dm03514

Reputation: 55962

@login_required can help you make sure the user is logged in to even access the view.

Once the view is accessed you could check to make sure the user is allowed to access the bookmarks, and only fetch bookmarks they are allowed to access

for example if your url looked something like

/bookmarks/ and corresponds to function bookmarks

@loggin_required
def bookmarks():
  # only fetch book makrs for this user
  bookmarks = Bookmarks.objects.filter(user=request.user)

This will make sure user is logged in to access the url and that book marks are only displayed for the user that is viewing the page. You could add some sort of permission system if some users can view other users bookmarks

if this view were to show all book marks for a user and you wanted to provide a url to edit bookmarks or something like

bookmarks/{{ bookmark_id }}/edit that maps to edit_bookmark

@login_required
def edit_bookmark(bookmark_id):
   # user is guarenteed to be logged in so request.user is available
   # your permission system will depend on how you authenticate whether a user can edit
   # a bookmark or not
   # CHECK if user has permission to edit bookmark
   pass

Upvotes: 3

Related Questions