Unsure how/where to manipulate Django objects - python

Okay so I am very new to Django and relatively new to Python as well. In the website I am building, I am using some middleware that someone else made to keep track of "online" users using the cache to do so. Here is the middleware I'm referring to
import datetime
from django.core.cache import cache
from django.conf import settings
class ActiveUserMiddleware:
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated():
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now,
settings.USER_LASTSEEN_TIMEOUT)
I want to take all of the online users, then divide them based on whether they are in highschool or college (which is an attributed I gave users via foreign key to a profile), and then return a random user from the list of online users who meet those certain requirements. I am at a loss on how to do this because the django structure is still confusing me. Would I implement this in a view or in a model? After looking at the code for the active_users app I have figured out that I can import the active_users, but I'm not sure if that is a list, an array, or an object. Also how do I determing the number of online_users? Does something like online_users.length work? Here is the code I have come up with so far: (I have omitted some other imports and views for the sake of brevity). I'm sorry I haven't come up with a lot of code on my own, I am just very stuck/frustrated. Any help is greatly appreciated.
from online_status.status import CACHE_USERS
from online_status.utils import encode_json
from django.contrib.auth.models import User
from django.core.cache import cache
from django.template.context import RequestContext
def send_to(request):
sender = request.user
sender_level = sender.username
online_users = cache.get(CACHE_USERS)
match_users=[]
for User in online_users:
if User.username == sender_level:
match_users.append(user)
random_user = choice(match_users)
html = "<html> <body> <p> User: %s % random_user </p></body></html>" % random_user
return render_to_response(html)

With a cache based seen info you need to extract the user name from the db to be able to get online users.
So the only way would be to filter UserProfile.objects.all() based on the value of the cache.
Then you can do
from random import choice
random_user = choice(online_users)
But it would be more efficient for those kinds of requests to store the seen info in your model. This way you could directly do a request like :
online_users = UserProfile.objects.filter(seen__lte=now-timeout)
In a typical use you would have a lot of users but a few online users. So the first version would be really slower.

Related

Getting user`s UUID from django server

I have a django server with an admin panel.
Different users make changes there and this is saved via auditlog in the database and displayed in the "history".
But there are situations when a user enters under the account of another user and makes changes on his behalf.
In order to identify from which device this or that change was made, it was a nice decision to also record data about the IP of the user from whom the change was made, and his unique device number.
By overloading several methods in the "AuditlogMiddleware" class, I got the desired result via "uuid.UUID(int=uuid.getnode())".
(Tested locally, because the prod server is heavily loaded and there is no way to do test committees)
from __future__ import unicode_literals
import threading
import time
from auditlog.middleware import AuditlogMiddleware
threadlocal = threading.local()
class ExtendedAuditlogMiddleware(AuditlogMiddleware):
def process_request(self, request):
threadlocal.auditlog = {
'signal_duid': (self.__class__, time.time()),
'remote_addr': request.META.get('REMOTE_ADDR'),
}
super(ExtendedAuditlogMiddleware, self).process_request(request)
**#changes here
import uuid
threadlocal.auditlog['additional_data'] = str(uuid.UUID(int=uuid.getnode()))+" | "+request.META["USERNAME"]**
# #staticmethod
def set_actor(self, user, sender, instance, signal_duid, **kwargs):
super(ExtendedAuditlogMiddleware, self).set_actor(user, sender, instance, signal_duid, **kwargs)
**#changes here
instance.additional_data = threadlocal.auditlog['additional_data']**
But the problem is that I think I get the UUID not of the user, but of the server, because there is no access to the user, i guess. I couldn't find the information, and I couldn't come up with my own solution either.
Question - is it even possible to get information from the server about django admin users' devices??
If not, what can i use instead of UUID to identify which device was used while making changes in django admin panel??
Thank you all in advance!
try to use javascript in side of your template to send this info thrugh

How should I enforce permission checking when file is reached/downloaded in Django?

I don't know this is a typical thing to do in web application, but what we achieve is that, let's say we have a Person model, inside this model, we have a FileField stores user's photo:
class Person(models.Model):
photo = models.FileField(upload_to='Person_photo')
What I want to achieve is that only the owner can see his or her photo. People who log on a different account or even not log in should not be able to see the photo. Let's assume we have a way to check whether a photo belongs to a certain user or not:
def permission(photo_filename, pid):
# return True if photo_filename exists and belongs to the person pid
We can figure this part out, for example, use permission system provided in Django. Of course from the views.py we can control whatever image we want to show on the page, but for example, we want to block people make attempts to figure out the URLs and get the photo, for example, typing
http://some.domain/media/Person_photo/Amy.jpg
in URL bar in the browser should only work if she is Amy. What is a good way to do it? Is there a library for this purpose?
You can define view for this
view.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from appname.models import Person
#login_required
def show_photo(request):
person = get_object_or_404(Person, user=request.user)
response = HttpResponse(person.photo.read(), content_type="image/jpg")
response['Content-Disposition'] = 'filename=photo.jpg'
return response
urls.py
urlpatterns += [
url(r'^photo/$', show_photo),
]
Users will only see their photo.

How to prevent user changing URL <pk> to see other submission data Django

I'm new to the web development world, to Django, and to applications that require securing the URL from users that change the foo/bar/pk to access other user data.
Is there a way to prevent this? Or is there a built-in way to prevent this from happening in Django?
E.g.:
foo/bar/22 can be changed to foo/bar/14 and exposes past users data.
I have read the answers to several questions about this topic and I have had little luck in an answer that can clearly and coherently explain this and the approach to prevent this. I don't know a ton about this so I don't know how to word this question to investigate it properly. Please explain this to me like I'm 5.
There are a few ways you can achieve this:
If you have the concept of login, just restrict the URL to:
/foo/bar/
and in the code, user=request.user and display data only for the logged in user.
Another way would be:
/foo/bar/{{request.user.id}}/
and in the view:
def myview(request, id):
if id != request.user.id:
HttpResponseForbidden('You cannot view what is not yours') #Or however you want to handle this
You could even write a middleware that would redirect the user to their page /foo/bar/userid - or to the login page if not logged in.
I'd recommend using django-guardian if you'd like to control per-object access. Here's how it would look after configuring the settings and installing it (this is from django-guardian's docs):
>>> from django.contrib.auth.models import User
>>> boss = User.objects.create(username='Big Boss')
>>> joe = User.objects.create(username='joe')
>>> task = Task.objects.create(summary='Some job', content='', reported_by=boss)
>>> joe.has_perm('view_task', task)
False
If you'd prefer not to use an external library, there's also ways to do it in Django's views.
Here's how that might look:
from django.http import HttpResponseForbidden
from .models import Bar
def view_bar(request, pk):
bar = Bar.objects.get(pk=pk)
if not bar.user == request.user:
return HttpResponseForbidden("You can't view this Bar.")
# The rest of the view goes here...
Just check that the object retrieved by the primary key belongs to the requesting user. In the view this would be
if some_object.user == request.user:
...
This requires that the model representing the object has a reference to the User model.
In my project, for several models/tables, a user should only be able to see data that he/she entered, and not data that other users entered. For these models/tables, there is a user column.
In the list view, that is easy enough to implement, just filter the query set passed to the list view for model.user = loggged_id.user.
But for the detail/update/delete views, seeing the PK up there in the URL, it is conceivable that user could edit the PK in the URL and access another user's row/data.
I'm using Django's built in class based views.
The views with PK in the URL already have the LoginRequiredMixin, but that does not stop a user from changing the PK in the URL.
My solution: "Does Logged In User Own This Row Mixin"
(DoesLoggedInUserOwnThisRowMixin) -- override the get_object method and test there.
from django.core.exceptions import PermissionDenied
class DoesLoggedInUserOwnThisRowMixin(object):
def get_object(self):
'''only allow owner (or superuser) to access the table row'''
obj = super(DoesLoggedInUserOwnThisRowMixin, self).get_object()
if self.request.user.is_superuser:
pass
elif obj.iUser != self.request.user:
raise PermissionDenied(
"Permission Denied -- that's not your record!")
return obj
Voila!
Just put the mixin on the view class definition line after LoginRequiredMixin, and with a 403.html template that outputs the message, you are good to go.
In django, the currently logged in user is available in your views as the property user of the request object.
The idea is to filter your models by the logged in user first, and then if there are any results only show those results.
If the user is trying to access an object that doesn't belong to them, don't show the object.
One way to take care of all of that is to use the get_object_or_404 shortcut function, which will raise a 404 error if an object that matches the given parameters is not found.
Using this, we can just pass the primary key and the current logged in user to this method, if it returns an object, that means the primary key belongs to this user, otherwise it will return a 404 as if the page doesn't exist.
Its quite simple to plug it into your view:
from django.shortcuts import get_object_or_404, render
from .models import YourModel
def some_view(request, pk=None):
obj = get_object_or_404(YourModel, pk=pk, user=request.user)
return render(request, 'details.html', {'object': obj})
Now, if the user tries to access a link with a pk that doesn't belong to them, a 404 is raised.
You're going to want to look into user authentication and authorization, which are both supplied by [Django's Auth package] (https://docs.djangoproject.com/en/4.0/topics/auth/) . There's a big difference between the two things, as well.
Authentication is making sure someone is who they say they are. Think, logging in. You get someone to entire their user name and password to prove they are the owner of the account.
Authorization is making sure that someone is able to access what they are trying to access. So, a normal user for instance, won't be able to just switch PK's.
Authorization is well documented in the link I provided above. I'd start there and run through some of the sample code. Hopefully that answers your question. If not, hopefully it provides you with enough information to come back and ask a more specific question.
This is a recurring question and also implies a serious security flaw. My contribution is this:
There are 2 basic aspects to take care of.
The first is the view:
a) Take care to add a decorator to the function-based view (such as #login_required) or a mixin to the class-based function (such as LoginRequiredMixin). I find the official Django documentation quite helpful on this (https://docs.djangoproject.com/en/4.0/topics/auth/default/).
b) When, in your view, you define the data to be retrieved or inserted (GET or POST methods), the data of the user must be filtered by the ID of that user. Something like this:
def get(self, request, *args, **kwargs):
self.object = self.get_object(queryset=User.objects.filter(pk=self.request.user.id))
return super().get(request, *args, **kwargs)
The second aspect is the URL:
In the URL you should also limit the URL to the pk that was defined in the view. Something like this:
path('int:pk/blog-add/', AddBlogView.as_view(), name='blog-add'),
In my experience, this prevents that an user sees the data of another user, simply by changing a number in the URL.
Hope it helps.
In django CBV (class based views) you can prevent this by comparing the
user entered pk and the current logged in user:
Note: I tested it in django 4 and python 3.9.
from django.http import HttpResponseForbidden
class UserDetailView(LoginRequiredMixin, DetailView):
model = your_model
def dispatch(self, request, *args, **kwargs):
if kwargs.get('pk') != self.request.user.pk:
return HttpResponseForbidden(_('You do not have permission to view this page'))
return super().dispatch(request, *args, **kwargs)

Reporting user on Django error reports

I use Django's built-in feature for sending me error reports every time there's a 500 on the server. I use the include_html feature to get the richer version.
I'd really like the logged-in user, if one is logged in, to be sent as part of the report. I know I can deduce it myself using the session id, but I'd really prefer it be sent so I won't have to look it up every time. How can I do that?
You need to make use of Custom Error Reports. settings.py You'll need to make your own exception reporter class. I haven't used it with the include_html feature though.
This is an example of what you'll need to do.
from django.shortcuts import render
from django.views.debug import SafeExceptionReporterFilter
class CustomExceptionReporterFilter(SafeExceptionReporterFilter):
def get_request_repr(self, request):
result = u"User Info: \n"
if request.user.is_authenticated():
user = request.user
result += u"\nUser Id: {}".format(user.id)
else:
result += u"\nUser Id: Not logged in"
result += super(CustomExceptionReporterFilter, self).get_request_repr(request)
return result

django: keep each users data separate

I am trying to workout how / the best, most secure way to keep a user's data separate within a django site that I need to write.
Here is an example of what I need to do...
example app ToDoList
Using django contrib.auth to manage users / passwords etc, I will have the following users
tom
jim
lee
There will be a ToDo model (in my real app there will be additional models)
class ToDo(models.Model):
user = models.ForeignKey(User)
description = models.CharField(max_length=20)
details = models.CharField(max_length=50)
created = models.DateTimeField('created on')
The issue that I am having - and may be over thinking this: How would this be locked down so tom can only see Tom's todo list, lee can only see his todo list and so on...
I have seen a few posts stating that you could use filter in every query, or use urls, so the url could look like www.domain.com/username/todo
But either way I am not sure if this is the right way / best way, or bonkers in terms of stopping users seeing each others data
cheers
Richard
One approach is to filter the ToDo items by the currently logged in user:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from your_app.models import ToDo
#login_required
def todos_for_user(request):
todos = ToDo.objects.filter(user=request.user)
return render(request, 'todos/index.html', {'todos' : todos})
This locks down the view for authenticated users only, and filtering by the logged in user from the request, another user, even if logged in, can't access another user's ToDo records. Hope that helps you out.
Make url like www.domain.com/username/todo is one way to implement it, but it doesn't guarantee you achieve security.
What you should do keep your user's login information in a session data after user login, and every time you check certain view,
check whether that particular user has right to see this view.
using user's login info (ID, or username) when querying user's Todo list.
And I guess this link will help you to do your job.
Sessions, Users, and Registration.

Categories

Resources