/oauth/models.py
Python | 299 lines | 267 code | 14 blank | 18 comment | 17 complexity | 9f833cb459d2ff9c3f2ce5322e5a71bb MD5 | raw file
- __author__ = 'tingsystems'
- import uuid
- import string
- from django.contrib.auth.models import UserManager, PermissionsMixin, AbstractBaseUser, GroupManager, \
- PermissionManager
- from django.contrib.contenttypes.models import ContentType
- from django.contrib.auth.hashers import make_password
- from django.utils.encoding import python_2_unicode_compatible
- from django.core import validators
- from django.db import models
- from django.utils import six, timezone
- from django.utils.translation import ugettext_lazy as _
- from django.contrib import auth
- from rest_framework.exceptions import PermissionDenied, ValidationError
- from jsonfield import JSONField
- from auditlog.registry import auditlog
- def _simple_domain_name_validator(value):
- """
- Validates that the given value contains no whitespaces to prevent common
- typos.
- """
- if not value:
- return
- checks = ((s in value) for s in string.whitespace)
- if any(checks):
- raise ValidationError(_("The domain name cannot contain any spaces or tabs."))
- class Site(models.Model):
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- logo = models.CharField(max_length=254, null=True, blank=True)
- name = models.CharField(max_length=128)
- slug = models.SlugField(unique=True)
- excerpt = models.CharField(max_length=200, null=True, blank=True)
- domain = models.CharField(
- max_length=100,
- validators=[_simple_domain_name_validator],
- unique=True,
- )
- email = models.EmailField()
- phone1 = models.CharField(max_length=20, null=True, blank=True)
- phone2 = models.CharField(max_length=20, null=True, blank=True)
- metadata = JSONField(null=True, blank=True)
- isActive = models.BooleanField(default=True)
- deployAt = models.DateField(null=True, blank=True)
- createdAt = models.DateTimeField(auto_now_add=True)
- updatedAt = models.DateTimeField(auto_now=True)
- def __str__(self):
- return self.name
- # A few helper functions for common logic between User and AnonymousUser.
- def _user_get_all_permissions(user, obj):
- permissions = set()
- for backend in auth.get_backends():
- if hasattr(backend, "get_all_permissions"):
- permissions.update(backend.get_all_permissions(user, obj))
- return permissions
- def _user_has_perm(user, perm, obj):
- """
- A backend can raise `PermissionDenied` to short-circuit permission checking.
- """
- for backend in auth.get_backends():
- if not hasattr(backend, 'has_perm'):
- continue
- try:
- if backend.has_perm(user, perm, obj):
- return True
- except PermissionDenied:
- return False
- return False
- def _user_has_module_perms(user, app_label):
- """
- A backend can raise `PermissionDenied` to short-circuit permission checking.
- """
- for backend in auth.get_backends():
- if not hasattr(backend, 'has_module_perms'):
- continue
- try:
- if backend.has_module_perms(user, app_label):
- return True
- except PermissionDenied:
- return False
- return False
- @python_2_unicode_compatible
- class Permission(models.Model):
- """
- The permissions system provides a way to assign permissions to specific
- users and groups of users.
- The permission system is used by the Django admin site, but may also be
- useful in your own code. The Django admin site uses permissions as follows:
- - The "add" permission limits the user's ability to view the "add" form
- and add an object.
- - The "change" permission limits a user's ability to view the change
- list, view the "change" form and change an object.
- - The "delete" permission limits the ability to delete an object.
- Permissions are set globally per type of object, not per specific object
- instance. It is possible to say "Mary may change news stories," but it's
- not currently possible to say "Mary may change news stories, but only the
- ones she created herself" or "Mary may only change news stories that have a
- certain status or publication date."
- Three basic permissions -- add, change and delete -- are automatically
- created for each Django model.
- """
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- name = models.CharField(_('name'), max_length=255)
- content_type = models.ForeignKey(ContentType, related_name='ct_permission')
- codename = models.CharField(_('codename'), max_length=100)
- objects = PermissionManager()
- class Meta:
- verbose_name = _('permission')
- verbose_name_plural = _('permissions')
- unique_together = (('content_type', 'codename'),)
- ordering = ('content_type__app_label', 'content_type__model',
- 'codename')
- def __str__(self):
- return "%s | %s | %s" % (
- six.text_type(self.content_type.app_label),
- six.text_type(self.content_type),
- six.text_type(self.name))
- def natural_key(self):
- return (self.codename,) + self.content_type.natural_key()
- natural_key.dependencies = ['contenttypes.contenttype']
- @python_2_unicode_compatible
- class Group(models.Model):
- """
- Groups are a generic way of categorizing users to apply permissions, or
- some other label, to those users. A user can belong to any number of
- groups.
- A user in a group automatically has all the permissions granted to that
- group. For example, if the group Site editors has the permission
- can_edit_home_page, any user in that group will have that permission.
- Beyond permissions, groups are a convenient way to categorize users to
- apply some label, or extended functionality, to them. For example, you
- could create a group 'Special users', and you could write code that would
- do special things to those users -- such as giving them access to a
- members-only portion of your site, or sending them members-only email
- messages.
- """
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- name = models.CharField(_('name'), max_length=80, unique=True)
- isActive = models.BooleanField(default=True)
- createdAt = models.DateTimeField(auto_now_add=True)
- updatedAt = models.DateTimeField(auto_now=True)
- permissions = models.ManyToManyField(
- Permission,
- verbose_name=_('permissions'), blank=True
- )
- objects = GroupManager()
- class Meta:
- verbose_name = _('group')
- verbose_name_plural = _('groups')
- def __str__(self):
- return self.name
- def natural_key(self):
- return (self.name,)
- class User(AbstractBaseUser):
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- username = models.CharField(
- max_length=30, unique=True,
- help_text=_('Required. 30 characters or fewer. Letters, digits and '
- '@/./+/-/_ only.'),
- validators=[
- validators.RegexValidator(r'^[\w.@+-]+$',
- _('Enter a valid username. '
- 'This value may contain only letters, numbers '
- 'and @/./+/-/_ characters.'), 'invalid'),
- ],
- error_messages={
- 'unique': _("A user with that username already exists."),
- }
- )
- firstName = models.CharField(max_length=30, blank=True)
- lastName = models.CharField(max_length=30, blank=True)
- email = models.EmailField()
- is_staff = models.BooleanField(default=False)
- is_active = models.BooleanField(default=True)
- date_joined = models.DateTimeField(default=timezone.now)
- bio = models.TextField(null=False, blank=True)
- photo = models.CharField(max_length=500, null=True, blank=True)
- lang = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name=_("default language"))
- token = models.CharField(max_length=200, null=True, blank=True, default=None)
- emailToken = models.CharField(max_length=200, null=True, blank=True, default=None)
- new_email = models.EmailField(null=True, blank=True)
- is_system = models.BooleanField(null=False, blank=False, default=False)
- ip = models.GenericIPAddressField(null=True, blank=True)
- fingerKey = models.CharField(max_length=100, null=True, blank=True)
- is_superuser = models.BooleanField(default=False)
- groups = models.ManyToManyField(Group, blank=True, related_name="user_set", related_query_name="user")
- user_permissions = models.ManyToManyField(Permission, blank=True, related_name="user_set",
- related_query_name="user")
- site = models.UUIDField(null=True, blank=True)
- sites = models.ManyToManyField(Site, blank=True, related_name="user_set", related_query_name="user")
- USERNAME_FIELD = 'username'
- REQUIRED_FIELDS = ['email', ]
- objects = UserManager()
- class Meta:
- verbose_name = 'user'
- verbose_name_plural = 'users'
- ordering = ['username']
- def __str__(self):
- return self.get_full_name()
- def get_group_permissions(self, obj=None):
- """
- Returns a list of permission strings that this user has through their
- groups. This method queries all available auth backends. If an object
- is passed in, only permissions matching this object are returned.
- """
- permissions = set()
- for backend in auth.get_backends():
- if hasattr(backend, "get_group_permissions"):
- permissions.update(backend.get_group_permissions(self, obj))
- return permissions
- def get_all_permissions(self, obj=None):
- return _user_get_all_permissions(self, obj)
- def has_perm(self, perm, obj=None):
- """
- Returns True if the user has the specified permission. This method
- queries all available auth backends, but returns immediately if any
- backend returns True. Thus, a user who has permission from a single
- auth backend is assumed to have permission in general. If an object is
- provided, permissions for this specific object are checked.
- """
- # Active superusers have all permissions.
- if self.is_active and self.is_superuser:
- return True
- return _user_has_perm(self, perm, obj)
- def has_perms(self, perm_list, obj=None):
- """
- Returns True if the user has each of the specified permissions. If
- object is passed, it checks if the user has all required perms for this
- object.
- """
- for perm in perm_list:
- if not self.has_perm(perm, obj):
- return False
- return True
- def has_module_perms(self, app_label):
- """
- Returns True if the user has any permissions in the given app label.
- Uses pretty much the same logic as has_perm, above.
- """
- # Active superusers have all permissions.
- if self.is_active and self.is_superuser:
- return True
- return _user_has_module_perms(self, app_label)
- def get_short_name(self):
- """Returns the short name for the user."""
- return self.username
- def get_full_name(self):
- return self.firstName or self.username or self.email
- def set_password(self, raw_password):
- self.password = make_password(raw_password)
- auditlog.register(Site)
- auditlog.register(User)