api.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.core.exceptions import ValidationError
  2. from django.http import JsonResponse
  3. from django.utils.translation import ugettext as _
  4. from misago.core.decorators import ajax_only, require_POST
  5. from misago.users import validators
  6. def api(f):
  7. @ajax_only
  8. @require_POST
  9. def decorator(request, *args, **kwargs):
  10. try:
  11. return JsonResponse({
  12. 'has_error': 0,
  13. 'message': f(request, *args, **kwargs),
  14. })
  15. except ValidationError as e:
  16. return JsonResponse({
  17. 'has_error': 1,
  18. 'message': unicode(e.message)
  19. })
  20. return decorator
  21. @api
  22. def validate_username(request, exclude=None):
  23. try:
  24. validators.validate_username(request.POST['username'])
  25. return _("Entered username is valid.")
  26. except KeyError:
  27. raise ValidationError(_('Enter username.'))
  28. @api
  29. def validate_email(request, exclude=None):
  30. try:
  31. validators.validate_email(request.POST['email'])
  32. return _("Entered e-mail is valid.")
  33. except KeyError:
  34. raise ValidationError(_('Enter e-mail address.'))
  35. @api
  36. def validate_password(request, exclude=None):
  37. try:
  38. validators.validate_password(request.POST['password'])
  39. return _("Entered password is valid.")
  40. except KeyError:
  41. raise ValidationError(_('Enter password.'))