django auth ldap with custom user model - python

I'm trying to use django auth ldap (v1.1.7) with a custom user model and, while I have everything else taken care of, I still run into a familiar error message that I just don't know how to fix.
Running python manage.py syncdb returns:
CommandError: One or more models did not validate:
django_auth_ldap.testprofile: 'user' defines a relation with the model 'auth.Use
r', which has been swapped out. Update the relation to point at settings.AUTH_US
ER_MODEL.
My question here is - where can I find django_auth_ldap.testprofile and update the relation, to fix the issue?
Thanks in advance for helping me out.
L.E.: Ok, after a little googleing, i found out that this testprofile is located in django_auth_ldap/models.py and get this: I searched through all of my files and found the file, modified it to point to settings.AUTH_USER_MODEL and still I receive the same error.
Can anyone please help me out with this issue?

This is the part of django_auth_ldap's models.py -
class TestProfile(models.Model):
"""
A user profile model for use by unit tests. This has nothing to do with the
authentication backend itself.
"""
user = models.OneToOneField('auth.User') # <-- here is the trouble
is_special = models.BooleanField(default=False)
populated = models.BooleanField(default=False)
You cannot fix it unless you fix this part of the code and do as said in Django documentation -
Instead of referring to User directly, you should reference the user
model using django.contrib.auth.get_user_model(). This method will
return the currently active User model – the custom User model if one
is specified, or User otherwise.
And I wont recommend modifying the 3rd party packages yourself. If you can, go suggest the change to the developer, or send them a pull request. Once it's accepted, update the package.

Related

Django: Random ManyToMany relation is added on User connect

Strangest bug I ever encountered
User model is the regular one from conrtib.auth.User
Let's say I have the following model:
class Region(model.Model):
name = models.CharField(max_length=256)
rakazim = models.ManyToManyField(settings.AUTH_USER_MODEL)
goal = models.IntegerField(default=0)
and someplace else I have:
user_model = get_user_model()
rakaz = user_model.objects.create_user(username, email, password)
Then Immediately after the user creation method is called the "rakaz" instance has a random region connected
rakaz.region_set.all() = [<random_region>]
It also sometimes connects to another model that has a similar ManyToManyField to AUTH_USER_MODEL
I debugged with pdb into the user creation method (in auth contrib) and immediately after calling save inside this happens.
AFAIK it happens only on the staging server, but until I find the reason I'm afraid to deploy to prod..
Django version 1.84. server using mariabdb on RDS
I don't use signals in my code (and at all :) ) and can't find relevant third party code doing this, (And if so it would happen on my machine also)
Any Ideas?
The issue turned out to be:
I seeded the staging server with data from prod for "region" the dumpdata command dumps the region with foreign keys for rakazim . But since the users where actually missing (I didn't copy the users from my prod environment) Instead of shouting at me, and not allowing me to loaddata with non existing foreign keys, mariadb chose to give me :+1 and add random foreign keys each time I created a user (Perhaps not random, but according to the imported mapping, not sure).
Lesson learned: use a proper DBMS and not a mysql varient.

Adding custom attributes to django scheema

I am trying to authenticate my django application written in python with okta IDP. I have almost configured everything at SP side and IDP side too. Now I need to pass a custom variable from IDP which assert SP that user is a publisher,editor or admin and further save this to the django format database (in auth_user_groups table). Anyone have tried doing this, or anyone has idea about this?
I am able to get the custom variable values by attributes mappings from IDP. But this allows me to save the custom attributes only on the user table. please let me know if i have not made myself clear here about my question.
Once again I have a privilege to answer my own question. So hear is the solution.
Django has a user profile module which is to be turned on by giving the module location in the settings.py
i.e -
"AUTH_PROFILE_MODULE = appTitle.UserProfile"
The UserProfile needs to be specified in modules.py specifying the required structure of user profile u need for your app.
Now doing sync -db django creates the Database table for your user profile and further on the same user profile pysaml adds the value (CustomAttribute) which come on the saml Assertion.
more explanations on this can be found on django documentations too.
If any one still faces any issue please let me know.

Unable to login after using Custom django models

I have configured OTP with my app. And after putting otp_required decorator on desired method i am redirecting to /account/login.
This is the default login page that comes with two_factor auth. After providing correct username(email) and password it returns an error.
IMPORTANT:
How i can check i have configured custom user models properly. what are the ways to test it out or where i am going wrong with the configurations.
i have followed this documentation
Please let me know if you required any thing further. Thanks!
This might help
To check you have configured custom user properly you can do the following.
Try to run django's create super user command to check either it is entering in desired table or not(python manage.py createsuperuser)
Try to check if you don't have any custom password hashing techniques for your custom user.
Saver approach is to create your own authentication backend. See the docs
AUTH_USER_MODEL = 'customauth.MyUser' , this is the configuration needed for the custom user model.
However if you need to refer User model in your apps after configuring the custom user model, you have to user get_user_model function. All third party apps you used also needs to follow this.
However you should reference the User model with the AUTH_USER_MODEL setting in code that is executed at import time. get_user_model() only works once Django has imported all models.
About the error you are facing , can you provide the stack trace of the error ?

Django Registration with Custom User Model

So I am using a custom user model accounts.player and i'm also using django-registration in my project.
With the custom model it now encounters an error. I know I could just write my own registration code but is there a way to use the custom model class with django-registration. I had a look on the docs but didn't really find a solution.
I'm sure theres probably a way using something like a subclass but i'm not sure how to implement this.
What files are required and what code would I need??
This is what I did for a personal project of mine:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name = 'MoreAboutUser', unique=True)
age = ....
gender = ....
Regarding your error, I don't know how to help you since you didn't provide any traceback/code. But you can connect your custom model with the User model with a OneToOneFiel'
You could either Fork django-registration and make changes to Make it work with Custom User model... But that would be a long process...
Or
You could switch to django-allauth , which is a better and well maintained Registration app for Django.
It is compatible with Latest django version and also provides social registration out of the box

django-guardian custom user permissions

Setup
I've just started working with django-guardian and have straight away run into some obstacles. I'm using custom users by extending the AbstractBaseUser class. I followed this example to setup my models.py and admin.py. I also followed the developers guide configuration guide to setup guardian.
Problem
django-guardian throws a AttributeError: type object 'MyCustomUser' has no attribute 'groups' error (MyCustomUser is my custom user class) whenever I try to get permissions pertaining to a user i.e. when I add a permission, it goes straight into the guardian_userobjectpermission table, like it should. However, calls to get_perms throw the mentioned error.
The same error appears while trying to edit permissions via the admin page. (progmatically added permissions don't show up here. :/) I wrote a small manage.py task to test it:
class Command(BaseCommand):
def handle(self, *args, **options):
user1 = MyCustomUser.objects.filter(username='pankaj')[0]
checker = ObjectPermissionChecker(user1)
# model on which permissions are applied
stream = Stream.objects.filter(uuid='001')[0]
# works on the database level, doesn't show up on admin page
assign_perm('read_stream', user1, stream)
# error
print 'read_stream' in get_perms(user1, stream)
# error
print checker.has_perm('read_stream', stream)
# error
print checker.get_perms(stream)
# works on the database level, doesn't show up on admin page
remove_perm('read_stream', user, stream)
# ALWAYS returns True, irrespective of whether permission granted or not
print user.has_perm('read_stream', stream)
Possible Solution
There might be a problem with setting up the authentication backend. I currently have it set to:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
Maybe implementing a custom user => changing/implementing custom groups? Currently I have admin.site.unregister(Group) in admin.py, but changing it doesn't help.
As the developer has warned, guardian might not be compatible with custom users?
According to django-guardian documentations here. Gaurdian was depending heavily on the old fashion of django user model. But you can get through it, if you extend AbstractUser model, or defined ManyToMany relation with auth.Group could groups in your authentication model.
django-guardian relies heavily on the auth.User model. Specifically it was build from the ground-up with relation beteen auth.User and auth.Group models. Retaining this relation is crucial for guardian - without many to many User (custom or default) and auth.Group relation django-guardian will BREAK.

Categories