I have my legacy database.I created models using inspectdb.I am able to see my tables in admin page . I created 4 users and i want to implement role-based permission for each model. I just show you with example what i did in model to add permissions like edit, view, delete.
Example:-
class BusinessIntegrationSourceCategory(models.Model):
date_added = models.DateTimeField(blank=True, null=True)
date_modified = models.DateTimeField(blank=True, null=True)
source_category = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'business_integration_source_category'
permissions = (
("view_category", "view category"),
("add_category", "Add category"),
("delete_category", "Delete category"),
)
Now where i can add the next steps to add role based permissions.
This from The Django docs.
Handling object permissions
Django’s permission framework has a foundation for object permissions,
though there is no implementation for it in the core. That means that
checking for object permissions will always return False or an empty
list (depending on the check performed). An authentication backend
will receive the keyword parameters obj and user_obj for each object
related authorization method and can return the object level
permission as appropriate.
So as said: An authentication backend will receive the keyword parameters obj and user_obj.
And these tow variables are the seeds of object level permissions, but the default backend django.contrib.auth.backends.ModelBackend does not take advantage of that. So you should create a custom backend.
Note:
If you use custom User model, your user model should subclass PermissionsMixin, because The has_perm method of PermissionsMixin passes the work off to the registered authentication backends.
Try:
backends.py file:
from django.contrib.auth import get_user_model
class MyAuthenticationBackend:
def authenticate(self, *args, **kwargs):
pass
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
def has_perm(self, user_obj, perm, obj=None):
if perm == "view_category":
return True # everybody can view
# otherwise only the owner or the superuser can delete
return user_obj.is_active and obj.user.pk==user_obj.pk
def has_perms(self, user_obj, perm_list, obj=None):
return all(self.has_perm(user_obj, perm, obj) for perm in perm_list)
In settings.py file add:
AUTHENTICATION_BACKENDS = [
'your_app.backends.MyAuthenticationBackend',
# Your other auth backends, if you were using the default,
# then comment out the next line, otherwise specify yours
# 'django.contrib.auth.backends.ModelBackend'
]
Note: every model already has default permissions (add, change and delete)
I hope this will push you forward.
Related
I'm making a simple real estate app where the users must be separated into two different groups. A regular user and a broker. I'm using the Django admin backend for creating user groups. I'm also using a post_save signal to assign all the new users to the regular users' group. At first glance, it works well and in Django admin, it shows me that the user is in the corresponding group. But when I try to print self.request.user.groups the value is None. Also when I try to check if users have permission to do something, regardless of the permissions I gave the view I check always gives me 403 Forbidden regardless of whether the user has permission or not. I use class-based views and PermissionRequiredMixin respectively.
Here is my user model:
class DjangoEstatesUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
USERNAME_MAX_LENGTH = 30
username = models.CharField(
max_length=USERNAME_MAX_LENGTH,
unique=True,
)
date_joined = models.DateTimeField(
auto_now_add=True,
)
is_staff = models.BooleanField(
default=False,
)
USERNAME_FIELD = 'username'
objects = DjangoEstatesUserManager()
Also the signal for assigning the new users to a group:
#receiver(post_save, sender=DjangoEstatesUser)
def create_user_profile(sender, instance, created, **kwargs):
if created:
instance.groups.add(Group.objects.get(name='Users'))
and this is one view that I'm trying to restrict for different users:
class AddEstateView(auth_mixins.LoginRequiredMixin, auth_mixins.PermissionRequiredMixin, views.CreateView):
permission_required = 'auth_permission.add_estate'
template_name = 'main/estates/add_estate.html'
form_class = AddEstateForm
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def get_success_url(self):
return reverse_lazy('profile details', kwargs={'pk': self.object.user_id})
And these are the groups with the permissions.
brokers_group
and
users_group.
And these are my
db_tables
and auth_permission_table.
I can't figure out where I'm wrong or what I'm not doing right, any help will be appreciated!
Thank you in advance!
self.request.user.groups prints always None: that is a RelatedManager [Django-doc], not a QuerySet. Managers will print the model name with None, so for a Model named ModelName in app_name, it prints:
app_name.ModelName.None
You print the items with self.request.user.groups.all():
print(self.request.user.groups.all())
In django-rest-framework-simplejwt plugin username and password are used by default. But I wanted to use email instead of username. So, I did like below:
In serializer:
class MyTokenObtainSerializer(Serializer):
username_field = User.EMAIL_FIELD
def __init__(self, *args, **kwargs):
super(MyTokenObtainSerializer, self).__init__(*args, **kwargs)
self.fields[self.username_field] = CharField()
self.fields['password'] = PasswordField()
def validate(self, attrs):
# self.user = authenticate(**{
# self.username_field: attrs[self.username_field],
# 'password': attrs['password'],
# })
self.user = User.objects.filter(email=attrs[self.username_field]).first()
print(self.user)
if not self.user:
raise ValidationError('The user is not valid.')
if self.user:
if not self.user.check_password(attrs['password']):
raise ValidationError('Incorrect credentials.')
print(self.user)
# Prior to Django 1.10, inactive users could be authenticated with the
# default `ModelBackend`. As of Django 1.10, the `ModelBackend`
# prevents inactive users from authenticating. App designers can still
# allow inactive users to authenticate by opting for the new
# `AllowAllUsersModelBackend`. However, we explicitly prevent inactive
# users from authenticating to enforce a reasonable policy and provide
# sensible backwards compatibility with older Django versions.
if self.user is None or not self.user.is_active:
raise ValidationError('No active account found with the given credentials')
return {}
#classmethod
def get_token(cls, user):
raise NotImplemented(
'Must implement `get_token` method for `MyTokenObtainSerializer` subclasses')
class MyTokenObtainPairSerializer(MyTokenObtainSerializer):
#classmethod
def get_token(cls, user):
return RefreshToken.for_user(user)
def validate(self, attrs):
data = super(MyTokenObtainPairSerializer, self).validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = text_type(refresh)
data['access'] = text_type(refresh.access_token)
return data
In view:
class MyTokenObtainPairView(TokenObtainPairView):
"""
Takes a set of user credentials and returns an access and refresh JSON web
token pair to prove the authentication of those credentials.
"""
serializer_class = MyTokenObtainPairSerializer
And it works!!
Now my question is, how can I do it more efficiently? Can anyone give suggestion on this? Thanks in advance.
This answer is for future readers and therefore contains extra information.
In order to simplify the authentication backend, you have multiple classes to hook into. I would suggest to do option 1 (and optionally option 3, a simplified version of yours) below. Couple of notes before you read on:
Note 1: django does not enforce email as required or being unique on user creation (you can override this, but it's off-topic)! Option 3 (your implementation) might therefore give you issues with duplicate emails.
Note 1b: use User.objects.filter(email__iexact=...) to match the emails in a case insensitive way.
Note 1c: use get_user_model() in case you replace the default user model in future, this really is a life-saver for beginners!
Note 2: avoid printing the user to console. You might be printing sensitive data.
As for the 3 options:
Adjust django authentication backend with f.e. class EmailModelBackend(ModelBackend) and replace authenticate function.
Does not adjust token claims
Not dependent on JWT class/middleware (SimpleJWT, JWT or others)
Also adjusts other authentication types (Session/Cookie/non-API auth, etc.)
The required input parameter is still username, example below. Adjust if you dont like it, but do so with care. (Might break your imports/plugins and is not required!)
Replace django authenticate(username=, password=, **kwarg) from django.contrib.auth
Does not adjust token claims
You need to replace token backend as well, since it should use a different authentication, as you did above.
Does not adjust other apps using authenticate(...), only replaces JWT auth (if you set it up as such)
parameters is not required and therefore this option is less adviced).
Implement MyTokenObtainPairSerializer with email as claim.
Now email is sent back as JWT data (and not id).
Together with option 1, your app authentication has become username agnostic.
Option 1 (note that this also allows username!!):
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class EmailorUsernameModelBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username))
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
Option 2:
Skipped, left to reader and not adviced.
Option 3:
You seem to have this covered above.
Note: you dont have to define MyTokenObtainPairView, you can use TokenObtainPairView(serializer_class=MyTokenObtainPairSerializer).as_view() in your urls.py. Small simplification which overrides the used token serializer.
Note 2: You can specify the identifying claim and the added data in your settings.py (or settings file) to use email as well. This will make your frontend app use the email for the claim as well (instead of default user.id)
SIMPLE_JWT = {
'USER_ID_FIELD': 'id', # model property to attempt claims for
'USER_ID_CLAIM': 'user_id', # actual keyword in token data
}
However, heed the uniqueness warnings given by the creators:
For example, specifying a "username" or "email" field would be a poor choice since an account's username or email might change depending on how account management in a given service is designed.
If you can guarantee uniqueness, you are all set.
Why did you copy and paste so much instead of subclassing? I got it to work with:
# serializers.py
from rest_framework_simplejwt.serializers import TokenObtainSerializer
class EmailTokenObtainSerializer(TokenObtainSerializer):
username_field = User.EMAIL_FIELD
class CustomTokenObtainPairSerializer(EmailTokenObtainSerializer):
#classmethod
def get_token(cls, user):
return RefreshToken.for_user(user)
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data["refresh"] = str(refresh)
data["access"] = str(refresh.access_token)
return data
And
# views.py
from rest_framework_simplejwt.views import TokenObtainPairView
class EmailTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
And of course
#urls.py
from rest_framework_simplejwt.views import TokenRefreshView
from .views import EmailTokenObtainPairView
url("token/", EmailTokenObtainPairView.as_view(), name="token_obtain_pair"),
url("refresh/", TokenRefreshView.as_view(), name="token_refresh"),
The question has been a while but, I add +1 for #Mic's answer. By the way, wasn't it sufficient to update to TokenObtainPairSerializer only as following?:
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.serializers import (
TokenObtainPairSerializer, User
)
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
username_field = User.EMAIL_FIELD
class EmailTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
Let summarize the above solutions:
1- Create two app by Django command. One for the new token and the other for the user:
python manage.py startapp m_token # modified token
python manage.py startapp m_user # modified user
2- In the m_token, create the serializers.py and override the serializer to replace username with email field:
# serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, User
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
username_field = User.EMAIL_FIELD
3- In the m_token, override the view to replace the serializer with the new one:
# views.py
from rest_framework_simplejwt.views import TokenObtainPairView
from .serializer import CustomTokenObtainPairSerializer
class EmailTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
4- In the m_token, create the urls.py and give the paths as follows:
# urls.py
from django.urls import path
from .views import TokenObtainPairView
from rest_framework_simplejwt.views import TokenRefreshView, TokenVerifyView
urlpatterns = [
path(r'token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path(r'token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path(r'token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
5- In the m_user, override the user model as follows:
# models.py
from django.contrib.auth.models import AbstractUser
class MUser(AbstractUser):
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['username']
6- In the django project root, add AUTH_USER_MODEL = 'm_user.MUser' to setting.py.
I tested it in my project and it worked perfectly. I hope I did not miss anything. This way the swagger also shows "email" instead of "username" in the token parameters:
And in addition to #Mic's answer, remember to set USERNAME_FIELD = 'email' and may be REQUIRED_FIELDS = ['username'] in the User model.
For those using a custom User model, you simply can add those lines:
class User(AbstractUser):
...
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
Then, in urls.py:
from rest_framework_simplejwt.views import TokenObtainPairView
urlpatterns = [
...
path('api/login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
Using this code you can allow users to login using either username or email in the username field. You can add some lines to validate the email.
class TokenPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
raw_username = attrs["username"]
users = User.objects.filter(email=raw_username)
if(users):
attrs['username'] = users.first().username
# else:
# raise serializers.ValidationError("Only email is allowed!")
data = super(TokenPairSerializer, self).validate(attrs)
return data
In "wagtail_hooks.py" I have the code below. As wagtail admin I can see the StudentModelAdmin, but as a user with restricted access to the admin interface I can't.
I would like to allow users with wagtail admin access and the specific permission below to access the student model admin. How do I go about creating the "CourseRegisterPermission" class?
from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register)
from wagtail.wagtailcore import hooks
from .models import Participant
#hooks.register('register_permissions')
def view_course_registrations():
return Permission.objects.filter(codename="view_course_registrations")
class CourseRegisterPermission(PermissionHelper):
# how do I allow users with the permission to view course registrations
# to see the 'StudentModelAdmin" below?
class StudentModelAdmin(ModelAdmin):
model = Participant
menu_label = "Student Registrations"
menu_icon = "group"
search_fields = ('name', 'supervisor_name')
list_display = ('name', 'email')
list_filter = ('course',)
permission_helper_class = CourseRegisterPermission
I tried to find some examples of wagtail PermissionHelper but wasn't able to find any.
Any hint would be appreciated!
You can use the wagtail.contrib.modeladmin.helpers.PermissionHelper or wagtail.contrib.modeladmin.helpers.PagePermissionHelper permission helper classes from Wagtail's sources as an example. See methods like user_can_list, user_can_create, etc.
But... Are you sure that you need to define your own permission helper class? It seems to me that you can just create a new (or edit existing) group in the Wagtail admin and give required object permissions to your Participant model.
On my screenshot Programme is the model that I manage using ModelAdmin.
You can override some functions inside CourseRegisterPermission
class CourseRegisterPermission(PermissionHelper):
def user_can_list(self, user):
"""
Return a boolean to indicate whether `user` is permitted to access the
list view for self.model
"""
# this is just an example
return user.role == "driver"
def user_can_delete_obj(self, user, obj):
"""
Return a boolean to indicate whether `user` is permitted to 'delete'
a specific `self.model` instance.
"""
perm_codename = self.get_perm_codename('delete')
if obj.status > 0:
return False
if not self.user_has_specific_permission(user, perm_codename):
return False
if user.id == obj.id:
# users may not delete themselves
return False
You can also override the following functions:
def user_can_list(self, user):
def user_can_create(self, user):
def user_can_inspect_obj(self, user, obj):
def user_can_edit_obj(self, user, obj):
def user_can_delete_obj(self, user, obj):
def user_can_unpublish_obj(self, user, obj):
def user_can_copy_obj(self, user, obj):
I am using Django 1.9. When I tried to add PermissionRequiredMixin to my class-based-view, it seems not to work as expected. I created a new user in a auth_group. This auth_group doesn't have any permission to any apps or models. This new user is not a superuser or admin user. But the app doesn't prevent this user from accessing to a particular view that needs permission_required.
Firstly, here is what I tried to make sure the user doesn't have permission:
user.get_all_permissions() # return set() - empty permission, which is correct.
user.is_superuser # return false, which is correct.
user.has_perm('myapp.add_something or even any words that make no sense') # always return true, which is very weird.
The app has custom user model and also uses django-allauth as the AUTHENTICATION_BACKENDS. I am not sure if PermissionRequiredMixin will check user.has_perm() and it always return true so that's why checking permission doesn't work as expected?
# views.py
class My_View(PermissionRequiredMixin, View):
permission_required = 'polls.can_vote'
def get(self, request, *args, **kwargs):
# do something...
return render(request, "template.html", {})
# models.py - Custom User Model
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
group = models.ManyToManyField(Group, through='UserGroupRelationship')
....
# models.py - many-to-many relationship between user and group
class UserGroupRelationship(models.Model):
user = models.ForeignKey("CustomUser")
user_group = models.ForeignKey(Group)
I also tried the old way to check permission in urls.py. It doesn't prevent user accessing either so I do not think that's the problem of using PermissionRequiredMixin.
urlpatterns = patterns('',
(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
)
After spending a few days on this problem, I eventually find out the cause.
When I looked into the source code about PermissionRequiredMixin, I found that PermissionRequiredMixin indeed checks user.has_perm(). When I tried to find the source code of has_perm(), I found that my codes (which is copied from the custom user model example from Django's document) contains the following overridden method...
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
That's reason why user.has_perm('anything') always return true, which also affects the functionality of PermissionRequiredMixin. Therefore, if you are new to Django and try to copy some example codes from document, you need to be very careful about each line...
I've created a User model for my django app
class User(Model):
"""
The Authentication model. This contains the user type. Both Customer and
Business models refer back to this model.
"""
email = EmailField(unique=True)
name = CharField(max_length=50)
passwd = CharField(max_length=76)
user_type = CharField(max_length=10, choices=USER_TYPES)
created_on = DateTimeField(auto_now_add=True)
last_login = DateTimeField(auto_now=True)
def __unicode__(self):
return self.email
def save(self, *args, **kw):
# If this is a new account then encrypt the password.
# Lets not re-encrypt it everytime we save.
if not self.created_on:
self.passwd = sha256_crypt.encrypt(self.passwd)
super(User, self).save(*args, **kw)
I've also created an authentication middleware to use this model.
from accounts.models import User
from passlib.hash import sha256_crypt
class WaitformeAuthBackend(object):
"""
Authentication backend fo waitforme
"""
def authenticate(self, email=None, password=None):
print 'authenticating : ', email
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
user = None
if user and sha256_crypt.verify(password, user.passwd):
return user
else:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
I have ammended the settings.py file correctly and if I add some print statements to this backend I can see the user details print out. I don't recall reading that I need to implement is_authenticated in the django docs. Am I missing something silly?
I'm not quite sure why you have created a new User model instead of using Django's built-in one and adding a linked UserProfile, which is the recommended thing to do (until 1.5 is released, when pluggable user models will be available). However, yes you need to define an is_authenticated method, which always returns True: this is exactly what the built-in model does. The reason is that if you have an actual User, it will always be authenticated: otherwise, you will have an AnonymousUser object, whose is_authenticated method always returns False.
you dont have to reinvent the wheel. Just use Djangos build in authentication system and save yourself a lot of trouble. You can also extend it to your needs or use different authentication backends. Have a read here. HTH.