change-email-form.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import Ember from 'ember';
  2. import ValidatedForm from 'misago/components/forms/validated-form';
  3. export default ValidatedForm.extend({
  4. tagName: 'form',
  5. classNames: 'form-horizontal',
  6. isBusy: false,
  7. new_email: '',
  8. password: '',
  9. apiUrl: function() {
  10. return 'users/' + this.auth.get('user.id') + '/change-email';
  11. }.property(),
  12. newEmailValidation: function() {
  13. var value = Ember.$.trim(this.get('new_email'));
  14. var state = 'ok';
  15. var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  16. if (value.length === 0) {
  17. state = [gettext('Enter new e-mail.')];
  18. } else if (value === this.get('auth.user.email')) {
  19. state = [gettext('New e-mail is same as current one.')];
  20. } else if (!re.test(value)) {
  21. state = [gettext('Invalid e-mail address.')];
  22. }
  23. this.set('validation.new_email', state);
  24. }.observes('new_email'),
  25. passwordValidation: function() {
  26. var value = Ember.$.trim(this.get('password'));
  27. if (value.length === 0) {
  28. this.set('validation.password', [gettext('Enter current password.')]);
  29. } else {
  30. this.set('validation.password', 'ok');
  31. }
  32. }.observes('password'),
  33. submit: function() {
  34. if (this.get('isBusy')) {
  35. return false;
  36. }
  37. var data = {
  38. new_email: Ember.$.trim(this.get('new_email')),
  39. password: Ember.$.trim(this.get('password')),
  40. };
  41. this.newEmailValidation();
  42. this.passwordValidation();
  43. if (this.hasValidationErrors()) {
  44. this.toast.error(gettext('Form contains errors.'));
  45. return false;
  46. }
  47. this.set('isBusy', true);
  48. var self = this;
  49. this.ajax.post(this.get('apiUrl'), data
  50. ).then(function(response) {
  51. if (self.isDestroyed) { return; }
  52. self.success(response);
  53. }, function(jqXHR) {
  54. if (self.isDestroyed) { return; }
  55. self.error(jqXHR);
  56. }).finally(function() {
  57. if (self.isDestroyed) { return; }
  58. self.set('isBusy', false);
  59. });
  60. return false;
  61. },
  62. success: function(responseJSON) {
  63. this.setProperties({
  64. 'new_email': '',
  65. 'password': '',
  66. });
  67. this.resetValidation();
  68. this.toast.info(responseJSON.detail);
  69. },
  70. error: function(jqXHR) {
  71. var rejection = jqXHR.responseJSON;
  72. if (jqXHR.status === 400) {
  73. this.toast.error(gettext('Form contains errors.'));
  74. this.get('validation').setProperties(rejection);
  75. } else {
  76. this.toast.apiError(jqXHR);
  77. }
  78. },
  79. });