How can I restrain acess for my profile view? - python

I did a view to access personal information. To do this, there is a pk in the URL. However, this is problematic because they can access other user info just by changing the value of the pk. I read the doc and I didn't find anything related to that.
How can I prevent this problem?
path('profil/<int:pk>', views.ProfilView.as_view(), name="profil")

If there is no reason for the PK to be in the URL (i.e. you don't want to use the same view to view others' information), you can make your ProfilView look something like this, assuming it derives from DetailView:
from django.contrib.auth.mixins import LoginRequiredMixin
# ...
class ProfilView(LoginRequiredMixin, DetailView):
model = User # or whatever it happens to be
def get_object(self):
return self.request.user # Always return the current user
and simply
path('profil/', views.ProfilView.as_view(), name="profil")
in your URL configuration.

Require the user to be logged in, and display a 401 Unauthorized error if it's not their own profile id.
It might be useful have a profil/me url that always shows the user's own profile.

Related

Need help understanding Django authentication code

Code from views.py:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
user = request.user
posts = Post.objects.filter(user=user)
I can't understand the inline #login_required. Why should we use this decorator?
And what about user = request.user? In this project, we hadn't created a model named user.
Please explain this to me. Thanks a lot!
In this code I can't understand inline #login_required Why should we use the decorator
The #login_required decorator does exactly what it says: it requires a user to log in when accessing the route associated with this view.
And user=request.user user ?? In this project, we hadn't created models named user.
Django defines a User model fore you.
For more details about the default authentication and authorization system, read the documentation. Googling something like "django login_required" gives a wealth of information.
The logic behind this function is to achieve that only the logged-in user has access to the posts he wrote himself: all http requests contain the id of the user: if he is not logged in, he is identified as anonymous, otherwise as user.
To get his identification, you call request.user and then pass it to the query to call his posts.
Therefore :
neither an anonymous user nor another user can get access to the full list of posts of a third user.

Django - How to differentiate between users in the database?

I'm building a Django server for my company and I'm still unfamiliar with some processes. I'm sure this is super simple, I'm just completely unaware of how this works.
How do I differentiate between user's data so it doesn't get mixed up?
If Jill is a user and she requests a page of her profile data, how do I not send her Jack's profile data, especially if there are multiple models invovled?
For example, the code in the view would look like this:
def display_profile(request)
profile = Profile.objects.get(???) # What do I put in here?
I understand that I can do:
def display_profile(request, user)
profile = Profile.objects.get(user_id=user)
But that's not my design intention.
Thank you in advance.
As documented
Django uses sessions and middleware to hook the authentication system into request objects.
These provide a request.user attribute on every request which
represents the current user. If the current user has not logged in,
this attribute will be set to an instance of AnonymousUser, otherwise
it will be an instance of User.
So in your case (notice field not being called user_id )
profile = Profile.objects.get(user=user)
In your Django view, you can access the current user with request.user.
So if you want to get a Profile instance matching your current logged in user, just do a query as follow:
profile = Profile.objects.get(user=request.user)
This assumes you have a user foreign key field (or OneToOne) in your Profile model.

Django - call celery Task from view

i want to call a celery task from my views.py but for some reason i get the following error:
...
tasks.py
...
urls.py
...
Thanks in advance
Your user = get_user_model.objects.get(pk=pk) line should be changed to user = get_user_model().objects.get(pk=pk). get_user_model is a method which returns the default user model for the project. get_user_model method will not be called until you put the function parentheses after it (like get_user_model()).
You are not passing the pk of the user in the url, so it is always None and the user with pk=None doesn't exists. You should add the pk to the url, like url(r'^user/wallet_deposit/new_addr_btc/(?P<pk>\d+)$', MyProject_Accounts.wallet_deposit_gen_new_addr_btc, name='wallet_deposit_gen_new_addr_btc'). Also a user should be able to arrive at the correct url (you should generate the links correctly).
Maybe, as a user, I should be able to change only my account? If so, you should take the authenticated user from the request, as you did in the else block

Django 1.10 query a table using username from logged in user

I'm new to Django, creating a site where I want logged in users to see there own data provided in a table. This table has a field username.
I want the users to see there own data in a listview. I can't figure out how I can query, using the username from User. To give you an idea of what I am doing, this is what I have as code: (I tried multiple other ways, but I can't get a string with the User login Name.
from django.contrib.auth.models import User
from django.views.generic import ListView
username = User.username
class RoosterListView(LoginRequiredMixin, ListView):
queryset = Roosters.objects.filter(startvc__range=(DatumStart, DatumEind),username=CurrentUser).order_by("startvc")[:35]
Thanks so much in advance.
Remove the username = User.username line - User is the model class, not the current user instance.
You can access the current user if you set queryset, as this is loaded when the module is imported, not when the request is made. If you override the get_queryset method, you can access the user with self.request.user.
class RoosterListView(LoginRequiredMixin, ListView):
def get_queryset(self):
return Roosters.objects.filter(startvc__range=(DatumStart, DatumEind), username=self.request.user.username).order_by("startvc")[:35]
you can get the username of your logged in user by
username = request.user
you can simply pass your request parameter around to get all the information of the current session and do whatever query you wanna do.

Using Account Auth to verify if logged in yet

I have a small view:
def AccountHome(request):
return render(request, 'myapp/account/accounthome.html', {
})
In previous views, I've used:
if user is not None and user.is_active
to check if a user is already authenticated or not when using native form classes like: AuthenticationForm for example when logging in a user.
But on this view I am not using that, is there someway to validate whether a user is logged in or not without using this AuthenticationForm classagain? Thisviews purpose is to show the homescreen when logged in, so it seems non-intuitive to extend thatAuthenticationForm` class again.
Any help or thoughts?
Thanks
Use is_authenticated() method
Like this: if request.user.is_authenticated():
You can find the reference here: https://docs.djangoproject.com/en/dev/ref/contrib/auth/#methods

Categories