api.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. Module functions for ACLs
  3. Workflow for ACLs in Misago is simple:
  4. First, you get user ACL. Its directory that you can introspect to find out user
  5. permissions, or if you have objects, you can use this acl to make those objects
  6. aware of their ACLs. This gives objects themselves special "acl" attribute with
  7. properties defined by ACL providers within their "add_acl_to_target"
  8. """
  9. import copy
  10. from misago.core import threadstore
  11. from misago.core.cache import cache
  12. from . import version
  13. from .builder import build_acl
  14. from .providers import providers
  15. def get_user_acl(user):
  16. """
  17. Get ACL for User
  18. """
  19. acl_key = 'acl_%s' % user.acl_key
  20. acl_cache = threadstore.get(acl_key)
  21. if not acl_cache:
  22. acl_cache = cache.get(acl_key)
  23. if acl_cache and version.is_valid(acl_cache.get('_acl_version')):
  24. return acl_cache
  25. else:
  26. new_acl = build_acl(user.get_roles())
  27. new_acl['_acl_version'] = version.get_version()
  28. threadstore.set(acl_key, new_acl)
  29. cache.set(acl_key, new_acl)
  30. return new_acl
  31. def add_acl(user, target):
  32. """
  33. Add valid ACL to target (iterable of objects or single object)
  34. """
  35. if hasattr(target, '__iter__'):
  36. for item in target:
  37. _add_acl_to_target(user, item)
  38. else:
  39. _add_acl_to_target(user, target)
  40. def _add_acl_to_target(user, target):
  41. """
  42. Add valid ACL to single target, helper for add_acl function
  43. """
  44. target.acl = {}
  45. for annotator in providers.get_type_annotators(target):
  46. annotator(user, target)
  47. def serialize_acl(target):
  48. """
  49. Serialize authenticated user's ACL
  50. """
  51. serialized_acl = copy.deepcopy(target.acl_cache)
  52. for serializer in providers.get_type_serializers(target):
  53. serializer(serialized_acl)
  54. return serialized_acl