Conditional sign up for internal Django site - python

I'm using Django (with python-social-auth) to authenticate users for an internal student information system.
We currently have an external SQL table, that keeps track of whether a user is: an admin, staff member, or student, based on their Google Apps email address.
Current post_save function
#receiver(post_save, sender=User)
def create_student_or_staff(sender, instance, created, **kwargs):
if created:
try:
state = UserState.objects.get(
email=instance.email
)
except UserState.DoesNotExist:
# if exception is raised here, user is not created but site crashes
# if no exception is raised, a user is created but no admin, staff or student instance
pass
if state.staff:
if state.is_admin:
Admin.objects.create(
user=instance
)
else:
Staff.objects.create(
user=instance
)
else:
class_instance = None
if state.year and state.band and state.set:
class_model = apps.get_model('class_groups.ClassGroup')
class_instance = class_model.objects.get(
year=state.year,
band=state.band,
set=state.set
)
Student.objects.create(
user=instance,
class_group=class_instance
)
When a user first attempts to login, I want to be able to check against that database to see if they meet any of the criteria.
Currently, using the post_save signal for the user (I've also tried to use pre_save but no dice) to somehow halt the creation of a Django user object if they are not on the UserState table.
Is this possible at all? The only way I can halt the creation of a user instance currently is by raising an exception during the post_save, which isn't ideal of course.
Sorry for the broad question, if you need any specifics please let me know. Thanks in advance!

The best option i think is use the user_pass_test function or use the UserPassTestMixin for class base views.

Ended up adding a new pipeline for python-social that checks if the incoming email address is already in the UserState database.
Pipeline added after the social details are retrieved.
settings.py
# adding all the pipelines in for the time being, can adjust later
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
# custom pipeline
'sis_users.pipeline.user_state_exists',
'social.pipeline.user.user_details',
...
)
pipeline.py
def user_state_exists(backend, details, response, *args, **kwargs):
email = details['email']
try:
UserState.objects.get(
email=email
)
except UserState.DoesNotExist:
raise UserStateDoesNotExistException(backend)
exceptions.py
from social_core.exceptions import AuthException
class UserStateDoesNotExistException(AuthException):
def __str__(self):
return "You must be an administrator, staff member or a student to sign in. Please contact the school for more assistance."
Thanks for all the suggestions!

Related

How to add a function after a record inserted in database using django admin?

I want to execute a function after a record inserted to database using django-admin panel .
I have a product table , i want to send notification to users when a record inserted in database by django admin panel . i know how to send notification to users , but i dont know where to put my code .
any suggestion will be helpfull .
How can i execute a function to notify user after my record inserted ?
here is my code to execute after record inserted :
from fcm_django.models import FCMDevice
device = FCMDevice.objects.all()
device.send_message(title="Title", body="Message", icon=..., data={"test": "test"})
i searched alot but not found anything usefull .
thanks to this great communtiy .
You can modify save method on your product model
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
device = FCMDevice.objects.all()
device.send_message(title="Title", body="Message", icon=..., data={"test": "test"})
Well, it will send the notification every time the instance is saved (not only when it was added in django admin panel).
You need to use the Django model post_save signals to achieve this. This signal receiver can be placed in the same place where the model is
class FCMDevice(models.Model):
...
#receiver(post_save, sender=FCMDevice)
def notify_users(sender, instance, **kwargs):
# your logic goes here
# instance is referred to currently inserted row
pass
You might wanna check post_save signal. From the docs:
Like pre_save, but sent at the end of the save() method.
url: https://docs.djangoproject.com/en/2.1/ref/signals/#post-save
django-version: 1.7+

notify user if similar model created _Django

I have a model.that I need to if any model with specific field created in database.send a Email to user for notify.I did some search too many apps are there for handling the notify. thats not my concern .I dont know how deploy this structure.any guide or example for this.for example :
if x = book.objects.create(title="book1") :
print("the book created")
if this action happend do something.
If you need to monitor object creation globally the best thing to use is signals
Like so:
from .models import Book
from django.db.models.signals import post_save
def book_created(sender, instance, created, **kwargs):
if created and instance.title == 'book1':
#logic here
post_save.connect(save_profile, sender=Book)
you need to stick that post_save.connect() function somewhere where it will be evaluated when the app is run, you can use app_dir/app.py for instance.

How to Create A User Model Only Including Username in Django?

Well, this is a bit complicated, but let me explain myself. I want to create a RESTful service. This service will contain users, but not in a classic way.
I want to create users based on random hashes, I will use uuid to do that. And the most important thing is that I will not need username, password, email or full_name (?). This type of user will authenticate via a GET parameter on a view, only using its username, not anything else.
I read some articles on extending Django user, yet I couldn't find satisfying explanation especially for this case.
Further Explanations
Now, I can hear questions like "Why would anyone ever need especially passwordless User model, and especially thinking that it is quite insecure.". So, this part is especially for the ones who needs a logical explanation to understand such a request.
In service, I want to have three group of users:
anonymous users: the ones who do request some data on server
uuid users: the ones who have a unique id. Why do I need this type? Because I want to track those users' requests and response special data for them. These kind of users will also be removed if they are inactive for specific several days. I think I can do it by cron jobs.
admin: This is me, reaching admin panel. That is all.
I think this explains enough.
Environment
django 1.9.5
python 3.5.1
Django supports multiple backend authentications. As Luis Masuelli suggested you can extend the model to add more fields. But in your scenario, specifically you want to implement a custom authentication method. I woudl go about treating uuid as username and setting password as None.
So, in my settings.py:
AUTH_USER_MODEL = 'app_name.MyUUIDModel'
# REMOVE ALL PASSWORD Validators
In my app_name/models.py:
from django.contrib.auth.models import BaseUserManager
class MyUUIDManager(BaseUserManager):
def create_user(self, uuid):
user = self.model(
uuid=self.normalize_email(email),
)
user.set_password(None)
user.save(using=self._db)
return user
def create_superuser(self, uuid):
user = self.create_user(uuid)
user.save(using=self._db)
return user
def get_by_natural_key(self, email):
return self.get(**{self.model.USERNAME_FIELD: email})
class MyUUIDModel(AbstractBaseUser):
uuid = models.CharField(max_length=36, unique=True)
USERNAME_FIELD = 'uuid'
objects = UUIDModelManager()
def save(self, *args, **kwargs):
super(MyUUIDModel, self).save(*args, **kwargs)
At this point, if you run createuser or createsuperuser Django command, you may be able to create the user. The next bit is where the authentication needs to be done. You can simply check if the UUID exists in your DB and return true when authenticate() is called from the view.
Add authentication backend in the settings.py file:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'app_name.auth.MyBackend'
]
Create a file app_name/auth.py with contents SIMILAR to below:
class MyBackend(object):
def authenticate(self, username=None, password=None):
# Check if username i.e. UUID exists
try:
my_uuid = MyUUIDModel.objects.get(uuid=username)
except MyUUIDModel.DoesNotExist:
return None
return my_uuid
More more details refer to: https://docs.djangoproject.com/en/1.9/topics/auth/customizing/

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)

Google App Engine (Python) : use UserProperty with Webapp2 User Model

i have an application where we allow users to use Oauth2 for authentication and even Custom User Registrations. All the Users are saved into the default User entity in the datastore. If the user is logging in using Oauth2 for the first time a new record in the default User entity is created like this:
"""Check if user is already logged in"""
if self.logged_in:
logging.info('User Already Logged In. Updating User Login Information')
u = self.current_user
u.auth_ids.append(auth_id)
u.populate(**self._to_user_model_attrs(data, self.USER_ATTRS[provider]))
u.put()
else:
"""Create a New User"""
logging.info('Creating a New User')
ok, user = self.auth.store.user_model.create_user(auth_id, **self._to_user_model_attrs(data, self.USER_ATTRS[provider]))
if ok:
self.auth.set_session(
self.auth.store.user_to_dict(user)
)
self.redirect(continue_url)
for custom registrations records are inserted through the following handler.
class RegistrationHandler(TemplateHandler, SimpleAuthHandler):
def get(self):
self.render('register.html')
def post(self):
"""Process registration form."""
user = 'appname:%s' % self.request.get('email')
name = '%s %s' % (self.request.get('first_name'), self.request.get('last_name'))
password = self.request.get('password')
avatar = self.request.get('avatar')
act_url = user_activation.Activate(self.request.get('first_name'), self.request.get('email'))
ok, user = User.create_user(auth_id=user, name=name, password_raw=password, email=self.request.get('email'))
if ok:
self.auth.set_session(self.auth.store.user_to_dict(user))
acc = models.Account(display_name=self.request.get('first_name'), act_url=act_url, act_key=act_url.split('activate/')[1], user=users.User(User.get_by_auth_id(self.current_user.auth_ids[0]).email))
acc.put()
if avatar:
avt = models.Picture(is_avatar=True, is_approved=True, image=avatar, user=users.User(User.get_by_auth_id(self.current_user.auth_ids[0]).email))
avt.put()
self.redirect('/')
Now we are using webapp2_extras.sessions for session handling. We have different models like, Comments, Images, Reviews etc in which we want to use db.UserProperty() as the author field. However, the author field shows blank or None whenever we enter a record into any of these models using 'users.get_current_user()'. I think this is because we are handling the sessions through webapp2 sessions.
What we want to achieve is to be able to use the db.UserProperty field in various models and link appropriately to the current user using webapp2 sessions ?
the UserProperty() has to be passed with a User Object in order for it to properly insert the records. Even though we are able to enter the records using the following code :
user = users.User(User.get_by_auth_id(self.current_user.auth_ids[0]).email)
or
user = users.User(User.get_by_auth_id(self.current_user.auth_ids[0]).name)
but then we are not able to get the whole user object by referencing to model.author
Any ideas how we should achieve this ?
OAuth 2.0 is not currently supported by Users service. Supported options are
Google Accounts
OpenId
OAuth 1.0
I don't frankly understand what you're trying to accomplish with introducing db.User in to the codebase. Given there's self.current_user, I assume you're already handling authentication process.
When you do self.auth.store.user_model.create_user - that already gives you a webapp2's user object/entity (it has nothing to do with db.User though). I believe that's what you'll have to use as your author field given OAuth 2.0 constraint.
users.get_current_user() relies on a special cookie (App Engine internal). In fact, it has nothing to do with webapp2's session (or any other "custom" session for that matter). You could hack it by setting the cookie to a value that App Engine internals can understand and be tricked as if a user were logged in with one of the methods I mentioned, but I wouldn't recommend this approach. It is not documented (cookie name, format, etc.) and might be changed at any time.
Instead of using UserProperty to store references to the webapp2 user objects, you should instead store the auth_id as a StringProperty and add a convenience method for fetching the corresponding webapp2 user entity.
Something like this
from webapp2_extras.appengine.auth.models import User
class Comment(db.model):
text = db.StringProperty()
author = db.StringProperty()
def get_author(self):
return User.get_by_auth_id(self.author)

Categories

Resources