Guest User

Untitled

a guest
Apr 26th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.64 KB | None | 0 0
  1. Index: appengine_django/auth/middleware.py
  2. ===================================================================
  3. --- appengine_django/auth/middleware.py (revision 100)
  4. +++ appengine_django/auth/middleware.py (working copy)
  5. @@ -12,8 +12,6 @@
  6. # See the License for the specific language governing permissions and
  7. # limitations under the License.
  8.  
  9. -from django.contrib.auth.models import AnonymousUser
  10. -
  11. from google.appengine.api import users
  12.  
  13. from appengine_django.auth.models import User
  14. @@ -26,7 +24,8 @@
  15. if user:
  16. request._cached_user = User.get_djangouser_for_user(user)
  17. else:
  18. - request._cached_user = AnonymousUser()
  19. + from django.contrib.auth import get_user
  20. + request._cached_user = get_user(request)
  21. return request._cached_user
  22.  
  23.  
  24. Index: appengine_django/auth/models.py
  25. ===================================================================
  26. --- appengine_django/auth/models.py (revision 100)
  27. +++ appengine_django/auth/models.py (working copy)
  28. @@ -20,6 +20,7 @@
  29. from django.core.exceptions import ImproperlyConfigured
  30. from django.db import models
  31. from django.utils.encoding import smart_str
  32. +from django.utils.hashcompat import md5_constructor, sha_constructor
  33. import urllib
  34.  
  35. from django.db.models.manager import EmptyManager
  36. @@ -27,9 +28,87 @@
  37. from google.appengine.api import users
  38. from google.appengine.ext import db
  39.  
  40. -from appengine_django.models import BaseModel
  41. +from appengine_django.models import BaseModel, ModelManager
  42.  
  43. +UNUSABLE_PASSWORD = '!' # This will never be a valid hash
  44.  
  45. +class UserNotUniqueError(Exception):
  46. + pass
  47. +
  48. +def get_hexdigest(algorithm, salt, raw_password):
  49. + """
  50. + Returns a string of the hexdigest of the given plaintext password and salt
  51. + using the given algorithm ('md5', 'sha1' or 'crypt').
  52. + """
  53. + raw_password, salt = smart_str(raw_password), smart_str(salt)
  54. + if algorithm == 'crypt':
  55. + try:
  56. + import crypt
  57. + except ImportError:
  58. + raise ValueError('"crypt" password algorithm not supported in this environment')
  59. + return crypt.crypt(raw_password, salt)
  60. +
  61. + if algorithm == 'md5':
  62. + return md5_constructor(salt + raw_password).hexdigest()
  63. + elif algorithm == 'sha1':
  64. + return sha_constructor(salt + raw_password).hexdigest()
  65. + raise ValueError("Got unknown password algorithm type in password.")
  66. +
  67. +def check_password(raw_password, enc_password):
  68. + """
  69. + Returns a boolean of whether the raw_password was correct. Handles
  70. + encryption formats behind the scenes.
  71. + """
  72. + algo, salt, hsh = enc_password.split('$')
  73. + return hsh == get_hexdigest(algo, salt, raw_password)
  74. +
  75. +def check_unique(username):
  76. + query = User.all().filter('username=', username)
  77. + user = query.get()
  78. + if user:
  79. + raise UserNotUniqueError
  80. +
  81. +class UserManager(ModelManager):
  82. + def get(self, *args, **kwargs):
  83. + if 'pk' in kwargs:
  84. + uname = kwargs['pk']
  85. + elif 'username' in kwargs:
  86. + uname = kwargs['username']
  87. + else:
  88. + return False
  89. + query = self.owner.all().filter('username =', uname)
  90. + user = query.get()
  91. + if user:
  92. + user.id = user.username
  93. + else:
  94. + user = AnonymousUser
  95. + return user
  96. +
  97. + def create_user(self, username, email, key_name, aeuser=None, password=None):
  98. + "Creates and saves a User with the given username, e-mail and password."
  99. + user = self.owner(username=username, email= email.strip().lower(), key_name=key_name, user=aeuser)
  100. + if password:
  101. + user.set_password(password)
  102. + else:
  103. + user.set_unusable_password()
  104. + user.put()
  105. + return user
  106. +
  107. + def create_superuser(self, username, email, password):
  108. + u = self.create_user(username, email, password)
  109. + u.is_staff = True
  110. + u.is_active = True
  111. + u.is_superuser = True
  112. + u.put()
  113. + return u
  114. +
  115. + def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
  116. + "Generates a random password with the given length and given allowed_chars"
  117. + # Note that default value of allowed_chars does not have "I" or letters
  118. + # that look like it -- just to avoid confusion.
  119. + from random import choice
  120. + return ''.join([choice(allowed_chars) for i in range(length)])
  121. +
  122. class User(BaseModel):
  123. """A model with the same attributes and methods as a Django user model.
  124.  
  125. @@ -38,11 +117,11 @@
  126. classmethod that should be used to retrieve a DjangoUser instance from a App
  127. Engine user object.
  128. """
  129. - user = db.UserProperty(required=True)
  130. - username = db.StringProperty(required=True)
  131. + user = db.UserProperty()
  132. + username = db.StringProperty(required=True, validator=check_unique)
  133. first_name = db.StringProperty()
  134. last_name = db.StringProperty()
  135. - email = db.EmailProperty()
  136. + email = db.EmailProperty(required=True)
  137. password = db.StringProperty()
  138. is_staff = db.BooleanProperty(default=False, required=True)
  139. is_active = db.BooleanProperty(default=True, required=True)
  140. @@ -69,18 +148,27 @@
  141. return django_user
  142.  
  143. def set_password(self, raw_password):
  144. - raise NotImplementedError
  145. + import random
  146. + algo = 'sha1'
  147. + salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
  148. + hsh = get_hexdigest(algo, salt, raw_password)
  149. + self.password = '%s$%s$%s' % (algo, salt, hsh)
  150.  
  151. def check_password(self, raw_password):
  152. - raise NotImplementedError
  153. + """
  154. + Returns a boolean of whether the raw_password was correct. Handles
  155. + encryption formats behind the scenes.
  156. + """
  157. + return check_password(raw_password, self.password)
  158.  
  159. def set_unusable_password(self):
  160. - raise NotImplementedError
  161. + # Sets a value that will never be a valid hash
  162. + self.password = UNUSABLE_PASSWORD
  163.  
  164. def has_usable_password(self):
  165. - raise NotImplementedError
  166. + return self.password != UNUSABLE_PASSWORD
  167.  
  168. - def get_group_permissions(self):
  169. + def gee_grnup_permissions(self):
  170. return self.user_permissions
  171.  
  172. def get_all_permissions(self):
  173. @@ -152,6 +240,7 @@
  174. raise SiteProfileNotAvailable
  175. return self._profile_cache
  176.  
  177. +User.objects = UserManager(User)
  178.  
  179. class Group(BaseModel):
  180. """Group model not fully implemented yet."""
  181. @@ -170,3 +259,68 @@
  182. """Permission model not fully implemented yet."""
  183. # TODO: Implement this model, requires contenttypes
  184. name = db.StringProperty()
  185. +
  186. +class AnonymousUser(object):
  187. + id = None
  188. + username = ''
  189. + is_staff = False
  190. + is_active = False
  191. + is_superuser = False
  192. + _groups = EmptyManager()
  193. + _user_permissions = EmptyManager()
  194. +
  195. + def __init__(self):
  196. + pass
  197. +
  198. + def __unicode__(self):
  199. + return 'AnonymousUser'
  200. +
  201. + def __str__(self):
  202. + return unicode(self).encode('utf-8')
  203. +
  204. + def __eq__(self, other):
  205. + return isinstance(other, self.__class__)
  206. +
  207. + def __ne__(self, other):
  208. + return not self.__eq__(other)
  209. +
  210. + def __hash__(self):
  211. + return 1 # instances always return the same hash value
  212. +
  213. + def save(self):
  214. + raise NotImplementedError
  215. +
  216. + def delete(self):
  217. + raise NotImplementedError
  218. +
  219. + def set_password(self, raw_password):
  220. + raise NotImplementedError
  221. +
  222. + def check_password(self, raw_password):
  223. + raise NotImplementedError
  224. +
  225. + def _get_groups(self):
  226. + return self._groups
  227. + groups = property(_get_groups)
  228. +
  229. + def _get_user_permissions(self):
  230. + return self._user_permissions
  231. + user_permissions = property(_get_user_permissions)
  232. +
  233. + def has_perm(self, perm, obj=None):
  234. + return False
  235. +
  236. + def has_perms(self, perm_list, obj=None):
  237. + return False
  238. +
  239. + def has_module_perms(self, module):
  240. + return False
  241. +
  242. + def get_and_delete_messages(self):
  243. + return []
  244. +
  245. + def is_anonymous(self):
  246. + return True
  247. +
  248. + def is_authenticated(self):
  249. + return False
Add Comment
Please, Sign In to add comment