asyncForm.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import App from '../base'
  2. import '../vendor/libs/passfield'
  3. App.directive('asyncForm', [
  4. '$http',
  5. 'validateCaptcha',
  6. 'validateCaptchaV3',
  7. function ($http, validateCaptcha, validateCaptchaV3) {
  8. return {
  9. controller: [
  10. '$scope',
  11. '$location',
  12. function ($scope, $location) {
  13. this.getEmail = () => $scope.email
  14. this.getEmailFromQuery = () =>
  15. $location.search().email || $location.search().new_email
  16. return this
  17. },
  18. ],
  19. link(scope, element, attrs, ctrl) {
  20. let response
  21. const formName = attrs.asyncForm
  22. scope[attrs.name].response = response = {}
  23. scope[attrs.name].inflight = false
  24. scope.email =
  25. scope.email ||
  26. scope.usersEmail ||
  27. ctrl.getEmailFromQuery() ||
  28. attrs.newEmail
  29. const validateCaptchaIfEnabled = function (callback) {
  30. scope.$applyAsync(() => {
  31. scope[attrs.name].inflight = true
  32. })
  33. if (attrs.captchaActionName) {
  34. validateCaptchaV3(attrs.captchaActionName)
  35. }
  36. if (attrs.captcha != null) {
  37. validateCaptcha(callback)
  38. } else {
  39. callback()
  40. }
  41. }
  42. const _submitRequest = function (grecaptchaResponse) {
  43. const formData = {}
  44. for (const data of Array.from(element.serializeArray())) {
  45. formData[data.name] = data.value
  46. }
  47. if (grecaptchaResponse) {
  48. formData['g-recaptcha-response'] = grecaptchaResponse
  49. }
  50. // clear the response object which may be referenced downstream
  51. Object.keys(response).forEach(field => delete response[field])
  52. // for asyncForm prevent automatic redirect to /login if
  53. // authentication fails, we will handle it ourselves
  54. const httpRequestFn = _httpRequestFn(element.attr('method'))
  55. return httpRequestFn(element.attr('action'), formData, {
  56. disableAutoLoginRedirect: true,
  57. })
  58. .then(function (httpResponse) {
  59. const { data, headers } = httpResponse
  60. scope[attrs.name].inflight = false
  61. response.success = true
  62. response.error = false
  63. const onSuccessHandler = scope[attrs.onSuccess]
  64. if (onSuccessHandler) {
  65. onSuccessHandler(httpResponse)
  66. return
  67. }
  68. if (data.redir) {
  69. ga('send', 'event', formName, 'success')
  70. return (window.location = data.redir)
  71. } else if (data.message) {
  72. response.message = data.message
  73. if (data.message.type === 'error') {
  74. response.success = false
  75. response.error = true
  76. return ga('send', 'event', formName, 'failure', data.message)
  77. } else {
  78. return ga('send', 'event', formName, 'success')
  79. }
  80. } else if (scope.$eval(attrs.asyncFormDownloadResponse)) {
  81. const blob = new Blob([data], {
  82. type: headers('Content-Type'),
  83. })
  84. location.href = URL.createObjectURL(blob) // Trigger file save
  85. }
  86. })
  87. .catch(function (httpResponse) {
  88. const { data, status } = httpResponse
  89. scope[attrs.name].inflight = false
  90. response.success = false
  91. response.error = true
  92. response.status = status
  93. response.data = data
  94. const onErrorHandler = scope[attrs.onError]
  95. if (onErrorHandler) {
  96. onErrorHandler(httpResponse)
  97. return
  98. }
  99. let responseMessage
  100. if (data.message && data.message.text) {
  101. responseMessage = data.message.text
  102. } else {
  103. responseMessage = data.message
  104. }
  105. if (status === 400) {
  106. // Bad Request
  107. response.message = {
  108. text:
  109. responseMessage ||
  110. 'Invalid Request. Please correct the data and try again.',
  111. type: 'error',
  112. }
  113. } else if (status === 403) {
  114. // Forbidden
  115. response.message = {
  116. text:
  117. responseMessage ||
  118. 'Session error. Please check you have cookies enabled. If the problem persists, try clearing your cache and cookies.',
  119. type: 'error',
  120. }
  121. } else if (status === 429) {
  122. response.message = {
  123. text:
  124. responseMessage ||
  125. 'Too many attempts. Please wait for a while and try again.',
  126. type: 'error',
  127. }
  128. } else {
  129. response.message = {
  130. text:
  131. responseMessage ||
  132. 'Something went wrong talking to the server :(. Please try again.',
  133. type: 'error',
  134. }
  135. }
  136. ga('send', 'event', formName, 'failure', data.message)
  137. })
  138. }
  139. const submit = () =>
  140. validateCaptchaIfEnabled(response => _submitRequest(response))
  141. const _httpRequestFn = (method = 'post') => {
  142. const $HTTP_FNS = {
  143. post: $http.post,
  144. get: $http.get,
  145. }
  146. return $HTTP_FNS[method.toLowerCase()]
  147. }
  148. element.on('submit', function (e) {
  149. e.preventDefault()
  150. submit()
  151. })
  152. if (attrs.autoSubmit) {
  153. submit()
  154. }
  155. },
  156. }
  157. },
  158. ])
  159. App.directive('formMessages', function () {
  160. return {
  161. restrict: 'E',
  162. template: `\
  163. <div class="alert" ng-class="{
  164. 'alert-danger': form.response.message.type == 'error',
  165. 'alert-success': form.response.message.type != 'error'
  166. }" ng-show="!!form.response.message" ng-bind-html="form.response.message.text">
  167. </div>
  168. <div ng-transclude></div>\
  169. `,
  170. transclude: true,
  171. scope: {
  172. form: '=for',
  173. },
  174. }
  175. })