Why Django auto adds permissions to group? - django

Currently I'm making some groups for my backend and I noticed through the admin panel that the groups have some extra permissions I did not add. What is the cause of this behavior?
models.py:
produccion_group, created = Group.objects.get_or_create(name="Produccion y cuentas")
produccion_group.permissions.add(
Permission.objects.get(codename='add_brand'),
Permission.objects.get(codename='change_brand'),
Permission.objects.get(codename='view_brand'),
Permission.objects.get(codename='add_expense'),
Permission.objects.get(codename='change_expense'),
Permission.objects.get(codename='view_expense'),
)
produccion_group.save()
Admin panel:

The problem is solved by adding the following block of code. Still doesn't answer the incognita of why it's added automatically, but fixes the unwanted permissions.
def ready(self):
produccion_group.permissions.remove(
Permission.objects.get(codename='add_user'),
Permission.objects.get(codename='change_user'),
Permission.objects.get(codename='delete_user'),
Permission.objects.get(codename='view_user'),
Permission.objects.get(codename='add_group'),
Permission.objects.get(codename='change_group'),
Permission.objects.get(codename='delete_group'),
Permission.objects.get(codename='view_group'),
)
produccion_group.save()

Related

Is Viewflow for superusers only?

I'm learning django viewflow (non-Pro) and the all processes that I've been creating works for superuser users only
Is that normal?
Thanks, José.-
Edit 2: My specific problem is that my user can start the process, but he can't continue it (can't see the "otro_paso" task. See the code below), only if he's not superuser. When I cnange him to superuser, works.. why??
Edit 1: I'm using django-material auto-generated forms
A way to make it work is implementing custom views, making the permission validation programmatically
Edit 3:
Here's the flows.py part:
#frontend.register
class Flujo_Proceso_Recursos_fisicos(Flow):
process_class = Proceso_Recursos_fisicos
process_title = 'Recursos físicos'
process_description = 'Registro de recursos físicos'
inicio = flow.Start(
CreateProcessView,
fields=['anio'],
task_title='Iniciar'
).Available(
username='jose'
).Permission(
'helloworld.puede_participar_biblioteca'
).Next(this.otro_paso)
otro_paso = flow.View(
UpdateProcessView,
fields=['campus'],
task_title='Campus',
task_description= "Completar campus",
).Permission(
'helloworld.puede_participar_biblioteca'
).Assign(
username='jose'
).Next(this.fin)
fin = flow.End(
task_title='Finalizado',
)
To make a task available for a user, you need to auto-assign it with flow.View(..).Assign(...) or provide permission that would make this task available for a user - flow.View(..).Permission(..)
For the reference, you can check the demos
https://github.com/viewflow/viewflow/blob/master/demo/helloworld/flows.py#L42
https://github.com/viewflow/viewflow/blob/master/demo/shipment/flows.py#L28

How to check if currently logged in user is admin or not

How can I check in sitecore that the current user is an administrator?
something like:
if(User.Current.Name == "extranet\Admin")
// then do some thing ??
Sitecore.Security.Accounts.User class has built in property IsAdministrator:
Sitecore.Context.User.IsAdministrator
You can actually just call Sitecore.Context.IsAdministrator
This should do what you wanted:
Sitecore.Context.User.IsInRole("extranet\admin")
You can try this code :
var result = Sitecore.Context.User.IsAdministrator;
If admin is logged in result is true, otherwise result is false.
A remark \ is a escape in c# use "extranet\\Admin" and the CMS admin is sitecore\admin
I assum you need to know your extranet admin. it's a good idea to do role-based, there can be multiple admin's (not sure if the IsAdministrator property is good working for a extranet)
Sitecore.Context.User.IsInRole("extranet\\your extranet admin rol");
If you do not have a Extranet admin rol and don't want it, then you can use what you already have if (Sitecore.Context.User.Name == "extranet\\Admin")

Django 1.7 - Adding permissions programmatically does not work as expected

What is going on here ?
> from django.contrib.auth.models import Permission
> from django.contrib.contenttypes.models import ContentType
> p = Permission.objects.filter(
content_type = ContentType.objects.get_for_model(Transaction)
).get(
codename = 'add_transaction'
)
> user.user_permissions.add(p)
> user.user_permissions.all()
[<Permission: myapp | Transaction | Can add Transaction>]
> user.get_all_permissions()
set([])
> user.has_perm('add_transaction')
False
> user.has_perm('myapp.add_transaction')
False
am i missing a save here somewhere ?
The ModelBackend caches the permissions on the user object. The Django docs suggest that you reload the user from the db after changing the permissions.
user.user_permissions.add(p)
user = User.objects.get(pk=user.pk)
dgel's answer is correct but incomplete. Both _perm_cache and _user_perm_cache need to be cleared to force a full reload.
for attr in ('_perm_cache', '_user_perm_cache'):
delattr(user, attr)
I believe user instances have a permissions cache that is populated when it is first pulled from the DB. Try deleting the cache before calling has_perm:
delattr(user, '_perm_cache')
After that, has_perm should work as expected. Normally this isn't an issue as you rarely add then immediately test for permissions on the same user instance (without pulling it from the DB again). Definitely can trip you up when you're testing in the python shell though.

how to set the default permission name created in Django?

I'm using django 1.6
Now when I define a model, it will create three permissions record for it (can_create, can_update, can_delete).
I'm now adding other permissions on the models (which doesn't matter in this question), and want to make a view to let the user assign them all to users and groups.
Now the problem is:
I want to replace the default name displayed for the three default created permissions.
Is there any way to do this?
Yes there is possibility to create custom permission while creating the models/table in django. But this will create the extra custom permission, by default 3 permission will create i.e( add, change, delete). One can create custom permission by following thing.
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)
The only thing this does is create those extra permissions when you run manage.py migrate (the function that creates permissions is connected to the post_migrate signal). Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:
user.has_perm('app.view_task')
One can see the django doc here django permission description
Based on this blog post and this Django ticket, I would say it is not possible and also not advisable to change these codenames (since they are used in the admin). It is however possible to change the human readable name (such as 'Can add permission')
I cannot add comment to the answers already there, hence adding a new answer.
I have been looking for a solution and could not find any. So I just make use of default permissions and use permissions to re-create them and use whatever name and codename you want. Django documentation here
class Foo(models.Model):
title = models.CharField(max_length=250)
class Meta:
default_permissions = ()
permissions = (
("add_foo", "Can add foo"),
("change_foo", "Can change foo"),
("delete_foo", "Can delete foo"),
("view_foo", "Can view foo"),
("list_foo", "Can list all foo")
)

How to find user group and use of caching in django?

I am new to django/python and working my way through my webapp. I need assistance in solving one of my problems.
In my app, I am planning to assign each user (from auth_user) to one of the group ( from auth_group). Each group can have multiple users. I have entry in auth_group, auth_user and auth_user_groups. Here is my question:
At time of login I want to check that logging user belongs to which group?
I want to keep that group info in session/cache so all pages I can show information about that group only.
If you have any sample code will be great.
Giving support to the very well #trinchet's answer with an example of context_processor code.
Puts inside your webapp a new file called context_processors.py and writes this lines on it:
def user_groups(request):
"""
Add `groups` var to the context with all the
groups the logged in user has, so you can access
in your templates to this var as: {{ groups }}
"""
groups = None
if request.user.is_authenticated():
groups = user.groups
return {'groups': groups}
Finally on your settings.py add 'webbapp.context_processors.user_groups'to TEMPLATE_CONTEXT_PROCESSOR:
TEMPLATE_CONTEXT_PROCESSORS = (
'webbapp.context_processors.user_groups',
)
1) Be user an instance of auth.models.User, you can get all groups the user belong to, through user.groups. If you want to ask at time of login then you should do this in your login view.
2) You can use session or cache approaches to deal with, this is irrelevant, but once you have the group you need to render the pages having this value, i mean, you need to provide the group to the template rendering, to do this I suggest to you using a custom context processor.