client.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /* global
  2. AT: false
  3. */
  4. "use strict";
  5. // Allowed Internal (client-side) States
  6. AT.prototype.STATES = [
  7. "changePwd", // Change Password
  8. "enrollAccount", // Account Enrollment
  9. "forgotPwd", // Forgot Password
  10. "hide", // Nothing displayed
  11. "resetPwd", // Reset Password
  12. "signIn", // Sign In
  13. "signUp", // Sign Up
  14. "verifyEmail", // Email verification
  15. "resendVerificationEmail", // Resend verification email
  16. ];
  17. AT.prototype._loginType = "";
  18. // Flag telling whether the whole form should appear disabled
  19. AT.prototype._disabled = false;
  20. // State validation
  21. AT.prototype._isValidState = function(value) {
  22. return _.contains(this.STATES, value);
  23. };
  24. // Flags used to avoid clearing errors and redirecting to previous route when
  25. // signing in/up as a results of a call to ensureSignedIn
  26. AT.prototype.avoidRedirect = false;
  27. AT.prototype.avoidClearError = false;
  28. // Token to be provided for routes like reset-password and enroll-account
  29. AT.prototype.paramToken = null;
  30. AT.prototype.loginType = function () {
  31. return this._loginType;
  32. };
  33. AT.prototype.getparamToken = function() {
  34. return this.paramToken;
  35. };
  36. // Getter for current state
  37. AT.prototype.getState = function() {
  38. return this.state.form.get("state");
  39. };
  40. // Getter for disabled state
  41. AT.prototype.disabled = function() {
  42. return this.state.form.equals("disabled", true) ? "disabled" : undefined;
  43. };
  44. // Setter for disabled state
  45. AT.prototype.setDisabled = function(value) {
  46. check(value, Boolean);
  47. return this.state.form.set("disabled", value);
  48. };
  49. // Setter for current state
  50. AT.prototype.setState = function(state, callback) {
  51. check(state, String);
  52. if (!this._isValidState(state) || (this.options.forbidClientAccountCreation && state === 'signUp')) {
  53. throw new Meteor.Error(500, "Internal server error", "accounts-templates-core package got an invalid state value!");
  54. }
  55. this.state.form.set("state", state);
  56. if (!this.avoidClearError) {
  57. this.clearState();
  58. }
  59. this.avoidClearError = false;
  60. if (_.isFunction(callback)) {
  61. callback();
  62. }
  63. };
  64. AT.prototype.clearState = function() {
  65. _.each(this._fields, function(field) {
  66. field.clearStatus();
  67. });
  68. var form = this.state.form;
  69. form.set("error", null);
  70. form.set("result", null);
  71. form.set("message", null);
  72. AccountsTemplates.setDisabled(false);
  73. };
  74. AT.prototype.clearError = function() {
  75. this.state.form.set("error", null);
  76. };
  77. AT.prototype.clearResult = function() {
  78. this.state.form.set("result", null);
  79. };
  80. AT.prototype.clearMessage = function() {
  81. this.state.form.set("message", null);
  82. };
  83. // Initialization
  84. AT.prototype.init = function() {
  85. console.warn("[AccountsTemplates] There is no more need to call AccountsTemplates.init()! Simply remove the call ;-)");
  86. };
  87. AT.prototype._init = function() {
  88. if (this._initialized) {
  89. return;
  90. }
  91. var usernamePresent = this.hasField("username");
  92. var emailPresent = this.hasField("email");
  93. if (usernamePresent && emailPresent) {
  94. this._loginType = "username_and_email";
  95. } else {
  96. this._loginType = usernamePresent ? "username" : "email";
  97. }
  98. if (this._loginType === "username_and_email") {
  99. // Possibly adds the field username_and_email in case
  100. // it was not configured
  101. if (!this.hasField("username_and_email")) {
  102. this.addField({
  103. _id: "username_and_email",
  104. type: "text",
  105. displayName: "usernameOrEmail",
  106. placeholder: "usernameOrEmail",
  107. required: true,
  108. });
  109. }
  110. }
  111. // Only in case password confirmation is required
  112. if (this.options.confirmPassword) {
  113. // Possibly adds the field password_again in case
  114. // it was not configured
  115. if (!this.hasField("password_again")) {
  116. var pwdAgain = _.clone(this.getField("password"));
  117. pwdAgain._id = "password_again";
  118. pwdAgain.displayName = {
  119. "default": "passwordAgain",
  120. changePwd: "newPasswordAgain",
  121. resetPwd: "newPasswordAgain",
  122. };
  123. pwdAgain.placeholder = {
  124. "default": "passwordAgain",
  125. changePwd: "newPasswordAgain",
  126. resetPwd: "newPasswordAgain",
  127. };
  128. this.addField(pwdAgain);
  129. }
  130. } else {
  131. if (this.hasField("password_again")) {
  132. throw new Error("AccountsTemplates: a field password_again was added but confirmPassword is set to false!");
  133. }
  134. }
  135. // Possibly adds the field current_password in case
  136. // it was not configured
  137. if (this.options.enablePasswordChange) {
  138. if (!this.hasField("current_password")) {
  139. this.addField({
  140. _id: "current_password",
  141. type: "password",
  142. displayName: "currentPassword",
  143. placeholder: "currentPassword",
  144. required: true,
  145. });
  146. }
  147. }
  148. // Ensuser the right order of special fields
  149. var moveFieldAfter = function(fieldName, referenceFieldName) {
  150. var fieldIds = AccountsTemplates.getFieldIds();
  151. var refFieldId = _.indexOf(fieldIds, referenceFieldName);
  152. // In case the reference field is not present, just return...
  153. if (refFieldId === -1) {
  154. return;
  155. }
  156. var fieldId = _.indexOf(fieldIds, fieldName);
  157. // In case the sought field is not present, just return...
  158. if (fieldId === -1) {
  159. return;
  160. }
  161. if (fieldId !== -1 && fieldId !== (refFieldId + 1)) {
  162. // removes the field
  163. var field = AccountsTemplates._fields.splice(fieldId, 1)[0];
  164. // push the field right after the reference field position
  165. var newFieldIds = AccountsTemplates.getFieldIds();
  166. var newReferenceFieldId = _.indexOf(newFieldIds, referenceFieldName);
  167. AccountsTemplates._fields.splice(newReferenceFieldId + 1, 0, field);
  168. }
  169. };
  170. // Ensuser the right order of special fields
  171. var moveFieldBefore = function(fieldName, referenceFieldName) {
  172. var fieldIds = AccountsTemplates.getFieldIds();
  173. var refFieldId = _.indexOf(fieldIds, referenceFieldName);
  174. // In case the reference field is not present, just return...
  175. if (refFieldId === -1) {
  176. return;
  177. }
  178. var fieldId = _.indexOf(fieldIds, fieldName);
  179. // In case the sought field is not present, just return...
  180. if (fieldId === -1) {
  181. return;
  182. }
  183. if (fieldId !== -1 && fieldId !== (refFieldId - 1)) {
  184. // removes the field
  185. var field = AccountsTemplates._fields.splice(fieldId, 1)[0];
  186. // push the field right after the reference field position
  187. var newFieldIds = AccountsTemplates.getFieldIds();
  188. var newReferenceFieldId = _.indexOf(newFieldIds, referenceFieldName);
  189. AccountsTemplates._fields.splice(newReferenceFieldId, 0, field);
  190. }
  191. };
  192. // The final order should be something like:
  193. // - username
  194. // - email
  195. // - username_and_email
  196. // - password
  197. // - password_again
  198. //
  199. // ...so lets do it in reverse order...
  200. moveFieldAfter("username_and_email", "username");
  201. moveFieldAfter("username_and_email", "email");
  202. moveFieldBefore("current_password", "password");
  203. moveFieldAfter("password", "current_password");
  204. moveFieldAfter("password_again", "password");
  205. // Sets visibility condition and validation flags for each field
  206. var gPositiveValidation = !!AccountsTemplates.options.positiveValidation;
  207. var gNegativeValidation = !!AccountsTemplates.options.negativeValidation;
  208. var gShowValidating = !!AccountsTemplates.options.showValidating;
  209. var gContinuousValidation = !!AccountsTemplates.options.continuousValidation;
  210. var gNegativeFeedback = !!AccountsTemplates.options.negativeFeedback;
  211. var gPositiveFeedback = !!AccountsTemplates.options.positiveFeedback;
  212. _.each(this._fields, function(field) {
  213. // Visibility
  214. switch(field._id) {
  215. case "current_password":
  216. field.visible = ["changePwd"];
  217. break;
  218. case "email":
  219. field.visible = ["forgotPwd", "signUp", "resendVerificationEmail"];
  220. if (AccountsTemplates.loginType() === "email") {
  221. field.visible.push("signIn");
  222. }
  223. break;
  224. case "password":
  225. field.visible = ["changePwd", "enrollAccount", "resetPwd", "signIn", "signUp"];
  226. break;
  227. case "password_again":
  228. field.visible = ["changePwd", "enrollAccount", "resetPwd", "signUp"];
  229. break;
  230. case "username":
  231. field.visible = ["signUp"];
  232. if (AccountsTemplates.loginType() === "username") {
  233. field.visible.push("signIn");
  234. }
  235. break;
  236. case "username_and_email":
  237. field.visible = [];
  238. if (AccountsTemplates.loginType() === "username_and_email") {
  239. field.visible.push("signIn");
  240. }
  241. break;
  242. default:
  243. field.visible = ["signUp"];
  244. }
  245. // Validation
  246. var positiveValidation = field.positiveValidation;
  247. if (_.isUndefined(positiveValidation)) {
  248. field.positiveValidation = gPositiveValidation;
  249. }
  250. var negativeValidation = field.negativeValidation;
  251. if (_.isUndefined(negativeValidation)) {
  252. field.negativeValidation = gNegativeValidation;
  253. }
  254. field.validation = field.positiveValidation || field.negativeValidation;
  255. if (_.isUndefined(field.continuousValidation)) {
  256. field.continuousValidation = gContinuousValidation;
  257. }
  258. field.continuousValidation = field.validation && field.continuousValidation;
  259. if (_.isUndefined(field.negativeFeedback)) {
  260. field.negativeFeedback = gNegativeFeedback;
  261. }
  262. if (_.isUndefined(field.positiveFeedback)) {
  263. field.positiveFeedback = gPositiveFeedback;
  264. }
  265. field.feedback = field.negativeFeedback || field.positiveFeedback;
  266. // Validating icon
  267. var showValidating = field.showValidating;
  268. if (_.isUndefined(showValidating)) {
  269. field.showValidating = gShowValidating;
  270. }
  271. // Custom Template
  272. if (field.template) {
  273. if (field.template in Template) {
  274. Template[field.template].helpers(AccountsTemplates.atInputHelpers);
  275. } else {
  276. console.warn(
  277. "[UserAccounts] Warning no template " + field.template + " found!"
  278. );
  279. }
  280. }
  281. });
  282. // Initializes reactive states
  283. var form = new ReactiveDict();
  284. form.set("disabled", false);
  285. form.set("state", "signIn");
  286. form.set("result", null);
  287. form.set("error", null);
  288. form.set("message", null);
  289. this.state = {
  290. form: form,
  291. };
  292. // Possibly subscribes to extended user data (to get the list of registered services...)
  293. if (this.options.showAddRemoveServices) {
  294. Meteor.subscribe("userRegisteredServices");
  295. }
  296. //Check that reCaptcha site keys are available and no secret keys visible
  297. if (this.options.showReCaptcha) {
  298. var atSiteKey = null;
  299. var atSecretKey = null;
  300. var settingsSiteKey = null;
  301. var settingsSecretKey = null;
  302. if (AccountsTemplates.options.reCaptcha) {
  303. atSiteKey = AccountsTemplates.options.reCaptcha.siteKey;
  304. atSecretKey = AccountsTemplates.options.reCaptcha.secretKey;
  305. }
  306. if (Meteor.settings && Meteor.settings.public && Meteor.settings.public.reCaptcha) {
  307. settingsSiteKey = Meteor.settings.public.reCaptcha.siteKey;
  308. settingsSecretKey = Meteor.settings.public.reCaptcha.secretKey;
  309. }
  310. if (atSecretKey || settingsSecretKey) {
  311. //erase the secret key
  312. if (atSecretKey) {
  313. AccountsTemplates.options.reCaptcha.secretKey = null;
  314. }
  315. if (settingsSecretKey) {
  316. Meteor.settings.public.reCaptcha.secretKey = null;
  317. }
  318. var loc = atSecretKey ? "User Accounts configuration!" : "Meteor settings!";
  319. throw new Meteor.Error(401, "User Accounts: DANGER - reCaptcha private key leaked to client from " + loc
  320. + " Provide the key in server settings ONLY.");
  321. }
  322. if (!atSiteKey && !settingsSiteKey) {
  323. throw new Meteor.Error(401, "User Accounts: reCaptcha site key not found! Please provide it or set showReCaptcha to false.");
  324. }
  325. }
  326. // Marks AccountsTemplates as initialized
  327. this._initialized = true;
  328. };
  329. AT.prototype.linkClick = function(route) {
  330. if (AccountsTemplates.disabled()) {
  331. return;
  332. }
  333. AccountsTemplates.setState(route);
  334. if (AccountsTemplates.options.focusFirstInput) {
  335. var firstVisibleInput = _.find(this.getFields(), function(f) {
  336. return _.contains(f.visible, route);
  337. });
  338. if (firstVisibleInput) {
  339. $("input#at-field-" + firstVisibleInput._id).focus();
  340. }
  341. }
  342. };
  343. AT.prototype.logout = function() {
  344. var onLogoutHook = AccountsTemplates.options.onLogoutHook;
  345. Meteor.logout(function() {
  346. if (onLogoutHook) {
  347. onLogoutHook();
  348. }
  349. });
  350. };
  351. AT.prototype.submitCallback = function(error, state, onSuccess) {
  352. var onSubmitHook = AccountsTemplates.options.onSubmitHook;
  353. if (onSubmitHook) {
  354. onSubmitHook(error, state);
  355. }
  356. if (error) {
  357. if (_.isObject(error.details)) {
  358. // If error.details is an object, we may try to set fields errors from it
  359. _.each(error.details, function(error, fieldId) {
  360. AccountsTemplates.getField(fieldId).setError(error);
  361. });
  362. } else {
  363. var err = "error.accounts.Unknown error";
  364. if (error.reason) {
  365. err = error.reason;
  366. }
  367. if (err.substring(0, 15) !== "error.accounts.") {
  368. err = "error.accounts." + err;
  369. }
  370. AccountsTemplates.state.form.set("error", [err]);
  371. }
  372. AccountsTemplates.setDisabled(false);
  373. // Possibly resets reCaptcha form
  374. if (state === "signUp" && AccountsTemplates.options.showReCaptcha) {
  375. grecaptcha.reset();
  376. }
  377. } else {
  378. if (onSuccess) {
  379. onSuccess();
  380. }
  381. if (state) {
  382. AccountsTemplates.setDisabled(false);
  383. }
  384. }
  385. };
  386. AccountsTemplates = new AT();
  387. // Initialization
  388. Meteor.startup(function() {
  389. AccountsTemplates._init();
  390. });