{"version":3,"sources":["meteor://💻app/packages/accounts-password/email_templates.js","meteor://💻app/packages/accounts-password/password_server.js"],"names":["_objectSpread","module","link","default","v","greet","welcomeMsg","user","url","greeting","profile","name","Accounts","emailTemplates","from","siteName","Meteor","absoluteUrl","replace","resetPassword","subject","text","verifyEmail","enrollAccount","bcrypt","bcryptHash","wrapAsync","hash","bcryptCompare","compare","getUserById","id","options","users","findOne","_addDefaultFieldSelector","_bcryptRounds","_options","bcryptRounds","getPasswordString","password","SHA256","algorithm","Error","digest","hashPassword","getRoundsFromBcryptHash","rounds","hashSegments","split","length","parseInt","_checkPasswordUserFields","_id","services","_checkPassword","result","userId","formattedPassword","hashRounds","error","_handleError","defer","update","$set","checkPassword","findUserByUsername","username","_findUserByQuery","findUserByEmail","email","NonEmptyString","Match","Where","x","check","String","passwordValidator","OneOf","str","test","settings","packages","accounts","passwordMaxLength","registerLoginHandler","undefined","_userQueryValidator","code","Optional","fields","_is2faEnabledForUser","_isTokenValid","twoFactorAuthentication","secret","setUsername","newUsername","oldUsername","_checkForCaseInsensitiveDuplicates","ex","methods","changePassword","oldPassword","newPassword","hashed","currentToken","_getLoginToken","connection","$pull","hashedToken","$ne","$unset","passwordChanged","setPassword","newPlaintextPassword","Maybe","logout","Boolean","pluckAddresses","emails","map","address","forgotPassword","caseSensitiveEmail","find","toLowerCase","sendResetPasswordEmail","generateResetToken","reason","extraTokenData","includes","token","Random","tokenRecord","when","Date","Object","assign","_ensure","enroll","reset","generateVerificationToken","emailRecord","e","verified","$push","verificationTokens","push","extraParams","realEmail","urls","generateOptionsForEmail","Email","send","isDevelopment","console","log","sendEnrollmentEmail","args","_loginMethod","isEnroll","tokenLifetimeMs","_getPasswordResetTokenLifetimeMs","_getPasswordEnrollTokenLifetimeMs","currentTimeMs","now","oldToken","_setLoginToken","resetToOldToken","affectedRecords","err","_clearAllLoginTokens","sendVerificationEmail","t","emailsRecord","addEmail","newEmail","caseInsensitiveRegExp","RegExp","_escapeRegExp","didUpdateOwnEmail","reduce","prev","$addToSet","removeEmail","createUser","ObjectIncluding","_createUserCheckingDuplicates","forbidClientAccountCreation","createUserVerifyingEmail","callback","createIndex","unique","sparse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAIA,aAAJ;;AAAkBC,MAAM,CAACC,IAAP,CAAY,sCAAZ,EAAmD;AAACC,SAAO,CAACC,CAAD,EAAG;AAACJ,iBAAa,GAACI,CAAd;AAAgB;;AAA5B,CAAnD,EAAiF,CAAjF;;AAAlB,MAAMC,KAAK,GAAGC,UAAU,IAAI,CAACC,IAAD,EAAOC,GAAP,KAAe;AACzC,QAAMC,QAAQ,GACZF,IAAI,CAACG,OAAL,IAAgBH,IAAI,CAACG,OAAL,CAAaC,IAA7B,mBACaJ,IAAI,CAACG,OAAL,CAAaC,IAD1B,SAEI,QAHN;AAIA,mBAAUF,QAAV,iBAEAH,UAFA,+CAIAE,GAJA;AAQD,CAbD;AAeA;AACA;AACA;AACA;AACA;;;AACAI,QAAQ,CAACC,cAAT,mCACMD,QAAQ,CAACC,cAAT,IAA2B,EADjC;AAEEC,MAAI,EAAE,yCAFR;AAGEC,UAAQ,EAAEC,MAAM,CAACC,WAAP,GACPC,OADO,CACC,cADD,EACiB,EADjB,EAEPA,OAFO,CAEC,KAFD,EAEQ,EAFR,CAHZ;AAOEC,eAAa,EAAE;AACbC,WAAO,EAAE,8CAC0BR,QAAQ,CAACC,cAAT,CAAwBE,QADlD,CADI;AAGbM,QAAI,EAAEhB,KAAK,CAAC,wBAAD;AAHE,GAPjB;AAYEiB,aAAW,EAAE;AACXF,WAAO,EAAE,+CAC2BR,QAAQ,CAACC,cAAT,CAAwBE,QADnD,CADE;AAGXM,QAAI,EAAEhB,KAAK,CAAC,8BAAD;AAHA,GAZf;AAiBEkB,eAAa,EAAE;AACbH,WAAO,EAAE,uDACmCR,QAAQ,CAACC,cAAT,CAAwBE,QAD3D,CADI;AAGbM,QAAI,EAAEhB,KAAK,CAAC,4BAAD;AAH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/accounts-password.js","sourcesContent":["const greet = welcomeMsg => (user, url) => {\n const greeting =\n user.profile && user.profile.name\n ? `Hello ${user.profile.name},`\n : 'Hello,';\n return `${greeting}\n\n${welcomeMsg}, simply click the link below.\n\n${url}\n\nThank you.\n`;\n};\n\n/**\n * @summary Options to customize emails sent from the Accounts system.\n * @locus Server\n * @importFromPackage accounts-base\n */\nAccounts.emailTemplates = {\n ...(Accounts.emailTemplates || {}),\n from: 'Accounts Example ',\n siteName: Meteor.absoluteUrl()\n .replace(/^https?:\\/\\//, '')\n .replace(/\\/$/, ''),\n\n resetPassword: {\n subject: () =>\n `How to reset your password on ${Accounts.emailTemplates.siteName}`,\n text: greet('To reset your password'),\n },\n verifyEmail: {\n subject: () =>\n `How to verify email address on ${Accounts.emailTemplates.siteName}`,\n text: greet('To verify your account email'),\n },\n enrollAccount: {\n subject: () =>\n `An account has been created for you on ${Accounts.emailTemplates.siteName}`,\n text: greet('To start using the service'),\n },\n};\n","import bcrypt from 'bcrypt'\nimport {Accounts} from \"meteor/accounts-base\";\n\nconst bcryptHash = Meteor.wrapAsync(bcrypt.hash);\nconst bcryptCompare = Meteor.wrapAsync(bcrypt.compare);\n\n// Utility for grabbing user\nconst getUserById = (id, options) => Meteor.users.findOne(id, Accounts._addDefaultFieldSelector(options));\n\n// User records have a 'services.password.bcrypt' field on them to hold\n// their hashed passwords.\n//\n// When the client sends a password to the server, it can either be a\n// string (the plaintext password) or an object with keys 'digest' and\n// 'algorithm' (must be \"sha-256\" for now). The Meteor client always sends\n// password objects { digest: *, algorithm: \"sha-256\" }, but DDP clients\n// that don't have access to SHA can just send plaintext passwords as\n// strings.\n//\n// When the server receives a plaintext password as a string, it always\n// hashes it with SHA256 before passing it into bcrypt. When the server\n// receives a password as an object, it asserts that the algorithm is\n// \"sha-256\" and then passes the digest to bcrypt.\n\n\nAccounts._bcryptRounds = () => Accounts._options.bcryptRounds || 10;\n\n// Given a 'password' from the client, extract the string that we should\n// bcrypt. 'password' can be one of:\n// - String (the plaintext password)\n// - Object with 'digest' and 'algorithm' keys. 'algorithm' must be \"sha-256\".\n//\nconst getPasswordString = password => {\n if (typeof password === \"string\") {\n password = SHA256(password);\n } else { // 'password' is an object\n if (password.algorithm !== \"sha-256\") {\n throw new Error(\"Invalid password hash algorithm. \" +\n \"Only 'sha-256' is allowed.\");\n }\n password = password.digest;\n }\n return password;\n};\n\n// Use bcrypt to hash the password for storage in the database.\n// `password` can be a string (in which case it will be run through\n// SHA256 before bcrypt) or an object with properties `digest` and\n// `algorithm` (in which case we bcrypt `password.digest`).\n//\nconst hashPassword = password => {\n password = getPasswordString(password);\n return bcryptHash(password, Accounts._bcryptRounds());\n};\n\n// Extract the number of rounds used in the specified bcrypt hash.\nconst getRoundsFromBcryptHash = hash => {\n let rounds;\n if (hash) {\n const hashSegments = hash.split('$');\n if (hashSegments.length > 2) {\n rounds = parseInt(hashSegments[2], 10);\n }\n }\n return rounds;\n};\n\n// Check whether the provided password matches the bcrypt'ed password in\n// the database user record. `password` can be a string (in which case\n// it will be run through SHA256 before bcrypt) or an object with\n// properties `digest` and `algorithm` (in which case we bcrypt\n// `password.digest`).\n//\n// The user parameter needs at least user._id and user.services\nAccounts._checkPasswordUserFields = {_id: 1, services: 1};\n//\nAccounts._checkPassword = (user, password) => {\n const result = {\n userId: user._id\n };\n\n const formattedPassword = getPasswordString(password);\n const hash = user.services.password.bcrypt;\n const hashRounds = getRoundsFromBcryptHash(hash);\n\n if (! bcryptCompare(formattedPassword, hash)) {\n result.error = Accounts._handleError(\"Incorrect password\", false);\n } else if (hash && Accounts._bcryptRounds() != hashRounds) {\n // The password checks out, but the user's bcrypt hash needs to be updated.\n Meteor.defer(() => {\n Meteor.users.update({ _id: user._id }, {\n $set: {\n 'services.password.bcrypt':\n bcryptHash(formattedPassword, Accounts._bcryptRounds())\n }\n });\n });\n }\n\n return result;\n};\nconst checkPassword = Accounts._checkPassword;\n\n///\n/// LOGIN\n///\n\n\n/**\n * @summary Finds the user with the specified username.\n * First tries to match username case sensitively; if that fails, it\n * tries case insensitively; but if more than one user matches the case\n * insensitive search, it returns null.\n * @locus Server\n * @param {String} username The username to look for\n * @param {Object} [options]\n * @param {MongoFieldSpecifier} options.fields Dictionary of fields to return or exclude.\n * @returns {Object} A user if found, else null\n * @importFromPackage accounts-base\n */\nAccounts.findUserByUsername =\n (username, options) => Accounts._findUserByQuery({ username }, options);\n\n/**\n * @summary Finds the user with the specified email.\n * First tries to match email case sensitively; if that fails, it\n * tries case insensitively; but if more than one user matches the case\n * insensitive search, it returns null.\n * @locus Server\n * @param {String} email The email address to look for\n * @param {Object} [options]\n * @param {MongoFieldSpecifier} options.fields Dictionary of fields to return or exclude.\n * @returns {Object} A user if found, else null\n * @importFromPackage accounts-base\n */\nAccounts.findUserByEmail =\n (email, options) => Accounts._findUserByQuery({ email }, options);\n\n// XXX maybe this belongs in the check package\nconst NonEmptyString = Match.Where(x => {\n check(x, String);\n return x.length > 0;\n});\n\nconst passwordValidator = Match.OneOf(\n Match.Where(str => Match.test(str, String) && str.length <= Meteor.settings?.packages?.accounts?.passwordMaxLength || 256), {\n digest: Match.Where(str => Match.test(str, String) && str.length === 64),\n algorithm: Match.OneOf('sha-256')\n }\n);\n\n// Handler to login with a password.\n//\n// The Meteor client sets options.password to an object with keys\n// 'digest' (set to SHA256(password)) and 'algorithm' (\"sha-256\").\n//\n// For other DDP clients which don't have access to SHA, the handler\n// also accepts the plaintext password in options.password as a string.\n//\n// (It might be nice if servers could turn the plaintext password\n// option off. Or maybe it should be opt-in, not opt-out?\n// Accounts.config option?)\n//\n// Note that neither password option is secure without SSL.\n//\nAccounts.registerLoginHandler(\"password\", options => {\n if (!options.password)\n return undefined; // don't handle\n\n check(options, {\n user: Accounts._userQueryValidator,\n password: passwordValidator,\n code: Match.Optional(NonEmptyString),\n });\n\n\n const user = Accounts._findUserByQuery(options.user, {fields: {\n services: 1,\n ...Accounts._checkPasswordUserFields,\n }});\n if (!user) {\n Accounts._handleError(\"User not found\");\n }\n\n\n if (!user.services || !user.services.password ||\n !user.services.password.bcrypt) {\n Accounts._handleError(\"User has no password set\");\n }\n\n const result = checkPassword(user, options.password);\n // This method is added by the package accounts-2fa\n // First the login is validated, then the code situation is checked\n if (\n !result.error &&\n Accounts._is2faEnabledForUser &&\n Accounts._is2faEnabledForUser(options.user)\n ) {\n if (!options.code) {\n Accounts._handleError('2FA code must be informed', true, 'no-2fa-code');\n }\n if (\n !Accounts._isTokenValid(\n user.services.twoFactorAuthentication.secret,\n options.code\n )\n ) {\n Accounts._handleError('Invalid 2FA code', true, 'invalid-2fa-code');\n }\n }\n\n return result;\n});\n\n///\n/// CHANGING\n///\n\n/**\n * @summary Change a user's username. Use this instead of updating the\n * database directly. The operation will fail if there is an existing user\n * with a username only differing in case.\n * @locus Server\n * @param {String} userId The ID of the user to update.\n * @param {String} newUsername A new username for the user.\n * @importFromPackage accounts-base\n */\nAccounts.setUsername = (userId, newUsername) => {\n check(userId, NonEmptyString);\n check(newUsername, NonEmptyString);\n\n const user = getUserById(userId, {fields: {\n username: 1,\n }});\n if (!user) {\n Accounts._handleError(\"User not found\");\n }\n\n const oldUsername = user.username;\n\n // Perform a case insensitive check for duplicates before update\n Accounts._checkForCaseInsensitiveDuplicates('username',\n 'Username', newUsername, user._id);\n\n Meteor.users.update({_id: user._id}, {$set: {username: newUsername}});\n\n // Perform another check after update, in case a matching user has been\n // inserted in the meantime\n try {\n Accounts._checkForCaseInsensitiveDuplicates('username',\n 'Username', newUsername, user._id);\n } catch (ex) {\n // Undo update if the check fails\n Meteor.users.update({_id: user._id}, {$set: {username: oldUsername}});\n throw ex;\n }\n};\n\n// Let the user change their own password if they know the old\n// password. `oldPassword` and `newPassword` should be objects with keys\n// `digest` and `algorithm` (representing the SHA256 of the password).\nMeteor.methods({changePassword: function (oldPassword, newPassword) {\n check(oldPassword, passwordValidator);\n check(newPassword, passwordValidator);\n\n if (!this.userId) {\n throw new Meteor.Error(401, \"Must be logged in\");\n }\n\n const user = getUserById(this.userId, {fields: {\n services: 1,\n ...Accounts._checkPasswordUserFields,\n }});\n if (!user) {\n Accounts._handleError(\"User not found\");\n }\n\n if (!user.services || !user.services.password || !user.services.password.bcrypt) {\n Accounts._handleError(\"User has no password set\");\n }\n\n const result = checkPassword(user, oldPassword);\n if (result.error) {\n throw result.error;\n }\n\n const hashed = hashPassword(newPassword);\n\n // It would be better if this removed ALL existing tokens and replaced\n // the token for the current connection with a new one, but that would\n // be tricky, so we'll settle for just replacing all tokens other than\n // the one for the current connection.\n const currentToken = Accounts._getLoginToken(this.connection.id);\n Meteor.users.update(\n { _id: this.userId },\n {\n $set: { 'services.password.bcrypt': hashed },\n $pull: {\n 'services.resume.loginTokens': { hashedToken: { $ne: currentToken } }\n },\n $unset: { 'services.password.reset': 1 }\n }\n );\n\n return {passwordChanged: true};\n}});\n\n\n// Force change the users password.\n\n/**\n * @summary Forcibly change the password for a user.\n * @locus Server\n * @param {String} userId The id of the user to update.\n * @param {String} newPassword A new password for the user.\n * @param {Object} [options]\n * @param {Object} options.logout Logout all current connections with this userId (default: true)\n * @importFromPackage accounts-base\n */\nAccounts.setPassword = (userId, newPlaintextPassword, options) => {\n check(userId, String)\n check(newPlaintextPassword, Match.Where(str => Match.test(str, String) && str.length <= Meteor.settings?.packages?.accounts?.passwordMaxLength || 256))\n check(options, Match.Maybe({ logout: Boolean }))\n options = { logout: true , ...options };\n\n const user = getUserById(userId, {fields: {_id: 1}});\n if (!user) {\n throw new Meteor.Error(403, \"User not found\");\n }\n\n const update = {\n $unset: {\n 'services.password.reset': 1\n },\n $set: {'services.password.bcrypt': hashPassword(newPlaintextPassword)}\n };\n\n if (options.logout) {\n update.$unset['services.resume.loginTokens'] = 1;\n }\n\n Meteor.users.update({_id: user._id}, update);\n};\n\n\n///\n/// RESETTING VIA EMAIL\n///\n\n// Utility for plucking addresses from emails\nconst pluckAddresses = (emails = []) => emails.map(email => email.address);\n\n// Method called by a user to request a password reset email. This is\n// the start of the reset process.\nMeteor.methods({forgotPassword: options => {\n check(options, {email: String})\n\n const user = Accounts.findUserByEmail(options.email, { fields: { emails: 1 } });\n\n if (!user) {\n Accounts._handleError(\"User not found\");\n }\n\n const emails = pluckAddresses(user.emails);\n const caseSensitiveEmail = emails.find(\n email => email.toLowerCase() === options.email.toLowerCase()\n );\n\n Accounts.sendResetPasswordEmail(user._id, caseSensitiveEmail);\n}});\n\n/**\n * @summary Generates a reset token and saves it into the database.\n * @locus Server\n * @param {String} userId The id of the user to generate the reset token for.\n * @param {String} email Which address of the user to generate the reset token for. This address must be in the user's `emails` list. If `null`, defaults to the first email in the list.\n * @param {String} reason `resetPassword` or `enrollAccount`.\n * @param {Object} [extraTokenData] Optional additional data to be added into the token record.\n * @returns {Object} Object with {email, user, token} values.\n * @importFromPackage accounts-base\n */\nAccounts.generateResetToken = (userId, email, reason, extraTokenData) => {\n // Make sure the user exists, and email is one of their addresses.\n // Don't limit the fields in the user object since the user is returned\n // by the function and some other fields might be used elsewhere.\n const user = getUserById(userId);\n if (!user) {\n Accounts._handleError(\"Can't find user\");\n }\n\n // pick the first email if we weren't passed an email.\n if (!email && user.emails && user.emails[0]) {\n email = user.emails[0].address;\n }\n\n // make sure we have a valid email\n if (!email ||\n !(pluckAddresses(user.emails).includes(email))) {\n Accounts._handleError(\"No such email for user.\");\n }\n\n const token = Random.secret();\n const tokenRecord = {\n token,\n email,\n when: new Date()\n };\n\n if (reason === 'resetPassword') {\n tokenRecord.reason = 'reset';\n } else if (reason === 'enrollAccount') {\n tokenRecord.reason = 'enroll';\n } else if (reason) {\n // fallback so that this function can be used for unknown reasons as well\n tokenRecord.reason = reason;\n }\n\n if (extraTokenData) {\n Object.assign(tokenRecord, extraTokenData);\n }\n // if this method is called from the enroll account work-flow then\n // store the token record in 'services.password.enroll' db field\n // else store the token record in in 'services.password.reset' db field\n if(reason === 'enrollAccount') {\n Meteor.users.update({_id: user._id}, {\n $set : {\n 'services.password.enroll': tokenRecord\n }\n });\n // before passing to template, update user object with new token\n Meteor._ensure(user, 'services', 'password').enroll = tokenRecord;\n } else {\n Meteor.users.update({_id: user._id}, {\n $set : {\n 'services.password.reset': tokenRecord\n }\n });\n // before passing to template, update user object with new token\n Meteor._ensure(user, 'services', 'password').reset = tokenRecord;\n }\n\n return {email, user, token};\n};\n\n/**\n * @summary Generates an e-mail verification token and saves it into the database.\n * @locus Server\n * @param {String} userId The id of the user to generate the e-mail verification token for.\n * @param {String} email Which address of the user to generate the e-mail verification token for. This address must be in the user's `emails` list. If `null`, defaults to the first unverified email in the list.\n * @param {Object} [extraTokenData] Optional additional data to be added into the token record.\n * @returns {Object} Object with {email, user, token} values.\n * @importFromPackage accounts-base\n */\nAccounts.generateVerificationToken = (userId, email, extraTokenData) => {\n // Make sure the user exists, and email is one of their addresses.\n // Don't limit the fields in the user object since the user is returned\n // by the function and some other fields might be used elsewhere.\n const user = getUserById(userId);\n if (!user) {\n Accounts._handleError(\"Can't find user\");\n }\n\n // pick the first unverified email if we weren't passed an email.\n if (!email) {\n const emailRecord = (user.emails || []).find(e => !e.verified);\n email = (emailRecord || {}).address;\n\n if (!email) {\n Accounts._handleError(\"That user has no unverified email addresses.\");\n }\n }\n\n // make sure we have a valid email\n if (!email ||\n !(pluckAddresses(user.emails).includes(email))) {\n Accounts._handleError(\"No such email for user.\");\n }\n\n const token = Random.secret();\n const tokenRecord = {\n token,\n // TODO: This should probably be renamed to \"email\" to match reset token record.\n address: email,\n when: new Date()\n };\n\n if (extraTokenData) {\n Object.assign(tokenRecord, extraTokenData);\n }\n\n Meteor.users.update({_id: user._id}, {$push: {\n 'services.email.verificationTokens': tokenRecord\n }});\n\n // before passing to template, update user object with new token\n Meteor._ensure(user, 'services', 'email');\n if (!user.services.email.verificationTokens) {\n user.services.email.verificationTokens = [];\n }\n user.services.email.verificationTokens.push(tokenRecord);\n\n return {email, user, token};\n};\n\n\n// send the user an email with a link that when opened allows the user\n// to set a new password, without the old password.\n\n/**\n * @summary Send an email with a link the user can use to reset their password.\n * @locus Server\n * @param {String} userId The id of the user to send email to.\n * @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first email in the list.\n * @param {Object} [extraTokenData] Optional additional data to be added into the token record.\n * @param {Object} [extraParams] Optional additional params to be added to the reset url.\n * @returns {Object} Object with {email, user, token, url, options} values.\n * @importFromPackage accounts-base\n */\nAccounts.sendResetPasswordEmail = (userId, email, extraTokenData, extraParams) => {\n const {email: realEmail, user, token} =\n Accounts.generateResetToken(userId, email, 'resetPassword', extraTokenData);\n const url = Accounts.urls.resetPassword(token, extraParams);\n const options = Accounts.generateOptionsForEmail(realEmail, user, url, 'resetPassword');\n Email.send(options);\n if (Meteor.isDevelopment) {\n console.log(`\\nReset password URL: ${url}`);\n }\n return {email: realEmail, user, token, url, options};\n};\n\n// send the user an email informing them that their account was created, with\n// a link that when opened both marks their email as verified and forces them\n// to choose their password. The email must be one of the addresses in the\n// user's emails field, or undefined to pick the first email automatically.\n//\n// This is not called automatically. It must be called manually if you\n// want to use enrollment emails.\n\n/**\n * @summary Send an email with a link the user can use to set their initial password.\n * @locus Server\n * @param {String} userId The id of the user to send email to.\n * @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first email in the list.\n * @param {Object} [extraTokenData] Optional additional data to be added into the token record.\n * @param {Object} [extraParams] Optional additional params to be added to the enrollment url.\n * @returns {Object} Object with {email, user, token, url, options} values.\n * @importFromPackage accounts-base\n */\nAccounts.sendEnrollmentEmail = (userId, email, extraTokenData, extraParams) => {\n const {email: realEmail, user, token} =\n Accounts.generateResetToken(userId, email, 'enrollAccount', extraTokenData);\n const url = Accounts.urls.enrollAccount(token, extraParams);\n const options = Accounts.generateOptionsForEmail(realEmail, user, url, 'enrollAccount');\n Email.send(options);\n if (Meteor.isDevelopment) {\n console.log(`\\nEnrollment email URL: ${url}`);\n }\n return {email: realEmail, user, token, url, options};\n};\n\n\n// Take token from sendResetPasswordEmail or sendEnrollmentEmail, change\n// the users password, and log them in.\nMeteor.methods({resetPassword: function (...args) {\n const token = args[0];\n const newPassword = args[1];\n return Accounts._loginMethod(\n this,\n \"resetPassword\",\n args,\n \"password\",\n () => {\n check(token, String);\n check(newPassword, passwordValidator);\n\n let user = Meteor.users.findOne(\n {\"services.password.reset.token\": token},\n {fields: {\n services: 1,\n emails: 1,\n }}\n );\n\n let isEnroll = false;\n // if token is in services.password.reset db field implies\n // this method is was not called from enroll account workflow\n // else this method is called from enroll account workflow\n if(!user) {\n user = Meteor.users.findOne(\n {\"services.password.enroll.token\": token},\n {fields: {\n services: 1,\n emails: 1,\n }}\n );\n isEnroll = true;\n }\n if (!user) {\n throw new Meteor.Error(403, \"Token expired\");\n }\n let tokenRecord = {};\n if(isEnroll) {\n tokenRecord = user.services.password.enroll;\n } else {\n tokenRecord = user.services.password.reset;\n }\n const { when, email } = tokenRecord;\n let tokenLifetimeMs = Accounts._getPasswordResetTokenLifetimeMs();\n if (isEnroll) {\n tokenLifetimeMs = Accounts._getPasswordEnrollTokenLifetimeMs();\n }\n const currentTimeMs = Date.now();\n if ((currentTimeMs - when) > tokenLifetimeMs)\n throw new Meteor.Error(403, \"Token expired\");\n if (!(pluckAddresses(user.emails).includes(email)))\n return {\n userId: user._id,\n error: new Meteor.Error(403, \"Token has invalid email address\")\n };\n\n const hashed = hashPassword(newPassword);\n\n // NOTE: We're about to invalidate tokens on the user, who we might be\n // logged in as. Make sure to avoid logging ourselves out if this\n // happens. But also make sure not to leave the connection in a state\n // of having a bad token set if things fail.\n const oldToken = Accounts._getLoginToken(this.connection.id);\n Accounts._setLoginToken(user._id, this.connection, null);\n const resetToOldToken = () =>\n Accounts._setLoginToken(user._id, this.connection, oldToken);\n\n try {\n // Update the user record by:\n // - Changing the password to the new one\n // - Forgetting about the reset token or enroll token that was just used\n // - Verifying their email, since they got the password reset via email.\n let affectedRecords = {};\n // if reason is enroll then check services.password.enroll.token field for affected records\n if(isEnroll) {\n affectedRecords = Meteor.users.update(\n {\n _id: user._id,\n 'emails.address': email,\n 'services.password.enroll.token': token\n },\n {$set: {'services.password.bcrypt': hashed,\n 'emails.$.verified': true},\n $unset: {'services.password.enroll': 1 }});\n } else {\n affectedRecords = Meteor.users.update(\n {\n _id: user._id,\n 'emails.address': email,\n 'services.password.reset.token': token\n },\n {$set: {'services.password.bcrypt': hashed,\n 'emails.$.verified': true},\n $unset: {'services.password.reset': 1 }});\n }\n if (affectedRecords !== 1)\n return {\n userId: user._id,\n error: new Meteor.Error(403, \"Invalid email\")\n };\n } catch (err) {\n resetToOldToken();\n throw err;\n }\n\n // Replace all valid login tokens with new ones (changing\n // password should invalidate existing sessions).\n Accounts._clearAllLoginTokens(user._id);\n\n return {userId: user._id};\n }\n );\n}});\n\n///\n/// EMAIL VERIFICATION\n///\n\n\n// send the user an email with a link that when opened marks that\n// address as verified\n\n/**\n * @summary Send an email with a link the user can use verify their email address.\n * @locus Server\n * @param {String} userId The id of the user to send email to.\n * @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first unverified email in the list.\n * @param {Object} [extraTokenData] Optional additional data to be added into the token record.\n * @param {Object} [extraParams] Optional additional params to be added to the verification url.\n *\n * @returns {Object} Object with {email, user, token, url, options} values.\n * @importFromPackage accounts-base\n */\nAccounts.sendVerificationEmail = (userId, email, extraTokenData, extraParams) => {\n // XXX Also generate a link using which someone can delete this\n // account if they own said address but weren't those who created\n // this account.\n\n const {email: realEmail, user, token} =\n Accounts.generateVerificationToken(userId, email, extraTokenData);\n const url = Accounts.urls.verifyEmail(token, extraParams);\n const options = Accounts.generateOptionsForEmail(realEmail, user, url, 'verifyEmail');\n Email.send(options);\n if (Meteor.isDevelopment) {\n console.log(`\\nVerification email URL: ${url}`);\n }\n return {email: realEmail, user, token, url, options};\n};\n\n// Take token from sendVerificationEmail, mark the email as verified,\n// and log them in.\nMeteor.methods({verifyEmail: function (...args) {\n const token = args[0];\n return Accounts._loginMethod(\n this,\n \"verifyEmail\",\n args,\n \"password\",\n () => {\n check(token, String);\n\n const user = Meteor.users.findOne(\n {'services.email.verificationTokens.token': token},\n {fields: {\n services: 1,\n emails: 1,\n }}\n );\n if (!user)\n throw new Meteor.Error(403, \"Verify email link expired\");\n\n const tokenRecord = user.services.email.verificationTokens.find(\n t => t.token == token\n );\n if (!tokenRecord)\n return {\n userId: user._id,\n error: new Meteor.Error(403, \"Verify email link expired\")\n };\n\n const emailsRecord = user.emails.find(\n e => e.address == tokenRecord.address\n );\n if (!emailsRecord)\n return {\n userId: user._id,\n error: new Meteor.Error(403, \"Verify email link is for unknown address\")\n };\n\n // By including the address in the query, we can use 'emails.$' in the\n // modifier to get a reference to the specific object in the emails\n // array. See\n // http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator)\n // http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull\n Meteor.users.update(\n {_id: user._id,\n 'emails.address': tokenRecord.address},\n {$set: {'emails.$.verified': true},\n $pull: {'services.email.verificationTokens': {address: tokenRecord.address}}});\n\n return {userId: user._id};\n }\n );\n}});\n\n/**\n * @summary Add an email address for a user. Use this instead of directly\n * updating the database. The operation will fail if there is a different user\n * with an email only differing in case. If the specified user has an existing\n * email only differing in case however, we replace it.\n * @locus Server\n * @param {String} userId The ID of the user to update.\n * @param {String} newEmail A new email address for the user.\n * @param {Boolean} [verified] Optional - whether the new email address should\n * be marked as verified. Defaults to false.\n * @importFromPackage accounts-base\n */\nAccounts.addEmail = (userId, newEmail, verified) => {\n check(userId, NonEmptyString);\n check(newEmail, NonEmptyString);\n check(verified, Match.Optional(Boolean));\n\n if (verified === void 0) {\n verified = false;\n }\n\n const user = getUserById(userId, {fields: {emails: 1}});\n if (!user)\n throw new Meteor.Error(403, \"User not found\");\n\n // Allow users to change their own email to a version with a different case\n\n // We don't have to call checkForCaseInsensitiveDuplicates to do a case\n // insensitive check across all emails in the database here because: (1) if\n // there is no case-insensitive duplicate between this user and other users,\n // then we are OK and (2) if this would create a conflict with other users\n // then there would already be a case-insensitive duplicate and we can't fix\n // that in this code anyway.\n const caseInsensitiveRegExp =\n new RegExp(`^${Meteor._escapeRegExp(newEmail)}$`, 'i');\n\n const didUpdateOwnEmail = (user.emails || []).reduce(\n (prev, email) => {\n if (caseInsensitiveRegExp.test(email.address)) {\n Meteor.users.update({\n _id: user._id,\n 'emails.address': email.address\n }, {$set: {\n 'emails.$.address': newEmail,\n 'emails.$.verified': verified\n }});\n return true;\n } else {\n return prev;\n }\n },\n false\n );\n\n // In the other updates below, we have to do another call to\n // checkForCaseInsensitiveDuplicates to make sure that no conflicting values\n // were added to the database in the meantime. We don't have to do this for\n // the case where the user is updating their email address to one that is the\n // same as before, but only different because of capitalization. Read the\n // big comment above to understand why.\n\n if (didUpdateOwnEmail) {\n return;\n }\n\n // Perform a case insensitive check for duplicates before update\n Accounts._checkForCaseInsensitiveDuplicates('emails.address',\n 'Email', newEmail, user._id);\n\n Meteor.users.update({\n _id: user._id\n }, {\n $addToSet: {\n emails: {\n address: newEmail,\n verified: verified\n }\n }\n });\n\n // Perform another check after update, in case a matching user has been\n // inserted in the meantime\n try {\n Accounts._checkForCaseInsensitiveDuplicates('emails.address',\n 'Email', newEmail, user._id);\n } catch (ex) {\n // Undo update if the check fails\n Meteor.users.update({_id: user._id},\n {$pull: {emails: {address: newEmail}}});\n throw ex;\n }\n}\n\n/**\n * @summary Remove an email address for a user. Use this instead of updating\n * the database directly.\n * @locus Server\n * @param {String} userId The ID of the user to update.\n * @param {String} email The email address to remove.\n * @importFromPackage accounts-base\n */\nAccounts.removeEmail = (userId, email) => {\n check(userId, NonEmptyString);\n check(email, NonEmptyString);\n\n const user = getUserById(userId, {fields: {_id: 1}});\n if (!user)\n throw new Meteor.Error(403, \"User not found\");\n\n Meteor.users.update({_id: user._id},\n {$pull: {emails: {address: email}}});\n}\n\n///\n/// CREATING USERS\n///\n\n// Shared createUser function called from the createUser method, both\n// if originates in client or server code. Calls user provided hooks,\n// does the actual user insertion.\n//\n// returns the user id\nconst createUser = options => {\n // Unknown keys allowed, because a onCreateUserHook can take arbitrary\n // options.\n check(options, Match.ObjectIncluding({\n username: Match.Optional(String),\n email: Match.Optional(String),\n password: Match.Optional(passwordValidator)\n }));\n\n const { username, email, password } = options;\n if (!username && !email)\n throw new Meteor.Error(400, \"Need to set a username or email\");\n\n const user = {services: {}};\n if (password) {\n const hashed = hashPassword(password);\n user.services.password = { bcrypt: hashed };\n }\n\n return Accounts._createUserCheckingDuplicates({ user, email, username, options })\n};\n\n// method for create user. Requests come from the client.\nMeteor.methods({createUser: function (...args) {\n const options = args[0];\n return Accounts._loginMethod(\n this,\n \"createUser\",\n args,\n \"password\",\n () => {\n // createUser() above does more checking.\n check(options, Object);\n if (Accounts._options.forbidClientAccountCreation)\n return {\n error: new Meteor.Error(403, \"Signups forbidden\")\n };\n\n const userId = Accounts.createUserVerifyingEmail(options);\n\n // client gets logged in as the new user afterwards.\n return {userId: userId};\n }\n );\n}});\n\n/**\n * @summary Creates an user and sends an email if `options.email` is informed.\n * Then if the `sendVerificationEmail` option from the `Accounts` package is\n * enabled, you'll send a verification email if `options.password` is informed,\n * otherwise you'll send an enrollment email.\n * @locus Server\n * @param {Object} options The options object to be passed down when creating\n * the user\n * @param {String} options.username A unique name for this user.\n * @param {String} options.email The user's email address.\n * @param {String} options.password The user's password. This is __not__ sent in plain text over the wire.\n * @param {Object} options.profile The user's profile, typically including the `name` field.\n * @importFromPackage accounts-base\n * */\nAccounts.createUserVerifyingEmail = (options) => {\n options = { ...options };\n // Create user. result contains id and token.\n const userId = createUser(options);\n // safety belt. createUser is supposed to throw on error. send 500 error\n // instead of sending a verification email with empty userid.\n if (! userId)\n throw new Error(\"createUser failed to insert new user\");\n\n // If `Accounts._options.sendVerificationEmail` is set, register\n // a token to verify the user's primary email, and send it to\n // that address.\n if (options.email && Accounts._options.sendVerificationEmail) {\n if (options.password) {\n Accounts.sendVerificationEmail(userId, options.email);\n } else {\n Accounts.sendEnrollmentEmail(userId, options.email);\n }\n }\n\n return userId;\n};\n\n// Create user directly on the server.\n//\n// Unlike the client version, this does not log you in as this user\n// after creation.\n//\n// returns userId or throws an error if it can't create\n//\n// XXX add another argument (\"server options\") that gets sent to onCreateUser,\n// which is always empty when called from the createUser method? eg, \"admin:\n// true\", which we want to prevent the client from setting, but which a custom\n// method calling Accounts.createUser could set?\n//\nAccounts.createUser = (options, callback) => {\n options = { ...options };\n\n // XXX allow an optional callback?\n if (callback) {\n throw new Error(\"Accounts.createUser with callback not supported on the server yet.\");\n }\n\n return createUser(options);\n};\n\n///\n/// PASSWORD-SPECIFIC INDEXES ON USERS\n///\nMeteor.users.createIndex('services.email.verificationTokens.token',\n { unique: true, sparse: true });\nMeteor.users.createIndex('services.password.reset.token',\n { unique: true, sparse: true });\nMeteor.users.createIndex('services.password.enroll.token',\n { unique: true, sparse: true });\n"]}