# Path: teamwork/models.py
# class Team(models.Model):
#     """
#     Organizational unit for a set of users with assigned roles
#     """
#     name = models.CharField(
#         _("name"), max_length=128, editable=True, unique=True,
#         db_index=True)
#     description = models.TextField(
#         _("Description of intended use"), null=True, blank=True)
#     founder = models.ForeignKey(
#         settings.AUTH_USER_MODEL, db_index=True, blank=True, null=True)
# 
#     created = models.DateTimeField(auto_now_add=True, db_index=True)
#     modified = models.DateTimeField(auto_now=True, null=True, db_index=True)
# 
#     objects = TeamManager()
# 
#     class Meta:
#         permissions = (
#             ('view_team', 'Can view team'),
#         )
# 
#     def __unicode__(self):
#         return self.name
# 
#     @property
#     def team(self):
#         return self
# 
#     def has_user(self, user):
#         """Determine whether the given user is a member of this team"""
#         # TODO: founder is not considered a member without an associated role
#         hits = (Role.users.through.objects
#                     .filter(role__team=self, user=user)).count()
#         return hits > 0
# 
#     def filter_permissions(self, user, permissions):
#         """Filter permissions with custom logic"""
#         if user == self.founder:
#             # Founder is admin-equivalent for the team
#             if permissions is None:
#                 permissions = set()
#             for perm, desc in self._meta.permissions:
#                 permissions.add('teamwork.%s' % perm)
#         return permissions
# 
#     def get_all_permissions(self, user):
#         """Get all Permissions applied to this User based on assigned Roles"""
#         role_ids = (Role.users.through.objects
#                         .filter(user=user, role__team=self)
#                         .values('role'))
#         return (p.permission for p in
#                 Role.permissions.through.objects
#                     .filter(role__in=role_ids)
#                     .select_related())
# 
# class Role(models.Model):
#     """
#     Role within a Team for a user.
# 
#     This works somewhat like a Group, but its Permissions only apply when a
#     User acts upon an object belonging to the Role's parent Team.
#     """
#     team = models.ForeignKey(Team, db_index=True, blank=False, null=False)
#     name = models.CharField(_("name"), max_length=128, db_index=False)
#     description = models.TextField(_("Description of intended use"),
#                                    blank=True)
# 
#     permissions = models.ManyToManyField(
#         Permission, blank=True,
#         help_text='Specific permissions for this role.')
# 
#     users = models.ManyToManyField(
#         settings.AUTH_USER_MODEL, blank=True,
#         help_text='Users granted this role')
# 
#     objects = RoleManager()
# 
#     def __unicode__(self):
#         return self.name
# 
#     class Meta:
#         unique_together = (('name', 'team'),)
#         permissions = (
#             ('view_role', 'Can view role'),
#             ('manage_role_permissions', 'Can manage role permissions'),
#             ('manage_role_users', 'Can manage role users'),
#         )
# 
#     def is_granted_to(self, user):
#         """Return whether this role is granted to the given user"""
#         return (self.users.filter(id=user.id).count() > 0)
# 
#     def filter_permissions(self, user, permissions):
#         """Filter permissions with custom logic"""
#         if user == self.team.founder:
#             # Founder is admin-equivalent for the team
#             if permissions is None:
#                 permissions = set()
#             for perm, desc in self._meta.permissions:
#                 permissions.add('teamwork.%s' % perm)
#         return permissions
# 
#     def add_permissions_by_name(self, names, obj=None):
#         from .shortcuts import get_permission_by_name
#         self.permissions.add(*(get_permission_by_name(name, obj)
#                              for name in names))
# 
# Path: teamwork/shortcuts.py
# def get_object_or_404_or_403(perm_name, user, model_cls, **kwargs):
#     """
#     Wrapper for get_object_or_404 that also tests a permission and throws a
#     PermissionDenied if the user doesn't have the permission.
#     """
#     obj = get_object_or_404(model_cls, **kwargs)
#     parts = perm_name.split('.', 1)
#     if len(parts) == 1:
#         ct = ContentType.objects.get_for_model(obj)
#         perm_name = '%s.%s' % (ct.app_label, perm_name)
#     if not user.has_perm(perm_name, obj):
#         raise PermissionDenied
#     return obj


from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseRedirect)
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import ugettext as _
from .models import Team, Role
from .shortcuts import get_object_or_404_or_403
import django.contrib.auth



def user_roles(request, username):
    user = get_object_or_404(get_user_model(), username=username)

    if 'POST' == request.method:

        role = get_object_or_404_or_403(
            'teamwork.manage_role_users', request.user,
            Role, id=request.POST.get('role_id'))

        if role.is_granted_to(user):
            role.users.remove(user)
            messages.info(request, _('Revoked %s for %s from %s') %
                          (role, role.team, user))
        else:
            role.users.add(user)
            messages.info(request, _('Granted %s for %s to %s') %

# Path: teamwork/models.py
# class Team(models.Model):
#     """
#     Organizational unit for a set of users with assigned roles
#     """
#     name = models.CharField(
#         _("name"), max_length=128, editable=True, unique=True,
#         db_index=True)
#     description = models.TextField(
#         _("Description of intended use"), null=True, blank=True)
#     founder = models.ForeignKey(
#         settings.AUTH_USER_MODEL, db_index=True, blank=True, null=True)
# 
#     created = models.DateTimeField(auto_now_add=True, db_index=True)
#     modified = models.DateTimeField(auto_now=True, null=True, db_index=True)
# 
#     objects = TeamManager()
# 
#     class Meta:
#         permissions = (
#             ('view_team', 'Can view team'),
#         )
# 
#     def __unicode__(self):
#         return self.name
# 
#     @property
#     def team(self):
#         return self
# 
#     def has_user(self, user):
#         """Determine whether the given user is a member of this team"""
#         # TODO: founder is not considered a member without an associated role
#         hits = (Role.users.through.objects
#                     .filter(role__team=self, user=user)).count()
#         return hits > 0
# 
#     def filter_permissions(self, user, permissions):
#         """Filter permissions with custom logic"""
#         if user == self.founder:
#             # Founder is admin-equivalent for the team
#             if permissions is None:
#                 permissions = set()
#             for perm, desc in self._meta.permissions:
#                 permissions.add('teamwork.%s' % perm)
#         return permissions
# 
#     def get_all_permissions(self, user):
#         """Get all Permissions applied to this User based on assigned Roles"""
#         role_ids = (Role.users.through.objects
#                         .filter(user=user, role__team=self)
#                         .values('role'))
#         return (p.permission for p in
#                 Role.permissions.through.objects
#                     .filter(role__in=role_ids)
#                     .select_related())
# 
# class Role(models.Model):
#     """
#     Role within a Team for a user.
# 
#     This works somewhat like a Group, but its Permissions only apply when a
#     User acts upon an object belonging to the Role's parent Team.
#     """
#     team = models.ForeignKey(Team, db_index=True, blank=False, null=False)
#     name = models.CharField(_("name"), max_length=128, db_index=False)
#     description = models.TextField(_("Description of intended use"),
#                                    blank=True)
# 
#     permissions = models.ManyToManyField(
#         Permission, blank=True,
#         help_text='Specific permissions for this role.')
# 
#     users = models.ManyToManyField(
#         settings.AUTH_USER_MODEL, blank=True,
#         help_text='Users granted this role')
# 
#     objects = RoleManager()
# 
#     def __unicode__(self):
#         return self.name
# 
#     class Meta:
#         unique_together = (('name', 'team'),)
#         permissions = (
#             ('view_role', 'Can view role'),
#             ('manage_role_permissions', 'Can manage role permissions'),
#             ('manage_role_users', 'Can manage role users'),
#         )
# 
#     def is_granted_to(self, user):
#         """Return whether this role is granted to the given user"""
#         return (self.users.filter(id=user.id).count() > 0)
# 
#     def filter_permissions(self, user, permissions):
#         """Filter permissions with custom logic"""
#         if user == self.team.founder:
#             # Founder is admin-equivalent for the team
#             if permissions is None:
#                 permissions = set()
#             for perm, desc in self._meta.permissions:
#                 permissions.add('teamwork.%s' % perm)
#         return permissions
# 
#     def add_permissions_by_name(self, names, obj=None):
#         from .shortcuts import get_permission_by_name
#         self.permissions.add(*(get_permission_by_name(name, obj)
#                              for name in names))
# 
# Path: teamwork/shortcuts.py
# def get_object_or_404_or_403(perm_name, user, model_cls, **kwargs):
#     """
#     Wrapper for get_object_or_404 that also tests a permission and throws a
#     PermissionDenied if the user doesn't have the permission.
#     """
#     obj = get_object_or_404(model_cls, **kwargs)
#     parts = perm_name.split('.', 1)
#     if len(parts) == 1:
#         ct = ContentType.objects.get_for_model(obj)
#         perm_name = '%s.%s' % (ct.app_label, perm_name)
#     if not user.has_perm(perm_name, obj):
#         raise PermissionDenied
#     return obj


# Path: teamwork/views.py
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseRedirect)
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import ugettext as _
from .models import Team, Role
from .shortcuts import get_object_or_404_or_403
import django.contrib.auth




def user_roles(request, username):
    user = get_object_or_404(get_user_model(), username=username)

    if 'POST' == request.method:

        role = get_object_or_404_or_403(
            'teamwork.manage_role_users', request.user,
            Role, id=request.POST.get('role_id'))

        if role.is_granted_to(user):
            role.users.remove(user)
            messages.info(request, _('Revoked %s for %s from %s') %
                          (role, role.team, user))
        else:
            role.users.add(user)
            messages.info(request, _('Granted %s for %s to %s') %

                          (role, role.team, user))