Skip to content

Commit

Permalink
add basic permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
jrafaelrn committed Aug 10, 2023
1 parent 27f219f commit be2f39e
Show file tree
Hide file tree
Showing 31 changed files with 855 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/site/erp/roles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from rolepermissions.roles import AbstractUserRole


class Gerente(AbstractUserRole):
available_permissions = {
'gerente_permission': True,
}
7 changes: 6 additions & 1 deletion src/site/erp/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'usuarios'
'usuarios',
'rolepermissions',
]

MIDDLEWARE = [
Expand Down Expand Up @@ -131,3 +132,7 @@

# Config Auth
AUTH_USER_MODEL = 'usuarios.Users'


# Role permissions
ROLEPERMISSIONS_MODULE = 'erp.roles'
3 changes: 2 additions & 1 deletion src/site/erp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('usuarios.urls')),
]
1 change: 1 addition & 0 deletions src/site/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
django
django-role-permissions
Pillow
psycopg2-binary
coveralls
Expand Down
5 changes: 4 additions & 1 deletion src/site/usuarios/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@
class UsersAdmin(admin_auth_django.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
model = Users
model = Users
fieldsets = admin_auth_django.UserAdmin.fieldsets + (
('Cargo', {'fields': ('cargo',)}),
)
6 changes: 6 additions & 0 deletions src/site/usuarios/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import views

urlpatterns = [
path('login/', views.login, name='login'),
]
3 changes: 3 additions & 0 deletions src/site/usuarios/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def login(request):
return HttpResponse('Login')
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pip
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2013-2015 Vinta Software

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Metadata-Version: 2.1
Name: django-role-permissions
Version: 3.2.0
Summary: A django app for role based permissions.
Home-page: http://github.com/vintasoftware/django-role-permissions
Author: Filipe Ximenes
Author-email: filipeximenes@gmail.com
License: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django (>=1.5)

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
django_role_permissions-3.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
django_role_permissions-3.2.0.dist-info/LICENSE,sha256=YleJ0gh90OYg3W73O7PIHu6pTCavqe81OKwM0TUfnBU,1085
django_role_permissions-3.2.0.dist-info/METADATA,sha256=M-phLBq_917AKwq46B_uKotZro8NHo5Nxsm7pkroiOI,842
django_role_permissions-3.2.0.dist-info/RECORD,,
django_role_permissions-3.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
django_role_permissions-3.2.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
django_role_permissions-3.2.0.dist-info/top_level.txt,sha256=wdEOh4dS4ywsTAd4UDEDy5n0_7mVsr_ImiNaqZat844,108
rolepermissions/__init__.py,sha256=fLFy1uMhoot8Treec4Xpa7SAgpCnCHggXt3VG5_gSrs,130
rolepermissions/__pycache__/__init__.cpython-310.pyc,,
rolepermissions/__pycache__/admin.cpython-310.pyc,,
rolepermissions/__pycache__/apps.cpython-310.pyc,,
rolepermissions/__pycache__/checkers.cpython-310.pyc,,
rolepermissions/__pycache__/decorators.cpython-310.pyc,,
rolepermissions/__pycache__/exceptions.cpython-310.pyc,,
rolepermissions/__pycache__/loader.cpython-310.pyc,,
rolepermissions/__pycache__/mixins.cpython-310.pyc,,
rolepermissions/__pycache__/models.cpython-310.pyc,,
rolepermissions/__pycache__/permissions.cpython-310.pyc,,
rolepermissions/__pycache__/roles.cpython-310.pyc,,
rolepermissions/__pycache__/utils.cpython-310.pyc,,
rolepermissions/admin.py,sha256=U_mEIfx1Bi748KG8jYNWbY902dpTd_i0nPhapVjXd8c,1743
rolepermissions/apps.py,sha256=EhlF5eVt056zfn1ripk3DO5GKHXFg3jNGxI7wD2tdLI,267
rolepermissions/checkers.py,sha256=9NaIdqwxhdOh-qZtPl3h4hzSFWsbvLsssUXcbiryCIc,1698
rolepermissions/decorators.py,sha256=VLiarucyqgxv9gX65RSM-wCsawWIEKRaVcFf6XQWFDs,1581
rolepermissions/exceptions.py,sha256=4eK2iO36T-ROMzlPIlkEMrOlXkfbPA5l3fC0rW1Kff8,194
rolepermissions/loader.py,sha256=gJmV0mEy5WfeJc5um2p8l6HN3WmDgJrCQWDaarO7JEg,808
rolepermissions/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
rolepermissions/management/__pycache__/__init__.cpython-310.pyc,,
rolepermissions/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
rolepermissions/management/commands/__pycache__/__init__.cpython-310.pyc,,
rolepermissions/management/commands/__pycache__/sync_roles.cpython-310.pyc,,
rolepermissions/management/commands/sync_roles.py,sha256=GYYsd7_p60SbuKbVV22mhN5G2TOK1kagSaIpzlWRuB0,2236
rolepermissions/mixins.py,sha256=nxn9aIFbFCPR7W-__KO8TqcEobqKl0yD8SWVQzUZyWo,865
rolepermissions/models.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
rolepermissions/permissions.py,sha256=us9YcQwfCt8NO6LaxsAimByIJ09xMQooCdLzzgrR86Y,3745
rolepermissions/roles.py,sha256=G6KAknLLnNKqFkdgvwmc4KuQsXX60R4Ocq7WMY9r5xM,8118
rolepermissions/templatetags/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
rolepermissions/templatetags/__pycache__/__init__.cpython-310.pyc,,
rolepermissions/templatetags/__pycache__/permission_tags.cpython-310.pyc,,
rolepermissions/templatetags/permission_tags.py,sha256=60GOdAku-eLnwk9I3IQT8o3ZxczqbsZfa7dxSpJ2QyU,829
rolepermissions/utils.py,sha256=pIMzqNyLIIGcBXmjjPY9EkBi19r5rAVxz99cnpcT0Gs,923
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.40.0)
Root-Is-Purelib: true
Tag: py3-none-any

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
rolepermissions
rolepermissions/management
rolepermissions/management/commands
rolepermissions/templatetags
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
__version__ = '3.2.0'

import django

if django.VERSION < (3, 2):
default_app_config = 'rolepermissions.apps.RolePermissions'
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from django.conf import settings
from django.contrib import admin, auth
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.admin.sites import NotRegistered
from rolepermissions import roles

ROLEPERMISSIONS_REGISTER_ADMIN = getattr(settings, 'ROLEPERMISSIONS_REGISTER_ADMIN', False)
UserModel = auth.get_user_model()


class RolePermissionsUserAdminMixin(object):
""" Must be mixed in with an UserAdmin class"""
def save_related(self, request, form, formsets, change):
user = UserModel.objects.get(pk=form.instance.pk)
old_user_roles = set(r.get_name() for r in roles.get_user_roles(user))
super(RolePermissionsUserAdminMixin, self).save_related(request, form, formsets, change)

new_user_groups = set(g.name for g in user.groups.all())

for role_name in (old_user_roles - new_user_groups): # roles removed from User's groups
try: # put the recently removed group back, let rolepermissions remove it...
group = Group.objects.get(name=role_name)
user.groups.add(group)
except Group.DoesNotExist:
pass
roles.remove_role(user, role_name)

for group_name in (new_user_groups - old_user_roles): # groups potentially added to User's roles
try:
roles.assign_role(user, group_name)
except roles.RoleDoesNotExist:
pass


class RolePermissionsUserAdmin(RolePermissionsUserAdminMixin, UserAdmin):
pass


if ROLEPERMISSIONS_REGISTER_ADMIN:
try:
admin.site.unregister(UserModel)
except NotRegistered:
pass
admin.site.register(UserModel, RolePermissionsUserAdmin)
12 changes: 12 additions & 0 deletions src/site/venv/lib/python3.10/site-packages/rolepermissions/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

from django.apps import AppConfig

from rolepermissions.loader import load_roles_and_permissions


class RolePermissions(AppConfig):
name = 'rolepermissions'
verbose_name = "Django Role Permissions"

def ready(self):
load_roles_and_permissions()
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from __future__ import unicode_literals

import inspect

from django.conf import settings
from rolepermissions.roles import (
RolesManager, get_user_roles)
from rolepermissions.permissions import (
PermissionsManager, available_perm_names)


def has_role(user, roles):
"""Check if a user has any of the given roles."""
if _check_superpowers(user):
return True

if not isinstance(roles, list):
roles = [roles]

normalized_roles = []
for role in roles:
if not inspect.isclass(role):
role = RolesManager.retrieve_role(role)

normalized_roles.append(role)

user_roles = get_user_roles(user)

return any([role in user_roles for role in normalized_roles])


def has_permission(user, permission_name):
"""Check if a user has a given permission."""
if _check_superpowers(user):
return True

return permission_name in available_perm_names(user)


def has_object_permission(checker_name, user, obj):
"""Check if a user has permission to perform an action on an object."""
if _check_superpowers(user):
return True

checker = PermissionsManager.retrieve_checker(checker_name)
user_roles = get_user_roles(user)

if not user_roles:
user_roles = [None]

return any([checker(user_role, user, obj) for user_role in user_roles])


def _check_superpowers(user):
"""
Check if user is superuser and should have superpowers.
Default is true to maintain backward compatibility.
"""
key = 'ROLEPERMISSIONS_SUPERUSER_SUPERPOWERS'

superpowers = getattr(settings, key, True)
if not superpowers:
return False

return user and user.is_superuser
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from __future__ import unicode_literals

from functools import wraps

from django.conf import settings
from django.contrib.auth.views import redirect_to_login as dj_redirect_to_login
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect as dj_redirect

from rolepermissions.checkers import has_role, has_permission
from rolepermissions.utils import user_is_authenticated


def _role_permission_checker(function, subject, redirect_to_login, redirect_url):
def request_decorator(dispatch):
@wraps(dispatch)
def wrapper(request, *args, **kwargs):
user = request.user
if user_is_authenticated(user):
if function(user, subject):
return dispatch(request, *args, **kwargs)

if redirect_url:
return dj_redirect(redirect_url)

redirect = redirect_to_login
if redirect is None:
redirect = getattr(
settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN', False)
if redirect:
return dj_redirect_to_login(request.get_full_path())
raise PermissionDenied
return wrapper
return request_decorator


def has_role_decorator(role, redirect_to_login=None, redirect_url=None):
return _role_permission_checker(has_role, role, redirect_to_login, redirect_url)


def has_permission_decorator(permission_name, redirect_to_login=None, redirect_url=None):
return _role_permission_checker(has_permission, permission_name, redirect_to_login, redirect_url)
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from __future__ import unicode_literals


class CheckerNotRegistered(Exception):
pass


class RoleDoesNotExist(Exception):
pass


class RolePermissionScopeException(Exception):
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from __future__ import unicode_literals

import inspect

from importlib import import_module
from pydoc import locate

from django.conf import settings


def get_app_name(app_name):
"""
Returns a app name from new app config if is
a class or the same app name if is not a class.
"""
type_ = locate(app_name)
if inspect.isclass(type_):
return type_.name
return app_name


def load_roles_and_permissions():
if hasattr(settings, 'ROLEPERMISSIONS_MODULE'):
import_module(settings.ROLEPERMISSIONS_MODULE)

for app_name in settings.INSTALLED_APPS:
if app_name != 'rolepermissions':
app_name = get_app_name(app_name)
try:
import_module('.permissions', app_name)
except ImportError:
pass
Empty file.
Empty file.
Loading

0 comments on commit be2f39e

Please sign in to comment.