utils.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from django.conf import settings
  2. from django.db.models import Q
  3. from social_core.storage import NO_ASCII_REGEX, NO_SPECIAL_REGEX
  4. __all__ = (
  5. 'clean_username',
  6. 'get_current_pepper',
  7. 'user_may_grant_token',
  8. )
  9. def user_may_grant_token(requesting_user, token_user):
  10. """
  11. Return True if *requesting_user* has permission to create a token for *token_user*,
  12. respecting ObjectPermission constraints on the users.grant_token permission.
  13. ``has_perm('users.grant_token', obj=None)`` always short-circuits to True when the
  14. permission is present in the cache (obj=None bypasses constraint evaluation in
  15. ObjectPermissionMixin.has_perm). Since the new token does not yet exist in the
  16. database we cannot pass an existing Token as obj. Instead we extract the raw
  17. constraint list, remap Token-field paths to User-field paths, and evaluate them
  18. directly against the target User record — the only variable in a new token creation.
  19. Field remapping rules:
  20. ``user__<field>`` → ``<field>`` (FK traversal into User)
  21. ``user`` → ``pk`` (Token.user FK becomes User.pk)
  22. Constraints referencing other Token fields cannot be evaluated for an unsaved
  23. token; the function returns False (deny) for those.
  24. """
  25. from users.models import User
  26. # Mirrors ObjectPermissionMixin.has_perm: superusers implicitly have all permissions.
  27. if requesting_user.is_active and requesting_user.is_superuser:
  28. return True
  29. perm = 'users.grant_token'
  30. # get_all_permissions() populates _object_perm_cache as a side effect.
  31. # Guard against missing cache key in case a non-standard backend is in use.
  32. if perm not in requesting_user.get_all_permissions():
  33. return False
  34. constraints = getattr(requesting_user, '_object_perm_cache', {}).get(perm, [])
  35. # An empty/null constraint means "no restriction" — allow any target.
  36. if any(not c for c in constraints):
  37. return True
  38. # Substitute the $user token so {"user": "$user"} resolves to the requesting user.
  39. resolved_user_id = requesting_user.pk
  40. q = Q()
  41. for constraint in constraints:
  42. user_constraint = {}
  43. for key, raw_val in constraint.items():
  44. val = resolved_user_id if raw_val == '$user' else raw_val
  45. if key == 'user':
  46. user_constraint['pk'] = val
  47. elif key.startswith('user__'):
  48. user_constraint[key.removeprefix('user__')] = val
  49. else:
  50. # Non-user Token field — cannot evaluate for a new (unsaved) token.
  51. # Fail closed.
  52. return False
  53. q |= Q(**user_constraint)
  54. return User.objects.filter(q, pk=token_user.pk).exists()
  55. def clean_username(value):
  56. """Clean username removing any unsupported character"""
  57. value = NO_ASCII_REGEX.sub('', value)
  58. value = NO_SPECIAL_REGEX.sub('', value)
  59. value = value.replace(':', '')
  60. return value
  61. def get_current_pepper():
  62. """
  63. Return the ID and value of the newest (highest ID) cryptographic pepper.
  64. """
  65. if not settings.API_TOKEN_PEPPERS:
  66. raise ValueError("API_TOKEN_PEPPERS is not defined")
  67. newest_id = sorted(settings.API_TOKEN_PEPPERS.keys())[-1]
  68. return newest_id, settings.API_TOKEN_PEPPERS[newest_id]