include::../description.adoc[]

include::../ask-yourself.adoc[]

include::../recommended.adoc[]

== Sensitive Code Example

----
# limiting access via "has_perm" and adding permission with "user_permissions.add"

from django.contrib.auth.models import Permission, User, Group
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied


def test_permissions(request, user_id):  # Sensitive. This method checks permissions/authentication or changes permissions
    user = get_object_or_404(User, pk=user_id)
    # Or
    user = request.user

    user.has_perm('thisis.a_perm')  # Check permission
    user.has_perms(['thisis.a_perm'])  # Check permission

    request.user.is_authenticated  # Check permission

    content_type = ContentType.objects.get_for_model(User)

    permission = Permission.objects.get(
        codename='change_something',
        content_type=content_type,
    )
    user.user_permissions.add(permission)  # Changes permissions
    user.user_permissions.set([permission])  # Changes permissions
    user.user_permissions.remove(permission)  # Changes permissions
    user.user_permissions.clear()  # Changes permissions

    group, created = Group.objects.get_or_create(name='mygroup')
    group = Group.objects.get(name='mygroup')  # Or

    group.permissions.add(permission)  # Changes permissions
    group.permissions.set([permission])  # Changes permissions
    group.permissions.remove(permission)  # Changes permissions
    group.permissions.clear()  # Changes permissions

    user.groups.set([group])  # Changes permissions
    user.groups.add(group)  # Changes permissions
    user.groups.remove(group)  # Changes permissions
    user.groups.clear()  # Changes permissions

    raise PermissionDenied  # Denies permission


# limiting access to the models with Model->Meta->permissions

from django.db import models

class Person(models.Model):
    class Meta:
        permissions = (('can_sleep_in_bed', 'Can sleep in bed'),)  # Sensitive.


# Limiting access with the decorators

from django.contrib.auth.decorators import permission_required, login_required

@login_required  # Checks authentication
@permission_required('app.can_sleep')  # Checks permission
def index(request):  # Sensitive.
    pass


# Limiting access with "PermissionRequiredMixin"

from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import View

class MyView(PermissionRequiredMixin, View):
    permission_required = ('app.can_sleep', 'app.can_drive')  # Sensitive.
----

include::../see.adoc[]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

=== Highlighting

secondary location on XXX


endif::env-github,rspecator-view[]
