Guest User

Untitled

a guest
Oct 7th, 2018
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. from django.db.models import Q
  2. from django.contrib.auth.models import User
  3. from django.contrib.auth.backends import ModelBackend
  4. from piston.authentication import (OAuthAuthentication as
  5. PistonOAuthAuthentication, send_oauth_error)
  6. from piston import oauth
  7. from model_cache import ModelCache
  8.  
  9.  
  10. user_cache = ModelCache(User)
  11.  
  12.  
  13. class OAuthAuthentication(PistonOAuthAuthentication):
  14. """
  15. Replacement for piston.authentication.OAuthAuthentication that utilizes
  16. the cache for it's lookups
  17. """
  18. def is_authenticated(self, request):
  19. """
  20. piston.authentication.OAuthAuthentication sets request.user,
  21. request.consumer and request.throttle_extra from token.consumer.id.
  22. This little hack alleviates having to fetch `token.consumer` and
  23. `token.user` if the request does not need it.
  24. """
  25.  
  26. if self.is_valid_request(request):
  27. try:
  28. consumer, token, params = self.validate_token(request)
  29. except oauth.OAuthError, err:
  30. print send_oauth_error(err)
  31. return False
  32. if consumer and token:
  33. #import pdb; pdb.set_trace()
  34.  
  35. request.user = user_cache(Q(pk=token.user_id))
  36. request.consumer = consumer
  37. request.token = token
  38. request.throttle_extra = consumer.id
  39. return True
  40. return False
  41.  
  42.  
  43. class CachedUserBackend(ModelBackend):
  44. """
  45. A django.contrib.auth.backends.ModelBackend that gets it's user from the
  46. cache if possible
  47. """
  48. def authenticate(self, username=None, password=None):
  49. try:
  50. user = user_cache(Q(username=username))
  51. if user.check_password(password):
  52. return user
  53. except User.DoesNotExist:
  54. return None
Add Comment
Please, Sign In to add comment