auth.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. from mongoengine import *
  2. from django.utils.encoding import smart_str
  3. from django.contrib.auth.models import _user_has_perm, _user_get_all_permissions, _user_has_module_perms
  4. from django.db import models
  5. from django.contrib.contenttypes.models import ContentTypeManager
  6. from django.contrib import auth
  7. from django.contrib.auth.models import AnonymousUser
  8. from django.utils.translation import ugettext_lazy as _
  9. from .utils import datetime_now
  10. REDIRECT_FIELD_NAME = 'next'
  11. try:
  12. from django.contrib.auth.hashers import check_password, make_password
  13. except ImportError:
  14. """Handle older versions of Django"""
  15. from django.utils.hashcompat import md5_constructor, sha_constructor
  16. def get_hexdigest(algorithm, salt, raw_password):
  17. raw_password, salt = smart_str(raw_password), smart_str(salt)
  18. if algorithm == 'md5':
  19. return md5_constructor(salt + raw_password).hexdigest()
  20. elif algorithm == 'sha1':
  21. return sha_constructor(salt + raw_password).hexdigest()
  22. raise ValueError('Got unknown password algorithm type in password')
  23. def check_password(raw_password, password):
  24. algo, salt, hash = password.split('$')
  25. return hash == get_hexdigest(algo, salt, raw_password)
  26. def make_password(raw_password):
  27. from random import random
  28. algo = 'sha1'
  29. salt = get_hexdigest(algo, str(random()), str(random()))[:5]
  30. hash = get_hexdigest(algo, salt, raw_password)
  31. return '%s$%s$%s' % (algo, salt, hash)
  32. class ContentType(Document):
  33. name = StringField(max_length=100)
  34. app_label = StringField(max_length=100)
  35. model = StringField(max_length=100, verbose_name=_('python model class name'),
  36. unique_with='app_label')
  37. objects = ContentTypeManager()
  38. class Meta:
  39. verbose_name = _('content type')
  40. verbose_name_plural = _('content types')
  41. # db_table = 'django_content_type'
  42. # ordering = ('name',)
  43. # unique_together = (('app_label', 'model'),)
  44. def __unicode__(self):
  45. return self.name
  46. def model_class(self):
  47. "Returns the Python model class for this type of content."
  48. from django.db import models
  49. return models.get_model(self.app_label, self.model)
  50. def get_object_for_this_type(self, **kwargs):
  51. """
  52. Returns an object of this type for the keyword arguments given.
  53. Basically, this is a proxy around this object_type's get_object() model
  54. method. The ObjectNotExist exception, if thrown, will not be caught,
  55. so code that calls this method should catch it.
  56. """
  57. return self.model_class()._default_manager.using(self._state.db).get(**kwargs)
  58. def natural_key(self):
  59. return (self.app_label, self.model)
  60. class SiteProfileNotAvailable(Exception):
  61. pass
  62. class PermissionManager(models.Manager):
  63. def get_by_natural_key(self, codename, app_label, model):
  64. return self.get(
  65. codename=codename,
  66. content_type=ContentType.objects.get_by_natural_key(app_label, model)
  67. )
  68. class Permission(Document):
  69. """The permissions system provides a way to assign permissions to specific
  70. users and groups of users.
  71. The permission system is used by the Django admin site, but may also be
  72. useful in your own code. The Django admin site uses permissions as follows:
  73. - The "add" permission limits the user's ability to view the "add"
  74. form and add an object.
  75. - The "change" permission limits a user's ability to view the change
  76. list, view the "change" form and change an object.
  77. - The "delete" permission limits the ability to delete an object.
  78. Permissions are set globally per type of object, not per specific object
  79. instance. It is possible to say "Mary may change news stories," but it's
  80. not currently possible to say "Mary may change news stories, but only the
  81. ones she created herself" or "Mary may only change news stories that have
  82. a certain status or publication date."
  83. Three basic permissions -- add, change and delete -- are automatically
  84. created for each Django model.
  85. """
  86. name = StringField(max_length=50, verbose_name=_('username'))
  87. content_type = ReferenceField(ContentType)
  88. codename = StringField(max_length=100, verbose_name=_('codename'))
  89. # FIXME: don't access field of the other class
  90. # unique_with=['content_type__app_label', 'content_type__model'])
  91. objects = PermissionManager()
  92. class Meta:
  93. verbose_name = _('permission')
  94. verbose_name_plural = _('permissions')
  95. # unique_together = (('content_type', 'codename'),)
  96. # ordering = ('content_type__app_label', 'content_type__model', 'codename')
  97. def __unicode__(self):
  98. return u"%s | %s | %s" % (
  99. unicode(self.content_type.app_label),
  100. unicode(self.content_type),
  101. unicode(self.name))
  102. def natural_key(self):
  103. return (self.codename,) + self.content_type.natural_key()
  104. natural_key.dependencies = ['contenttypes.contenttype']
  105. class Group(Document):
  106. """Groups are a generic way of categorizing users to apply permissions,
  107. or some other label, to those users. A user can belong to any number of
  108. groups.
  109. A user in a group automatically has all the permissions granted to that
  110. group. For example, if the group Site editors has the permission
  111. can_edit_home_page, any user in that group will have that permission.
  112. Beyond permissions, groups are a convenient way to categorize users to
  113. apply some label, or extended functionality, to them. For example, you
  114. could create a group 'Special users', and you could write code that would
  115. do special things to those users -- such as giving them access to a
  116. members-only portion of your site, or sending them members-only
  117. e-mail messages.
  118. """
  119. name = StringField(max_length=80, unique=True, verbose_name=_('name'))
  120. permissions = ListField(ReferenceField(Permission, verbose_name=_('permissions'), required=False))
  121. class Meta:
  122. verbose_name = _('group')
  123. verbose_name_plural = _('groups')
  124. def __unicode__(self):
  125. return self.name
  126. class UserManager(models.Manager):
  127. def create_user(self, username, email, password=None):
  128. """
  129. Creates and saves a User with the given username, e-mail and password.
  130. """
  131. now = datetime_now()
  132. # Normalize the address by lowercasing the domain part of the email
  133. # address.
  134. try:
  135. email_name, domain_part = email.strip().split('@', 1)
  136. except ValueError:
  137. pass
  138. else:
  139. email = '@'.join([email_name, domain_part.lower()])
  140. user = self.model(username=username, email=email, is_staff=False,
  141. is_active=True, is_superuser=False, last_login=now,
  142. date_joined=now)
  143. user.set_password(password)
  144. user.save(using=self._db)
  145. return user
  146. def create_superuser(self, username, email, password):
  147. u = self.create_user(username, email, password)
  148. u.is_staff = True
  149. u.is_active = True
  150. u.is_superuser = True
  151. u.save(using=self._db)
  152. return u
  153. def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
  154. "Generates a random password with the given length and given allowed_chars"
  155. # Note that default value of allowed_chars does not have "I" or letters
  156. # that look like it -- just to avoid confusion.
  157. from random import choice
  158. return ''.join([choice(allowed_chars) for i in range(length)])
  159. class User(Document):
  160. """A User document that aims to mirror most of the API specified by Django
  161. at http://docs.djangoproject.com/en/dev/topics/auth/#users
  162. """
  163. username = StringField(max_length=30, required=True,
  164. verbose_name=_('username'),
  165. help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"))
  166. first_name = StringField(max_length=30,
  167. verbose_name=_('first name'))
  168. last_name = StringField(max_length=30,
  169. verbose_name=_('last name'))
  170. email = EmailField(verbose_name=_('e-mail address'))
  171. password = StringField(max_length=128,
  172. verbose_name=_('password'),
  173. help_text=_("Use '[algo]$[iterations]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
  174. is_staff = BooleanField(default=False,
  175. verbose_name=_('staff status'),
  176. help_text=_("Designates whether the user can log into this admin site."))
  177. is_active = BooleanField(default=True,
  178. verbose_name=_('active'),
  179. help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
  180. is_superuser = BooleanField(default=False,
  181. verbose_name=_('superuser status'),
  182. help_text=_("Designates that this user has all permissions without explicitly assigning them."))
  183. last_login = DateTimeField(default=datetime_now,
  184. verbose_name=_('last login'))
  185. date_joined = DateTimeField(default=datetime_now,
  186. verbose_name=_('date joined'))
  187. user_permissions = ListField(ReferenceField(Permission), verbose_name=_('user permissions'),
  188. help_text=_('Permissions for the user.'))
  189. USERNAME_FIELD = 'username'
  190. REQUIRED_FIELDS = ['email']
  191. meta = {
  192. 'allow_inheritance': True,
  193. 'indexes': [
  194. {'fields': ['username'], 'unique': True, 'sparse': True}
  195. ]
  196. }
  197. def __unicode__(self):
  198. return self.username
  199. def get_full_name(self):
  200. """Returns the users first and last names, separated by a space.
  201. """
  202. full_name = u'%s %s' % (self.first_name or '', self.last_name or '')
  203. return full_name.strip()
  204. def is_anonymous(self):
  205. return False
  206. def is_authenticated(self):
  207. return True
  208. def set_password(self, raw_password):
  209. """Sets the user's password - always use this rather than directly
  210. assigning to :attr:`~mongoengine.django.auth.User.password` as the
  211. password is hashed before storage.
  212. """
  213. self.password = make_password(raw_password)
  214. self.save()
  215. return self
  216. def check_password(self, raw_password):
  217. """Checks the user's password against a provided password - always use
  218. this rather than directly comparing to
  219. :attr:`~mongoengine.django.auth.User.password` as the password is
  220. hashed before storage.
  221. """
  222. return check_password(raw_password, self.password)
  223. @classmethod
  224. def create_user(cls, username, password, email=None):
  225. """Create (and save) a new user with the given username, password and
  226. email address.
  227. """
  228. now = datetime_now()
  229. # Normalize the address by lowercasing the domain part of the email
  230. # address.
  231. if email is not None:
  232. try:
  233. email_name, domain_part = email.strip().split('@', 1)
  234. except ValueError:
  235. pass
  236. else:
  237. email = '@'.join([email_name, domain_part.lower()])
  238. user = cls(username=username, email=email, date_joined=now)
  239. user.set_password(password)
  240. user.save()
  241. return user
  242. def get_group_permissions(self, obj=None):
  243. """
  244. Returns a list of permission strings that this user has through his/her
  245. groups. This method queries all available auth backends. If an object
  246. is passed in, only permissions matching this object are returned.
  247. """
  248. permissions = set()
  249. for backend in auth.get_backends():
  250. if hasattr(backend, "get_group_permissions"):
  251. permissions.update(backend.get_group_permissions(self, obj))
  252. return permissions
  253. def get_all_permissions(self, obj=None):
  254. return _user_get_all_permissions(self, obj)
  255. def has_perm(self, perm, obj=None):
  256. """
  257. Returns True if the user has the specified permission. This method
  258. queries all available auth backends, but returns immediately if any
  259. backend returns True. Thus, a user who has permission from a single
  260. auth backend is assumed to have permission in general. If an object is
  261. provided, permissions for this specific object are checked.
  262. """
  263. # Active superusers have all permissions.
  264. if self.is_active and self.is_superuser:
  265. return True
  266. # Otherwise we need to check the backends.
  267. return _user_has_perm(self, perm, obj)
  268. def has_module_perms(self, app_label):
  269. """
  270. Returns True if the user has any permissions in the given app label.
  271. Uses pretty much the same logic as has_perm, above.
  272. """
  273. # Active superusers have all permissions.
  274. if self.is_active and self.is_superuser:
  275. return True
  276. return _user_has_module_perms(self, app_label)
  277. def email_user(self, subject, message, from_email=None):
  278. "Sends an e-mail to this User."
  279. from django.core.mail import send_mail
  280. send_mail(subject, message, from_email, [self.email])
  281. def get_profile(self):
  282. """
  283. Returns site-specific profile for this user. Raises
  284. SiteProfileNotAvailable if this site does not allow profiles.
  285. """
  286. if not hasattr(self, '_profile_cache'):
  287. from django.conf import settings
  288. if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
  289. raise SiteProfileNotAvailable('You need to set AUTH_PROFILE_MO'
  290. 'DULE in your project settings')
  291. try:
  292. app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
  293. except ValueError:
  294. raise SiteProfileNotAvailable('app_label and model_name should'
  295. ' be separated by a dot in the AUTH_PROFILE_MODULE set'
  296. 'ting')
  297. try:
  298. model = models.get_model(app_label, model_name)
  299. if model is None:
  300. raise SiteProfileNotAvailable('Unable to load the profile '
  301. 'model, check AUTH_PROFILE_MODULE in your project sett'
  302. 'ings')
  303. self._profile_cache = model._default_manager.using(self._state.db).get(user__id__exact=self.id)
  304. self._profile_cache.user = self
  305. except (ImportError, ImproperlyConfigured):
  306. raise SiteProfileNotAvailable
  307. return self._profile_cache
  308. class MongoEngineBackend(object):
  309. """Authenticate using MongoEngine and mongoengine.django.auth.User.
  310. """
  311. supports_object_permissions = False
  312. supports_anonymous_user = False
  313. supports_inactive_user = False
  314. _user_doc = False
  315. def authenticate(self, username=None, password=None):
  316. user = self.user_document.objects(username=username).first()
  317. if user:
  318. if password and user.check_password(password):
  319. backend = auth.get_backends()[0]
  320. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
  321. return user
  322. return None
  323. def get_user(self, user_id):
  324. return self.user_document.objects.with_id(user_id)
  325. @property
  326. def user_document(self):
  327. if self._user_doc is False:
  328. from .mongo_auth.models import get_user_document
  329. self._user_doc = get_user_document()
  330. return self._user_doc
  331. def get_user(userid):
  332. """Returns a User object from an id (User.id). Django's equivalent takes
  333. request, but taking an id instead leaves it up to the developer to store
  334. the id in any way they want (session, signed cookie, etc.)
  335. """
  336. if not userid:
  337. return AnonymousUser()
  338. return MongoEngineBackend().get_user(userid) or AnonymousUser()