diff --git a/.github/workflows/integration.js.yml b/.github/workflows/integration.js.yml index ff49e03b01..7a65882b6d 100644 --- a/.github/workflows/integration.js.yml +++ b/.github/workflows/integration.js.yml @@ -43,3 +43,5 @@ jobs: REFRESH_TOKEN: ${{ secrets.REFRESH_TOKEN }} CONSULTING_PROGRAM_IDS: ${{ secrets.CONSULTING_PROGRAM_IDS }} CONSULTING_BILLING_ITEM: ${{ secrets.CONSULTING_BILLING_ITEM }} + WEBSITE_HOSTNAME: ${{ vars.WEBSITE_HOSTNAME }} + MOBILE_WEBSITE_HOSTNAME: ${{ vars.MOBILE_WEBSITE_HOSTNAME }} diff --git a/package.json b/package.json index 0723f9d470..6d594845e4 100644 --- a/package.json +++ b/package.json @@ -35,12 +35,12 @@ "@hapi/good": "~9.0.1", "@hapi/good-console": "~9.0.1", "@hapi/good-squeeze": "~6.0.0", - "@hapi/hapi": "~21.4.10", + "@hapi/hapi": "~21.4.13", "@hapi/inert": "~7.1.2", "@notionhq/client": "~5.27.0", "@sentry/node": "~11.4.0", "@sentry/profiling-node": "~11.4.0", - "axios": "~1.20.0", + "axios": "~1.21.1", "bcryptjs": "~3.0.3", "bignumber.js": "~11.1.5", "cron": "~4.4.0", @@ -51,7 +51,7 @@ "form-data": "~4.0.6", "hapi-auth-jwt2": "~11.0.0", "intl": "~1.2.5", - "joi": "~18.2.9", + "joi": "~18.3.2", "joi-objectid": "~4.0.2", "jsonwebtoken": "~9.0.3", "jszip": "~3.10.2", @@ -62,7 +62,7 @@ "moment-range": "~4.0.2", "moment-timezone": "~0.5.34", "mongodb": "~7.7.0", - "mongoose": "~9.11.0", + "mongoose": "~9.11.4", "mongoose-autopopulate": "~1.2.1", "mongoose-lean-virtuals": "~2.1.0", "nodemailer": "~10.0.15", diff --git a/server.js b/server.js index c118691177..55a101f769 100644 --- a/server.js +++ b/server.js @@ -21,7 +21,7 @@ const server = Hapi.server({ collect: true, }, cors: { - origin: ['*'], + origin: [process.env.WEBSITE_HOSTNAME, ...[process.env.MOBILE_WEBSITE_HOSTNAME].filter(Boolean)], credentials: true, additionalHeaders: ['accept-language', 'accept-encoding', 'access-control-request-headers', 'x-access-token'], }, diff --git a/src/helpers/authentication.js b/src/helpers/authentication.js index c8c9483c86..d3383714fe 100644 --- a/src/helpers/authentication.js +++ b/src/helpers/authentication.js @@ -12,6 +12,7 @@ const translate = require('./translate'); const { MOBILE, EMAIL } = require('./constants'); const EmailHelper = require('./email'); const SmsHelper = require('./sms'); +const UtilsHelper = require('./utils'); const { CompaniDate } = require('./dates/companiDates'); const { CompaniDuration } = require('./dates/companiDurations'); @@ -40,7 +41,7 @@ exports.authenticate = async (payload) => { firstMobileConnectionDate: CompaniDate().toISO(), firstMobileConnectionMode: payload.mobileConnectionMode, }, - $unset: { loginCode: '' }, + $unset: { loginCode: '', loginCodeLock: '' }, } ); } @@ -73,9 +74,13 @@ exports.updatePassword = async (userId, userPayload) => User.findOneAndUpdate( { new: true } ).lean(); -exports.sendToken = (user) => { +exports.sendToken = async (user) => { const payload = pickBy({ _id: user._id, email: user.local.email }); + if (user.loginCodeLock) { + await User.updateOne({ _id: user._id }, { $unset: { loginCodeLock: '' } }, { timestamps: false }); + } + return { token: exports.encode(payload), user: payload }; }; @@ -84,16 +89,21 @@ exports.createPasswordToken = async email => exports.generatePasswordToken(email exports.forgotPassword = async (payload) => { const { email, origin, type } = payload; if (origin === MOBILE) { - const code = String(Math.floor(Math.random() * 9000 + 1000)); - let verification = await IdentityVerification.findOneAndUpdate({ email }, { $set: { code } }, { new: true }).lean(); - if (!verification) verification = await IdentityVerification.create({ email, code }); - - if (type === EMAIL) return EmailHelper.sendVerificationCodeEmail(email, verification.code); + const code = UtilsHelper.generateVerificationCode(); + const verification = await IdentityVerification.findOne({ email }, { updatedAt: 1 }).lean(); + if (verification) { + const isOlderThanOneHour = CompaniDate().isAfter(CompaniDate(verification.updatedAt).add('PT1H')); + await IdentityVerification.updateOne( + { _id: verification._id }, + { $set: { code, ...(isOlderThanOneHour && { attempts: 0 }) } } + ); + } else await IdentityVerification.create({ email, code }); + + if (type === EMAIL) return EmailHelper.sendVerificationCodeEmail(email, code); const user = await User.findOne({ 'local.email': email }, { contact: 1 }).lean(); - if (!get(user, 'contact.phone')) throw Boom.conflict(); - return SmsHelper.sendVerificationCodeSms(user.contact, verification.code); + return SmsHelper.sendVerificationCodeSms(user.contact, code); } const passwordToken = await exports.generatePasswordToken(email, 3600000); diff --git a/src/helpers/constants.js b/src/helpers/constants.js index 788bbe2b93..4d5706c737 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -14,6 +14,9 @@ module.exports = { REJECTED: 'rejected', // Time SECONDS_IN_AN_HOUR: 3600, + // Verification code + MAX_VERIFICATION_ATTEMPTS: 3, + LOGIN_CODE_LOCK_DELAYS: ['PT5M', 'PT15M', 'PT1H', 'PT24H'], // COMPANIDURATION PT0S: 'PT0S', // COMPANIDURATION FORMATS diff --git a/src/helpers/courses.js b/src/helpers/courses.js index f3d297e805..c5fd0dbc4f 100644 --- a/src/helpers/courses.js +++ b/src/helpers/courses.js @@ -57,6 +57,8 @@ const { VENDOR_ADMIN, TRAINING_ORGANISATION_MANAGER, TRAINER, + CLIENT_ADMIN, + COACH, REMOTE, OPERATIONS, HHhMM, @@ -567,6 +569,10 @@ exports.formatCourseWithProgress = (course, userId, shouldComputePresence = fals const getCourseForOperations = async (courseId, credentials, origin) => { const isRofOrAdmin = [VENDOR_ADMIN, TRAINING_ORGANISATION_MANAGER].includes(get(credentials, 'role.vendor.name')); + const canSeeLoginCode = [VENDOR_ADMIN, TRAINING_ORGANISATION_MANAGER, TRAINER] + .includes(get(credentials, 'role.vendor.name')) || + [CLIENT_ADMIN, COACH].includes(get(credentials, 'role.client.name')); + const loginCodeSelect = canSeeLoginCode ? ' loginCode' : ''; const fetchedCourse = await Course.findOne({ _id: courseId }) .populate([ @@ -578,7 +584,7 @@ const getCourseForOperations = async (courseId, credentials, origin) => { { path: 'trainees', select: 'identity.firstname identity.lastname local.email contact picture.link ' - + 'firstMobileConnectionDate loginCode', + + `firstMobileConnectionDate${loginCodeSelect}`, populate: { path: 'company' }, }, { @@ -608,7 +614,7 @@ const getCourseForOperations = async (courseId, credentials, origin) => { { path: 'tutors', select: 'identity.firstname identity.lastname contact local.email picture.link ' - + 'firstMobileConnectionDate loginCode', + + `firstMobileConnectionDate${loginCodeSelect}`, }, { path: 'slots', @@ -777,7 +783,7 @@ exports.getCourseFollowUp = async (course, query, credentials) => { }) .populate({ path: 'trainees', - select: 'identity.firstname identity.lastname firstMobileConnectionDate loginCode', + select: `identity.firstname identity.lastname firstMobileConnectionDate${query.trainee ? '' : ' loginCode'}`, populate: { path: 'company' }, }) .lean(); @@ -1176,11 +1182,14 @@ exports.addTrainee = async (courseId, payload, credentials) => { ); const trainee = await User - .findOne({ _id: payload.trainee }, { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1 }) + .findOne( + { _id: payload.trainee }, + { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1, 'local.password': 1 } + ) .lean(); - if (!trainee.firstMobileConnectionDate && !trainee.loginCode) { - const loginCode = String(Math.floor(Math.random() * 9000 + 1000)); + if (!trainee.firstMobileConnectionDate && !trainee.loginCode && !get(trainee, 'local.password')) { + const loginCode = UtilsHelper.generateVerificationCode(); await User.updateOne({ _id: payload.trainee }, { $set: { loginCode } }); } @@ -2100,7 +2109,7 @@ exports.addTutor = async (courseId, payload) => { const tutor = await User .findOne( { _id: payload.tutor }, - { firstMobileConnectionDate: 1, loginCode: 1, identity: 1, contact: 1, 'local.email': 1 } + { firstMobileConnectionDate: 1, loginCode: 1, identity: 1, contact: 1, 'local.email': 1, 'local.password': 1 } ) .lean(); @@ -2116,8 +2125,8 @@ exports.addTutor = async (courseId, payload) => { }); } - if (!(tutor.firstMobileConnectionDate || tutor.loginCode)) { - const loginCode = String(Math.floor(Math.random() * 9000 + 1000)); + if (!(tutor.firstMobileConnectionDate || tutor.loginCode || get(tutor, 'local.password'))) { + const loginCode = UtilsHelper.generateVerificationCode(); await User.updateOne({ _id: payload.tutor }, { $set: { loginCode } }); } diff --git a/src/helpers/translate.js b/src/helpers/translate.js index 489b7f3215..12f35a9026 100644 --- a/src/helpers/translate.js +++ b/src/helpers/translate.js @@ -6,6 +6,7 @@ module.exports = { /* Users strings */ usersNotFound: 'There are no users.', userNotFound: 'User doesn\'t exist.', + tooManyAttempts: 'Too many attempts. Try again later.', userEmailExists: 'This email is already taken by another user.', userFound: 'User found successfully.', userSaved: 'User saved successfully.', @@ -391,6 +392,7 @@ module.exports = { /* Users strings */ usersNotFound: 'Il n\'y a aucun compte.', userNotFound: 'Le compte n\'existe pas.', + tooManyAttempts: 'Trop de tentatives. Réessayez plus tard.', userEmailExists: 'Cet email est déjà pris par un autre compte.', userSaved: 'Compte enregistré avec succès.', userFound: 'Compte trouvé avec succès.', diff --git a/src/helpers/utils.js b/src/helpers/utils.js index b6225682f8..84d14beeba 100644 --- a/src/helpers/utils.js +++ b/src/helpers/utils.js @@ -313,6 +313,8 @@ exports.hasUserAccessToCompany = (credentials, company) => { exports.formatName = list => list.map(item => item.name).join(', '); +exports.generateVerificationCode = () => String(crypto.randomInt(1000, 10000)); + exports.formatRumNumber = (companyPrefixNumber, prefix, seq) => { const len = 20; const random = crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len).toUpperCase(); diff --git a/src/models/IdentityVerification.js b/src/models/IdentityVerification.js index cc5980ed77..e85f1c2080 100644 --- a/src/models/IdentityVerification.js +++ b/src/models/IdentityVerification.js @@ -4,6 +4,7 @@ const { formatQuery, queryMiddlewareList } = require('./preHooks/validate'); const IdentityVerificationSchema = mongoose.Schema({ email: { type: String, required: true }, code: { type: String, required: true }, + attempts: { type: Number, default: 0 }, }, { timestamps: true }); queryMiddlewareList.map(middleware => IdentityVerificationSchema.pre(middleware, formatQuery)); diff --git a/src/models/User.js b/src/models/User.js index d45a78b1f0..89a67369b8 100644 --- a/src/models/User.js +++ b/src/models/User.js @@ -157,7 +157,11 @@ const UserSchema = mongoose.Schema({ }, origin: { type: String, enum: ORIGIN_OPTIONS, required: true, immutable: true }, formationExpoTokenList: [{ type: String }], - loginCode: { type: String }, + loginCode: { type: String, select: false }, + loginCodeLock: { + type: mongoose.Schema({ attempts: Number, count: Number, lockedUntil: Date }, { _id: false, id: false }), + select: false, + }, isProgramEditor: { type: Boolean, default: false }, }, { timestamps: true, diff --git a/src/routes/authentication.js b/src/routes/authentication.js index efa8c73f25..e8bbadf12a 100644 --- a/src/routes/authentication.js +++ b/src/routes/authentication.js @@ -20,7 +20,7 @@ const { MOBILE_CONNECTION_MODE, UNKNOWN, } = require('../helpers/constants'); -const { checkPasswordToken, authorizeRefreshToken } = require('./preHandlers/authentication'); +const { checkPasswordToken, authorizeRefreshToken, authorizeForgotPassword } = require('./preHandlers/authentication'); exports.plugin = { name: 'routes-authentication', @@ -93,6 +93,7 @@ exports.plugin = { }), }, auth: false, + pre: [{ method: authorizeForgotPassword }], }, handler: forgotPassword, }); diff --git a/src/routes/preHandlers/authentication.js b/src/routes/preHandlers/authentication.js index c3046558d4..9b51d4b0a9 100644 --- a/src/routes/preHandlers/authentication.js +++ b/src/routes/preHandlers/authentication.js @@ -3,37 +3,133 @@ const flat = require('flat'); const get = require('lodash/get'); const User = require('../../models/User'); const IdentityVerification = require('../../models/IdentityVerification'); -const { SECONDS_IN_AN_HOUR } = require('../../helpers/constants'); +const { + MOBILE, + PHONE, + MAX_VERIFICATION_ATTEMPTS, + LOGIN_CODE_LOCK_DELAYS, +} = require('../../helpers/constants'); +const UtilsHelper = require('../../helpers/utils'); const translate = require('../../helpers/translate'); const UserCompany = require('../../models/UserCompany'); +const { CompaniDate } = require('../../helpers/dates/companiDates'); const { language } = translate; +// Lock the user after too many wrong attempts: the lock gets longer each time (5 min, 15 min, 1 h, then 24 h) +// and a new loginCode is generated, so that the code which was being guessed is not valid anymore +const lockLoginCode = async (user) => { + const now = CompaniDate(); + + // The previous lock count is kept only if the last lock ended less than 48 h ago, otherwise we start again at 5 min + const lockEndDate = get(user, 'loginCodeLock.lockedUntil'); + const hasRecentLock = lockEndDate && now.isBefore(CompaniDate(lockEndDate).add('PT48H')); + const previousLockCount = hasRecentLock ? user.loginCodeLock.count : 0; + + // The count is capped to the number of delays: after the last one, every lock lasts 24 h + const lockCount = Math.min(previousLockCount + 1, LOGIN_CODE_LOCK_DELAYS.length); + + const lockedUntil = now.add(LOGIN_CODE_LOCK_DELAYS[lockCount - 1]).toDate(); + + // loginCodeLock is replaced as a whole: attempts is dropped, so the user has 3 new attempts when the lock ends + await User.updateOne( + { _id: user._id }, + { $set: { loginCode: UtilsHelper.generateVerificationCode(), loginCodeLock: { count: lockCount, lockedUntil } } }, + { timestamps: false } + ); +}; + exports.checkPasswordToken = async (req) => { const { query, params } = req; if (query.email) { - const code = await IdentityVerification.findOne({ email: query.email, code: params.token }).lean(); - if (!code) throw Boom.notFound(); + const verification = await IdentityVerification + .findOneAndUpdate( + { email: query.email, attempts: { $not: { $gte: MAX_VERIFICATION_ATTEMPTS } } }, + { $inc: { attempts: 1 } }, + { new: true, timestamps: false } + ) + .lean(); + if (!verification) { + const hasExhaustedAttempts = await IdentityVerification + .countDocuments({ email: query.email, attempts: { $gte: MAX_VERIFICATION_ATTEMPTS } }); + if (hasExhaustedAttempts) throw Boom.tooManyRequests(translate[language].tooManyAttempts); + + throw Boom.notFound(); + } + if (verification.code !== params.token) throw Boom.notFound(); - const timeElapsed = (Date.now() - code.updatedAt) / 1000; - if (timeElapsed > SECONDS_IN_AN_HOUR) throw Boom.unauthorized(); + const isExpired = CompaniDate().isAfter(CompaniDate(verification.updatedAt).add('PT1H')); + if (isExpired) throw Boom.unauthorized(); const user = await User.findOne({ 'local.email': query.email }).select('local.email').lean(); if (!user) throw Boom.notFound(translate[language].userNotFound); + await IdentityVerification.deleteOne({ _id: verification._id }); + return user; } if (query.firstname) { - const user = await User - .findOne({ 'identity.firstname': query.firstname, 'identity.lastname': query.lastname, loginCode: params.token }) + // Users are identified by name and company only: homonyms of a same company are possible + const matchingUsers = await User + .find( + { 'identity.firstname': query.firstname, 'identity.lastname': query.lastname, loginCode: { $exists: true } }, + { _id: 1, loginCode: 1, loginCodeLock: 1 } + ) .collation({ locale: 'fr', strength: 1, alternate: 'shifted' }) .lean(); + const userCompanies = await UserCompany + .find({ user: { $in: matchingUsers.map(u => u._id) }, company: query.company }, { user: 1 }) + .lean(); + const companyUsers = matchingUsers + .filter(u => userCompanies.some(uc => UtilsHelper.areObjectIdsEquals(uc.user, u._id))); - const userCompany = await UserCompany.countDocuments({ user: get(user, '_id'), company: query.company }); - if (!user || !userCompany) throw Boom.notFound(translate[language].userNotFound); + // Right code: the user is returned only if he is not locked (checked in db, so it is safe with parallel requests). + // No attempt is counted for a right code. + const matchingCodeUser = companyUsers.find(u => u.loginCode === params.token); + if (matchingCodeUser) { + const user = await User + .findOne( + { + _id: matchingCodeUser._id, + loginCode: params.token, + 'loginCodeLock.attempts': { $not: { $gte: MAX_VERIFICATION_ATTEMPTS } }, + 'loginCodeLock.lockedUntil': { $not: { $gt: CompaniDate().toDate() } }, + }, + { 'local.email': 1, loginCode: 1, loginCodeLock: 1 } + ) + .lean(); + if (user) return user; + } - return user; + // Wrong code: count an attempt for every candidate, even homonyms, because we can't know who is targeted. + // The filter excludes locked users, so attemptedUsers only contains users that were not locked. + const usersWithUpdatedAttempts = ( + await Promise.all( + companyUsers + .map(u => User.findOneAndUpdate( + { + _id: u._id, + 'loginCodeLock.attempts': { $not: { $gte: MAX_VERIFICATION_ATTEMPTS } }, + 'loginCodeLock.lockedUntil': { $not: { $gt: CompaniDate().toDate() } }, + }, + { $inc: { 'loginCodeLock.attempts': 1 } }, + { new: true, timestamps: false, projection: { 'local.email': 1, loginCode: 1, loginCodeLock: 1 } } + ) + .lean())) + ).filter(Boolean); + + // Users who just reached the max attempts are locked and get a new login code + const usersToLock = usersWithUpdatedAttempts.filter(u => u.loginCodeLock.attempts >= MAX_VERIFICATION_ATTEMPTS); + await Promise.all(usersToLock.map(lockLoginCode)); + // No attempt could be counted for any candidate: they are all locked, answer 429 and not 404, + // so that the user knows that his code is not the problem + const areAllUsersLocked = companyUsers.length && !usersWithUpdatedAttempts.length; + if (usersToLock.length || areAllUsersLocked) { + throw Boom.tooManyRequests(translate[language].tooManyAttempts); + } + + throw Boom.notFound(translate[language].userNotFound); } const filter = { passwordToken: { token: params.token, expiresIn: { $gt: Date.now() } } }; @@ -43,6 +139,24 @@ exports.checkPasswordToken = async (req) => { return user; }; +// a new code can't be asked while the last one has been tried too many times in the last hour +exports.authorizeForgotPassword = async (req) => { + const { email, origin, type } = req.payload; + if (origin !== MOBILE) return null; + + const user = await User.findOne({ 'local.email': email }, { contact: 1 }).lean(); + if (!user) throw Boom.notFound(translate[language].userNotFound); + if (type === PHONE && !get(user, 'contact.phone')) throw Boom.conflict(); + + const verification = await IdentityVerification.findOne({ email }).lean(); + if (verification && verification.attempts >= MAX_VERIFICATION_ATTEMPTS) { + const isRecent = !CompaniDate().isAfter(CompaniDate(verification.updatedAt).add('PT1H')); + if (isRecent) throw Boom.tooManyRequests(translate[language].tooManyAttempts); + } + + return null; +}; + exports.authorizeRefreshToken = async (req) => { const refreshToken = get(req, 'payload.refreshToken') || get(req, `state.${process.env.REFRESH_TOKEN}`); if (!refreshToken) return Boom.unauthorized(); diff --git a/tests/integration/authentication.test.js b/tests/integration/authentication.test.js index 70ee62d666..56b04b632d 100644 --- a/tests/integration/authentication.test.js +++ b/tests/integration/authentication.test.js @@ -2,6 +2,7 @@ const { expect } = require('expect'); const sinon = require('sinon'); const app = require('../../server'); const User = require('../../src/models/User'); +const IdentityVerification = require('../../src/models/IdentityVerification'); const { usersSeedList, populateDB } = require('./seed/usersSeed'); const { getToken, getTokenByCredentials } = require('./helpers/authentication'); const { noRoleNoCompany } = require('../seed/authUsersSeed'); @@ -9,6 +10,7 @@ const EmailHelper = require('../../src/helpers/email'); const SmsHelper = require('../../src/helpers/sms'); const { MOBILE, EMAIL, PHONE, AUTHENTICATION } = require('../../src/helpers/constants'); const UtilsMock = require('../utilsMock'); +const UtilsHelper = require('../../src/helpers/utils'); const { authCompany, otherCompany } = require('../seed/authCompaniesSeed'); describe('NODE ENV', () => { @@ -229,13 +231,18 @@ describe('AUTHENTICATION ROUTES - POST /users/refreshToken', () => { describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { beforeEach(populateDB); let fakeDate; + let generateVerificationCode; beforeEach(() => { - fakeDate = sinon.stub(Date, 'now'); + fakeDate = sinon.stub(Date, 'now').returns(new Date().getTime()); + generateVerificationCode = sinon.stub(UtilsHelper, 'generateVerificationCode').returns('5678'); }); afterEach(() => { fakeDate.restore(); + generateVerificationCode.restore(); }); + const now = new Date('2021-01-25T10:00:00.000Z').getTime(); + it('should return a new access token after checking reset password token', async () => { fakeDate.returns(new Date('2020-01-20')); @@ -260,12 +267,13 @@ describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { expect(response.statusCode).toBe(200); expect(response.result.data.token).toEqual(expect.any(String)); + expect(await IdentityVerification.countDocuments({ email })).toBe(0); }); it('should return a 404 error if verification code is wrong', async () => { const token = '3311'; const { email } = usersSeedList[3].local; - fakeDate.returns(new Date('2021-01-26T10:08:32.582Z')); + fakeDate.returns(new Date('2021-01-25T10:08:32.582Z')); const response = await app.inject({ method: 'GET', @@ -275,6 +283,20 @@ describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { expect(response.statusCode).toBe(404); }); + it('should return a 429 error if verification code was wrong 3 times', async () => { + const { email } = usersSeedList[3].local; + fakeDate.returns(new Date('2021-01-25T10:08:32.582Z')); + + for (const token of ['3311', '3312', '3313']) { + await app.inject({ method: 'GET', url: `/users/passwordtoken/${token}?email=${email}` }); + } + + const responseWithGoodCode = await app.inject({ method: 'GET', url: `/users/passwordtoken/3310?email=${email}` }); + + expect(responseWithGoodCode.statusCode).toBe(429); + expect(responseWithGoodCode.result.message).toBe('Trop de tentatives. Réessayez plus tard.'); + }); + it('should return a 404 error if token is not valid', async () => { const token = '1234567890'; const { email } = usersSeedList[3].local; @@ -315,6 +337,20 @@ describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { expect(response.statusCode).toBe(200); }); + it('should return 200 and remove lock if token is correct and lock is over', async () => { + const company = authCompany._id; + const { _id, loginCode: token, loginCodeLock, identity: { lastname, firstname } } = usersSeedList[1]; + fakeDate.returns(loginCodeLock.lockedUntil.getTime() + 60 * 1000); + + const response = await app.inject({ + method: 'GET', + url: `/users/passwordtoken/${token}?firstname=${firstname}&lastname=${lastname}&company=${company}`, + }); + + expect(response.statusCode).toBe(200); + expect(await User.countDocuments({ _id, loginCodeLock: { $exists: false } })).toBe(1); + }); + it('should return 400 if both email and firstname are in query', async () => { const company = authCompany._id; const { loginCode: token, local: { email }, identity: { firstname, lastname } } = usersSeedList[3]; @@ -355,6 +391,7 @@ describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { const token = '1294'; const company = authCompany._id; const { identity: { lastname, firstname } } = usersSeedList[3]; + fakeDate.returns(now); const response = await app.inject({ method: 'GET', @@ -364,6 +401,59 @@ describe('AUTHENTICATION ROUTES - GET /users/passwordtoken/:token', () => { expect(response.statusCode).toBe(404); }); + it('should return 429, renew login code and add 5min lock if token is wrong and user has 2 attempts', async () => { + const company = authCompany._id; + const { _id, loginCodeLock, identity: { lastname, firstname } } = usersSeedList[1]; + const token = '1296'; + const fakeNow = loginCodeLock.lockedUntil.getTime() + 3 * 24 * 60 * 60 * 1000; + fakeDate.returns(fakeNow); + + const response = await app.inject({ + method: 'GET', + url: `/users/passwordtoken/${token}?firstname=${firstname}&lastname=${lastname}&company=${company}`, + }); + + expect(response.statusCode).toBe(429); + expect(response.result.message).toBe('Trop de tentatives. Réessayez plus tard.'); + + const lockedUser = await User.findOne({ _id }, { loginCode: 1, loginCodeLock: 1 }).lean(); + expect(lockedUser.loginCode).toBe('5678'); + expect(lockedUser.loginCodeLock.count).toBe(1); + expect(lockedUser.loginCodeLock.lockedUntil).toEqual(new Date(fakeNow + 5 * 60 * 1000)); + }); + + it('should return 429 if token is correct but user is locked', async () => { + const company = authCompany._id; + const { loginCode: token, loginCodeLock, identity: { lastname, firstname } } = usersSeedList[1]; + fakeDate.returns(loginCodeLock.lockedUntil.getTime() - 60 * 1000); + + const response = await app.inject({ + method: 'GET', + url: `/users/passwordtoken/${token}?firstname=${firstname}&lastname=${lastname}&company=${company}`, + }); + + expect(response.statusCode).toBe(429); + }); + + it('should lock user for a longer time if token is wrong after a first lock', async () => { + const company = authCompany._id; + const { _id, loginCodeLock, identity: { lastname, firstname } } = usersSeedList[1]; + const token = '1296'; + const fakeNow = loginCodeLock.lockedUntil.getTime() + 60 * 1000; + fakeDate.returns(fakeNow); + + const response = await app.inject({ + method: 'GET', + url: `/users/passwordtoken/${token}?firstname=${firstname}&lastname=${lastname}&company=${company}`, + }); + + expect(response.statusCode).toBe(429); + + const lockedUser = await User.findOne({ _id }, { loginCodeLock: 1 }).lean(); + expect(lockedUser.loginCodeLock.count).toBe(2); + expect(lockedUser.loginCodeLock.lockedUntil).toEqual(new Date(fakeNow + 15 * 60 * 1000)); + }); + it('should return 404 if company is not correct', async () => { const company = otherCompany._id; const { loginCode: token, identity: { lastname, firstname } } = usersSeedList[3]; @@ -421,6 +511,17 @@ describe('AUTHENTICATION ROUTES - POST /users/forgot-password', () => { sinon.assert.calledWith(sendVerificationCodeEmail, userEmail, sinon.match(sinon.match.string)); }); + it('should return 429 if origin mobile and verification code has already been tried 3 times', async () => { + const response = await app.inject({ + method: 'POST', + url: '/users/forgot-password', + payload: { email: usersSeedList[1].local.email, origin: MOBILE, type: EMAIL }, + }); + + expect(response.statusCode).toBe(429); + sinon.assert.notCalled(sendVerificationCodeEmail); + }); + it('should send a code verification by sms if origin mobile and type phone', async () => { const userEmail = usersSeedList[0].local.email; const response = await app.inject({ @@ -433,6 +534,17 @@ describe('AUTHENTICATION ROUTES - POST /users/forgot-password', () => { sinon.assert.calledWith(sendVerificationCodeSms, usersSeedList[0].contact, sinon.match(sinon.match.string)); }); + it('should return 409 if origin mobile, type phone and user has no phone', async () => { + const response = await app.inject({ + method: 'POST', + url: '/users/forgot-password', + payload: { email: usersSeedList[1].local.email, origin: MOBILE, type: PHONE }, + }); + + expect(response.statusCode).toBe(409); + sinon.assert.notCalled(sendVerificationCodeSms); + }); + it('should return 400 if origin mobile and wrong type', async () => { const userEmail = usersSeedList[0].local.email; const response = await app.inject({ diff --git a/tests/integration/seed/usersSeed.js b/tests/integration/seed/usersSeed.js index b73aca8dbf..d7b932ab93 100644 --- a/tests/integration/seed/usersSeed.js +++ b/tests/integration/seed/usersSeed.js @@ -159,6 +159,8 @@ const usersSeedList = [ administrative: { certificates: [{ driveId: '1234567890' }], driveFolder: { driveId: '0987654321' } }, origin: WEBAPP, formationExpoTokenList: ['ExponentPushToken[jeSuisUnAutreIdExpo]'], + loginCode: '4321', + loginCodeLock: { attempts: 2, count: 1, lockedUntil: new Date('2021-01-25T10:05:00.000Z') }, }, { // 2 _id: new ObjectId(), @@ -469,6 +471,7 @@ const identityVerifications = [ code: '3310', createdAt: new Date('2021-01-25T10:05:32.582Z'), }, + { _id: new ObjectId(), email: usersSeedList[1].local.email, code: '4321', attempts: 3 }, ]; const isInList = (list, user) => list.some(i => i._id.toHexString() === user._id.toHexString()); diff --git a/tests/integration/server.test.js b/tests/integration/server.test.js index 657467f0a7..498074614d 100644 --- a/tests/integration/server.test.js +++ b/tests/integration/server.test.js @@ -23,3 +23,38 @@ describe('SCAN PATH GUARD', () => { expect(response.statusCode).not.toBe(403); }); }); + +describe('CORS', () => { + it('should allow the webapp origin to call the api with credentials', async () => { + const origin = process.env.WEBSITE_HOSTNAME; + const response = await app.inject({ + method: 'OPTIONS', + url: '/users/forgot-password', + headers: { origin, 'access-control-request-method': 'POST' }, + }); + + expect(response.headers['access-control-allow-origin']).toBe(origin); + expect(response.headers['access-control-allow-credentials']).toBe('true'); + }); + + it('should allow the web version of the mobile app to call the api', async () => { + const origin = process.env.MOBILE_WEBSITE_HOSTNAME; + const response = await app.inject({ + method: 'OPTIONS', + url: '/users/forgot-password', + headers: { origin, 'access-control-request-method': 'POST' }, + }); + + expect(response.headers['access-control-allow-origin']).toBe(origin); + }); + + it('should not allow another origin to call the api', async () => { + const response = await app.inject({ + method: 'OPTIONS', + url: '/users/forgot-password', + headers: { origin: 'https://evil.example.com', 'access-control-request-method': 'POST' }, + }); + + expect(response.headers['access-control-allow-origin']).toBeUndefined(); + }); +}); diff --git a/tests/unit/helpers/authentication.test.js b/tests/unit/helpers/authentication.test.js index 49f9db4412..22b9216a04 100644 --- a/tests/unit/helpers/authentication.test.js +++ b/tests/unit/helpers/authentication.test.js @@ -3,6 +3,7 @@ const { expect } = require('expect'); const sinon = require('sinon'); const Boom = require('@hapi/boom'); const bcrypt = require('bcryptjs'); +const crypto = require('crypto'); const SinonMongoose = require('../sinonMongoose'); const AuthenticationHelper = require('../../../src/helpers/authentication'); const EmailHelper = require('../../../src/helpers/email'); @@ -72,7 +73,7 @@ describe('authenticate', () => { { _id: user._id, firstMobileConnectionDate: { $exists: false } }, { $set: { firstMobileConnectionDate: '2022-09-18T10:00:00.000Z', firstMobileConnectionMode: AUTHENTICATION }, - $unset: { loginCode: '' }, + $unset: { loginCode: '', loginCodeLock: '' }, } ); sinon.assert.calledOnceWithExactly(compare, payload.password, 'toto'); @@ -312,11 +313,14 @@ describe('updatePassword', () => { describe('sendToken', () => { let encode; + let updateOne; beforeEach(() => { encode = sinon.stub(AuthenticationHelper, 'encode'); + updateOne = sinon.stub(User, 'updateOne'); }); afterEach(() => { encode.restore(); + updateOne.restore(); }); it('should return token with user', async () => { @@ -329,6 +333,25 @@ describe('sendToken', () => { const result = await AuthenticationHelper.sendToken(user); expect(result).toEqual({ token: '1234567890', user: userPayload }); sinon.assert.calledWithExactly(encode, userPayload); + sinon.assert.notCalled(updateOne); + }); + + it('should remove login code lock of user', async () => { + const email = 'carolyn@alenvi.io'; + const user = { _id: new ObjectId(), local: { email }, loginCodeLock: { attempts: 2 } }; + const userPayload = { _id: user._id, email }; + + encode.returns('1234567890'); + + const result = await AuthenticationHelper.sendToken(user); + + expect(result).toEqual({ token: '1234567890', user: userPayload }); + sinon.assert.calledOnceWithExactly( + updateOne, + { _id: user._id }, + { $unset: { loginCodeLock: '' } }, + { timestamps: false } + ); }); }); @@ -358,7 +381,8 @@ describe('forgotPassword', () => { let sendVerificationCodeEmail; let sendVerificationCodeSms; let generatePasswordTokenStub; - let identityVerificationFindOneAndUpdate; + let identityVerificationFindOne; + let identityVerificationUpdateOne; let identityVerificationCreate; let codeVerification; let userFindOne; @@ -368,9 +392,10 @@ describe('forgotPassword', () => { sendVerificationCodeEmail = sinon.stub(EmailHelper, 'sendVerificationCodeEmail'); sendVerificationCodeSms = sinon.stub(SmsHelper, 'sendVerificationCodeSms'); generatePasswordTokenStub = sinon.stub(AuthenticationHelper, 'generatePasswordToken'); - identityVerificationFindOneAndUpdate = sinon.stub(IdentityVerification, 'findOneAndUpdate'); + identityVerificationFindOne = sinon.stub(IdentityVerification, 'findOne'); + identityVerificationUpdateOne = sinon.stub(IdentityVerification, 'updateOne'); identityVerificationCreate = sinon.stub(IdentityVerification, 'create'); - codeVerification = sinon.stub(Math, 'random'); + codeVerification = sinon.stub(crypto, 'randomInt'); userFindOne = sinon.stub(User, 'findOne'); }); afterEach(() => { @@ -378,7 +403,8 @@ describe('forgotPassword', () => { sendVerificationCodeEmail.restore(); sendVerificationCodeSms.restore(); generatePasswordTokenStub.restore(); - identityVerificationFindOneAndUpdate.restore(); + identityVerificationFindOne.restore(); + identityVerificationUpdateOne.restore(); identityVerificationCreate.restore(); codeVerification.restore(); userFindOne.restore(); @@ -395,7 +421,8 @@ describe('forgotPassword', () => { sinon.assert.calledOnceWithExactly(generatePasswordTokenStub, email, 3600000); sinon.assert.calledWithExactly(forgotPasswordEmail, email, { token: '123456789' }); sinon.assert.notCalled(sendVerificationCodeEmail); - sinon.assert.notCalled(identityVerificationFindOneAndUpdate); + sinon.assert.notCalled(identityVerificationFindOne); + sinon.assert.notCalled(identityVerificationUpdateOne); sinon.assert.notCalled(identityVerificationCreate); sinon.assert.notCalled(codeVerification); sinon.assert.notCalled(userFindOne); @@ -404,10 +431,9 @@ describe('forgotPassword', () => { it('should create and send a verification code if origin mobile and type email', async () => { const email = 'toto@toto.com'; - codeVerification.returns(0.1111); - identityVerificationFindOneAndUpdate.returns(SinonMongoose.stubChainedQueries(null, ['lean'])); - identityVerificationCreate.returns({ email, code: '1999' }); + codeVerification.returns(1999); sendVerificationCodeEmail.returns({ sent: true }); + identityVerificationFindOne.returns(SinonMongoose.stubChainedQueries(null, ['lean'])); const result = await AuthenticationHelper.forgotPassword({ email, origin: MOBILE, type: EMAIL }); @@ -416,43 +442,59 @@ describe('forgotPassword', () => { sinon.assert.notCalled(forgotPasswordEmail); sinon.assert.notCalled(generatePasswordTokenStub); sinon.assert.notCalled(sendVerificationCodeSms); - sinon.assert.calledOnceWithExactly(identityVerificationCreate, { email, code: '1999' }); + sinon.assert.notCalled(userFindOne); + sinon.assert.notCalled(identityVerificationUpdateOne); + sinon.assert.calledOnceWithExactly(codeVerification, 1000, 10000); SinonMongoose.calledOnceWithExactly( - identityVerificationFindOneAndUpdate, - [{ query: 'findOneAndUpdate', args: [{ email }, { $set: { code: '1999' } }, { new: true }] }, { query: 'lean' }] + identityVerificationFindOne, + [{ query: 'findOne', args: [{ email }, { updatedAt: 1 }] }, { query: 'lean' }] ); + sinon.assert.calledOnceWithExactly(identityVerificationCreate, { email, code: '1999' }); }); - it('should update and send new verification code if already exists one', async () => { + it('should only update code if verification code was created less than one hour ago', async () => { const email = 'toto@toto.com'; - codeVerification.returns(0.1111); - identityVerificationFindOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ email, code: '1999' }, ['lean'])); - identityVerificationCreate.returns(null); + const verification = { _id: new ObjectId(), updatedAt: new Date(Date.now() - 30 * 60 * 1000) }; + codeVerification.returns(1999); sendVerificationCodeEmail.returns({ sent: true }); + identityVerificationFindOne.returns(SinonMongoose.stubChainedQueries(verification, ['lean'])); const result = await AuthenticationHelper.forgotPassword({ email, origin: MOBILE, type: EMAIL }); expect(result).toEqual({ sent: true }); sinon.assert.calledWithExactly(sendVerificationCodeEmail, email, '1999'); - sinon.assert.notCalled(forgotPasswordEmail); - sinon.assert.notCalled(generatePasswordTokenStub); + sinon.assert.calledOnceWithExactly( + identityVerificationUpdateOne, + { _id: verification._id }, + { $set: { code: '1999' } } + ); sinon.assert.notCalled(identityVerificationCreate); - sinon.assert.notCalled(userFindOne); - sinon.assert.notCalled(sendVerificationCodeSms); - SinonMongoose.calledOnceWithExactly( - identityVerificationFindOneAndUpdate, - [{ query: 'findOneAndUpdate', args: [{ email }, { $set: { code: '1999' } }, { new: true }] }, { query: 'lean' }] + }); + + it('should update code and reset attempts if verification code was created more than one hour ago', async () => { + const email = 'toto@toto.com'; + const verification = { _id: new ObjectId(), updatedAt: new Date(Date.now() - 2 * 60 * 60 * 1000) }; + codeVerification.returns(1999); + sendVerificationCodeEmail.returns({ sent: true }); + identityVerificationFindOne.returns(SinonMongoose.stubChainedQueries(verification, ['lean'])); + + await AuthenticationHelper.forgotPassword({ email, origin: MOBILE, type: EMAIL }); + + sinon.assert.calledOnceWithExactly( + identityVerificationUpdateOne, + { _id: verification._id }, + { $set: { code: '1999', attempts: 0 } } ); + sinon.assert.notCalled(identityVerificationCreate); }); it('should send a code verification if origin mobile and type phone', async () => { const email = 'toto@toto.com'; const user = { local: { email: 'toto@toto.com' }, contact: { phone: '0687654321', countryCode: '+33' } }; - codeVerification.returns(0.1111); - identityVerificationFindOneAndUpdate.returns(SinonMongoose.stubChainedQueries({ email, code: '1999' }, ['lean'])); - identityVerificationCreate.returns(null); - userFindOne.returns(SinonMongoose.stubChainedQueries(user, ['lean'])); + codeVerification.returns(1999); sendVerificationCodeSms.returns({ phone: '0687654321', countryCode: '+33' }); + userFindOne.returns(SinonMongoose.stubChainedQueries(user, ['lean'])); + identityVerificationFindOne.returns(SinonMongoose.stubChainedQueries(null, ['lean'])); const result = await AuthenticationHelper.forgotPassword({ email, origin: MOBILE, type: PHONE }); @@ -460,42 +502,12 @@ describe('forgotPassword', () => { sinon.assert.notCalled(sendVerificationCodeEmail); sinon.assert.notCalled(forgotPasswordEmail); sinon.assert.notCalled(generatePasswordTokenStub); - sinon.assert.notCalled(identityVerificationCreate); - sinon.assert.calledOnceWithExactly(sendVerificationCodeSms, { phone: '0687654321', countryCode: '+33' }, '1999'); - SinonMongoose.calledOnceWithExactly( - identityVerificationFindOneAndUpdate, - [{ query: 'findOneAndUpdate', args: [{ email }, { $set: { code: '1999' } }, { new: true }] }, { query: 'lean' }] - ); SinonMongoose.calledOnceWithExactly( userFindOne, - [{ query: 'findOne', args: [{ 'local.email': 'toto@toto.com' }, { contact: 1 }] }, { query: 'lean' }] + [{ query: 'findOne', args: [{ 'local.email': email }, { contact: 1 }] }, { query: 'lean' }] ); - }); - - it('should throw 409 if no phone in user', async () => { - const email = 'toto@toto.com'; - try { - const user = { local: { email: 'toto@toto.com' } }; - codeVerification.returns(0.1111); - identityVerificationFindOneAndUpdate - .returns(SinonMongoose.stubChainedQueries({ email, code: '1999' }, ['lean'])); - identityVerificationCreate.returns(null); - userFindOne.returns(SinonMongoose.stubChainedQueries(user, ['lean'])); - - await AuthenticationHelper.forgotPassword({ email, origin: MOBILE, type: PHONE }); - } catch (e) { - expect(e.output.statusCode).toEqual(409); - } finally { - SinonMongoose.calledOnceWithExactly( - identityVerificationFindOneAndUpdate, - [{ query: 'findOneAndUpdate', args: [{ email }, { $set: { code: '1999' } }, { new: true }] }, { query: 'lean' }] - ); - SinonMongoose.calledOnceWithExactly( - userFindOne, - [{ query: 'findOne', args: [{ 'local.email': 'toto@toto.com' }, { contact: 1 }] }, { query: 'lean' }] - ); - sinon.assert.notCalled(sendVerificationCodeSms); - } + sinon.assert.calledOnceWithExactly(sendVerificationCodeSms, { phone: '0687654321', countryCode: '+33' }, '1999'); + sinon.assert.calledOnceWithExactly(identityVerificationCreate, { email, code: '1999' }); }); }); diff --git a/tests/unit/helpers/courses.test.js b/tests/unit/helpers/courses.test.js index 50827cb716..1e1d19fd47 100644 --- a/tests/unit/helpers/courses.test.js +++ b/tests/unit/helpers/courses.test.js @@ -3109,7 +3109,7 @@ describe('getCourse', () => { { path: 'trainees', select: 'identity.firstname identity.lastname local.email contact picture.link ' - + 'firstMobileConnectionDate loginCode', + + 'firstMobileConnectionDate', populate: { path: 'company' }, }, { @@ -3132,7 +3132,7 @@ describe('getCourse', () => { { path: 'tutors', select: 'identity.firstname identity.lastname contact local.email picture.link ' - + 'firstMobileConnectionDate loginCode', + + 'firstMobileConnectionDate', }, { path: 'slots', @@ -4674,7 +4674,7 @@ describe('getCourseFollowUp', () => { query: 'populate', args: [{ path: 'trainees', - select: 'identity.firstname identity.lastname firstMobileConnectionDate loginCode', + select: 'identity.firstname identity.lastname firstMobileConnectionDate', populate: { path: 'company' }, }], }, @@ -5726,7 +5726,10 @@ describe('addTrainee', () => { [ { query: 'findOne', - args: [{ _id: user._id }, { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1 }], + args: [ + { _id: user._id }, + { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1, 'local.password': 1 }, + ], }, { query: 'lean' }, ] @@ -5768,7 +5771,10 @@ describe('addTrainee', () => { [ { query: 'findOne', - args: [{ _id: user._id }, { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1 }], + args: [ + { _id: user._id }, + { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1, 'local.password': 1 }, + ], }, { query: 'lean' }, ] @@ -5782,6 +5788,21 @@ describe('addTrainee', () => { sinon.assert.notCalled(userUpdateOne); }); + it('should register an existing user with a password to course and not create loginCode', async () => { + const user = { _id: new ObjectId(), formationExpoTokenList: 'ExponentPushToken[bla]', local: { password: 'hash' } }; + const course = { _id: new ObjectId(), misc: 'Test', type: INTRA, companies: [new ObjectId()] }; + const payload = { trainee: user._id }; + const credentials = { _id: new ObjectId(), company: { _id: new ObjectId() } }; + + userFindOne.returns(SinonMongoose.stubChainedQueries(user, ['lean'])); + courseFindOneAndUpdate.returns(course); + + await CourseHelper.addTrainee(course._id, payload, credentials); + + sinon.assert.notCalled(userUpdateOne); + sinon.assert.calledOnceWithExactly(sendBlendedCourseRegistrationNotification, user, course._id); + }); + it('should register an existing user to course (INTRA) and create loginCode in db', async () => { const user = { _id: new ObjectId(), formationExpoTokenList: 'ExponentPushToken[bla]' }; const course = { _id: new ObjectId(), misc: 'Test', type: INTRA, companies: [new ObjectId()] }; @@ -5805,7 +5826,10 @@ describe('addTrainee', () => { [ { query: 'findOne', - args: [{ _id: user._id }, { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1 }], + args: [ + { _id: user._id }, + { formationExpoTokenList: 1, firstMobileConnectionDate: 1, loginCode: 1, 'local.password': 1 }, + ], }, { query: 'lean' }, ] @@ -10193,7 +10217,14 @@ describe('addTutor', () => { query: 'findOne', args: [ { _id: tutorId }, - { firstMobileConnectionDate: 1, loginCode: 1, identity: 1, contact: 1, 'local.email': 1 }, + { + firstMobileConnectionDate: 1, + loginCode: 1, + identity: 1, + contact: 1, + 'local.email': 1, + 'local.password': 1, + }, ], }, { query: 'lean' }, @@ -10201,6 +10232,25 @@ describe('addTutor', () => { ); }); + it('should add tutor with a password to course and not create loginCode', async () => { + const tutorId = new ObjectId(); + const course = { _id: new ObjectId(), misc: 'Test', tutors: [new ObjectId()] }; + const tutor = { + _id: tutorId, + identity: { firstname: 'Jeanne', lastname: 'Tutor' }, + local: { email: 'tutor@email.com', password: 'hash' }, + }; + + emailAddTutor.returns('email sent'); + courseFindOneAndUpdate.returns(SinonMongoose.stubChainedQueries(course, ['lean'])); + userFindOne.returns(SinonMongoose.stubChainedQueries(tutor, ['lean'])); + + await CourseHelper.addTutor(course._id, { tutor: tutorId }); + + sinon.assert.notCalled(userUpdateOne); + sinon.assert.calledOnceWithExactly(emailAddTutor, course._id, tutorId); + }); + it('should add tutor to course (with connection infos and gSheetId)', async () => { const tutorId = new ObjectId(); const course = { _id: new ObjectId(), misc: 'Test', tutors: [new ObjectId()], gSheetId: '12345' }; @@ -10244,7 +10294,14 @@ describe('addTutor', () => { query: 'findOne', args: [ { _id: tutorId }, - { firstMobileConnectionDate: 1, loginCode: 1, identity: 1, contact: 1, 'local.email': 1 }, + { + firstMobileConnectionDate: 1, + loginCode: 1, + identity: 1, + contact: 1, + 'local.email': 1, + 'local.password': 1, + }, ], }, { query: 'lean' }, diff --git a/yarn.lock b/yarn.lock index 0cee8b9ef9..b5ca7dd060 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1,6 +1,7 @@ # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 + "@aashutoshrathi/word-wrap@^1.2.3": version "1.2.6" resolved "https://registry.yarnpkg.com/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz#bd9154aec9983f77b3a034ecaa015c2e4201f6cf" @@ -191,6 +192,13 @@ dependencies: "@hapi/hoek" "^11.0.2" +"@hapi/ammo@^6.0.2": + version "6.0.2" + resolved "https://registry.yarnpkg.com/@hapi/ammo/-/ammo-6.0.2.tgz#d4b30a5d44aaa1bb161402fde59bce66ada21969" + integrity sha512-YeVEkur58mIJ2wxIuIDGKDgpiNEmLOGswggGarZu/VORUPLBjOUPiaZSl2oFZGECqt3yPSNFBiHTwOQH51U+vA== + dependencies: + "@hapi/hoek" "^11.0.2" + "@hapi/b64@^6.0.1": version "6.0.1" resolved "https://registry.yarnpkg.com/@hapi/b64/-/b64-6.0.1.tgz#786b47dc070e14465af49e2428c1025bd06ed3df" @@ -252,10 +260,10 @@ "@hapi/podium" "^5.0.0" "@hapi/validate" "^2.0.1" -"@hapi/content@^6.0.1", "@hapi/content@^6.0.2": - version "6.0.2" - resolved "https://registry.yarnpkg.com/@hapi/content/-/content-6.0.2.tgz#de71e00e555d9a36b950f645626aa0ab4cd1adec" - integrity sha512-OKyCOTjNR1hftwSjk9ueyAQTw8AwapvzBrPIWMGn39vhR5PmqLdYFmLc35bsSBye7gSMnlkXfc679bUdMIcRyQ== +"@hapi/content@^6.0.3": + version "6.0.3" + resolved "https://registry.yarnpkg.com/@hapi/content/-/content-6.0.3.tgz#f0e0a363fbba62c942ef3cedd5a3c0df44077245" + integrity sha512-ksXemMNZAwPq/mu1a9TZ7LDUSgMR9sexBgpalF3nrP6SM42ARlnBZs58IS5Ay+o4o7y6tFNXL+rMJkQ5ghvCSw== dependencies: "@hapi/boom" "^10.0.0" @@ -310,13 +318,13 @@ "@hapi/validate" "1.x.x" pumpify "2.x.x" -"@hapi/hapi@~21.4.10": - version "21.4.10" - resolved "https://registry.yarnpkg.com/@hapi/hapi/-/hapi-21.4.10.tgz#43fa3dbf1ceb180f8558525641fd3ea68a0d1c2e" - integrity sha512-G0l7tch1/85Gkyasmmjvjam2IWbx/9zCp4AQx4nZ/nn/rrrmVmRvFejj2ZGe5j3wFZVCLt2+Zeg95ImFFom+7w== +"@hapi/hapi@~21.4.13": + version "21.4.13" + resolved "https://registry.yarnpkg.com/@hapi/hapi/-/hapi-21.4.13.tgz#a03e4c5a56b9a61ccce6412680557183b37c022d" + integrity sha512-eupLASu8jIrFvo8yu+xK/C5v2kydqK7v43XIfBtFW4NrJKylud0sEhESoq7oYRe1uxOIiowJAz6mVYmCxC2w1g== dependencies: "@hapi/accept" "^6.0.3" - "@hapi/ammo" "^6.0.1" + "@hapi/ammo" "^6.0.2" "@hapi/boom" "^10.0.1" "@hapi/bounce" "^3.0.2" "@hapi/call" "^9.0.1" @@ -326,10 +334,10 @@ "@hapi/hoek" "^11.0.7" "@hapi/mimos" "^7.0.1" "@hapi/podium" "^5.0.2" - "@hapi/shot" "^6.0.2" + "@hapi/shot" "^6.0.3" "@hapi/somever" "^4.1.1" "@hapi/statehood" "^8.2.1" - "@hapi/subtext" "^8.1.3" + "@hapi/subtext" "^8.1.5" "@hapi/teamwork" "^6.0.1" "@hapi/topo" "^6.0.2" "@hapi/validate" "^2.0.1" @@ -404,14 +412,14 @@ dependencies: "@hapi/hoek" "9.x.x" -"@hapi/pez@^6.1.1": - version "6.1.1" - resolved "https://registry.yarnpkg.com/@hapi/pez/-/pez-6.1.1.tgz#d99a4f62291b1c008179bb534791b8dfc59f7f8d" - integrity sha512-yg2OS1tC0S1sHXvhUtWsfRn6lrKl9jKtRhZ+EI0woOW/gqX5vM2PZ1459ypCvCYDRLJ9nIyueeEH5MJV1ZDqIg== +"@hapi/pez@^6.1.2": + version "6.1.3" + resolved "https://registry.yarnpkg.com/@hapi/pez/-/pez-6.1.3.tgz#d31a9cb1fcb2593100562babb9fd3501b37bcd91" + integrity sha512-hit/Yb7jYv/rAKDMTJJIhPslxHgt9WxmFfUvZ97rHLsq+HpI6eQE6HbGhFE/fhOHT8llkRETcjJX4+7ut7GF3w== dependencies: "@hapi/b64" "^6.0.1" "@hapi/boom" "^10.0.1" - "@hapi/content" "^6.0.1" + "@hapi/content" "^6.0.3" "@hapi/hoek" "^11.0.7" "@hapi/nigel" "^5.0.1" @@ -438,10 +446,10 @@ "@hapi/teamwork" "^6.0.0" "@hapi/validate" "^2.0.1" -"@hapi/shot@^6.0.2": - version "6.0.2" - resolved "https://registry.yarnpkg.com/@hapi/shot/-/shot-6.0.2.tgz#30f0688a9fb800d8ad6dbf4b2033173335dd5571" - integrity sha512-WKK1ShfJTrL1oXC0skoIZQYzvLsyMDEF8lfcWuQBjpjCN29qivr9U36ld1z0nt6edvzv28etNMOqUF4klnHryw== +"@hapi/shot@^6.0.3": + version "6.0.3" + resolved "https://registry.yarnpkg.com/@hapi/shot/-/shot-6.0.3.tgz#7432d547a429ba27c4dde2949cdc5628c5bca236" + integrity sha512-xKmKONUE5AxUNK+EQCSCz35UpPq4cSy6wRCFvMLCDHdyPeXsmAvwxvU4OemGqpWHtAQHyCPjnDbm/fEU9O6l/w== dependencies: "@hapi/hoek" "^11.0.2" "@hapi/validate" "^2.0.1" @@ -467,18 +475,18 @@ "@hapi/iron" "^7.0.1" "@hapi/validate" "^2.0.1" -"@hapi/subtext@^8.1.3": - version "8.1.3" - resolved "https://registry.yarnpkg.com/@hapi/subtext/-/subtext-8.1.3.tgz#e682026e0449b76083afd214f2c91fc9e7c6158c" - integrity sha512-WTpEZQjBP3UJ3gGunNl3w5Ao1EOJsuu2vttZ2KEcG+csSLxc0dI6VIkl2md2jDlHiQ2ARAoqdSUScy05A/NHtA== +"@hapi/subtext@^8.1.5": + version "8.1.5" + resolved "https://registry.yarnpkg.com/@hapi/subtext/-/subtext-8.1.5.tgz#2491d6874c50b3bd5ce505c128fb752fe971b711" + integrity sha512-VSoL75dYqMfs2URprWPu9RXdL/+c5pZ5L0siSa3ZKg0VQKGQn2Yncd05Jl/154VvVYO/ymrOW3TR/a9psp1+kA== dependencies: "@hapi/boom" "^10.0.1" "@hapi/bourne" "^3.0.0" - "@hapi/content" "^6.0.2" + "@hapi/content" "^6.0.3" "@hapi/file" "^3.0.0" "@hapi/hoek" "^11.0.7" - "@hapi/pez" "^6.1.1" - "@hapi/wreck" "^18.1.1" + "@hapi/pez" "^6.1.2" + "@hapi/wreck" "^18.1.3" "@hapi/teamwork@^6.0.0": version "6.0.0" @@ -532,10 +540,10 @@ dependencies: "@hapi/hoek" "^11.0.2" -"@hapi/wreck@^18.1.1": - version "18.1.2" - resolved "https://registry.yarnpkg.com/@hapi/wreck/-/wreck-18.1.2.tgz#1c1c84427085d7018ff4157ef3eb1e2cf080b26b" - integrity sha512-3dMnV2pfhQiyEqu8DL3VBmxkdLiRDiiUDuG79Dp+UK1gL9ZxAfDOUhB6k3D5MLqcgJJ1IARyGFhwoc1NITr/pg== +"@hapi/wreck@^18.1.3": + version "18.1.3" + resolved "https://registry.yarnpkg.com/@hapi/wreck/-/wreck-18.1.3.tgz#383450763a2fae7cc71cdb8f1cc5509575b6221e" + integrity sha512-PZ1FQpk5DWbEFFYiHu/kCkWeSHwUhAxDSUdv6Zsp1qi2coUP22cnYQlp647KCSsCc4uFB4LOTsHo9f5k7vgtHg== dependencies: "@hapi/boom" "^10.0.1" "@hapi/bourne" "^3.0.0" @@ -1256,12 +1264,12 @@ available-typed-arrays@^1.0.7: dependencies: possible-typed-array-names "^1.0.0" -axios@~1.20.0: - version "1.20.0" - resolved "https://registry.yarnpkg.com/axios/-/axios-1.20.0.tgz#515513445aa60e71d04b6521ca6210829ccb4786" - integrity sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg== +axios@~1.21.1: + version "1.21.1" + resolved "https://registry.yarnpkg.com/axios/-/axios-1.21.1.tgz#e15d57924d677aea9adb9f06b112b13b9ea0b9dd" + integrity sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ== dependencies: - follow-redirects "^1.16.0" + follow-redirects "^1.16.2" form-data "^4.0.6" https-proxy-agent "^5.0.1" proxy-from-env "^2.1.0" @@ -2503,10 +2511,10 @@ flatted@^3.4.2: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.4.4.tgz#aeeca2a506303f0cee61c59e6c9f2a88d2f29fc6" integrity sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q== -follow-redirects@^1.16.0: - version "1.16.0" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.16.0.tgz#28474a159d3b9d11ef62050a14ed60e4df6d61bc" - integrity sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw== +follow-redirects@^1.16.2: + version "1.16.3" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.16.3.tgz#62b60932427f616327014a5e401e8fc5e9027e9b" + integrity sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A== fontkit@^2.0.4: version "2.0.4" @@ -3546,10 +3554,10 @@ joi-objectid@~4.0.2: resolved "https://registry.yarnpkg.com/joi-objectid/-/joi-objectid-4.0.2.tgz#a4065aa91431bbc6959a57f7b4d1dd10bd95a4b7" integrity sha512-OjYM+wK/JGo2bSb9ADEyzxxROJPZYtrqIwBbywpJ2a98oKlbLtWTKvpzmrnXzou69Ey9EsjHsFvZYzpjeCdKuA== -joi@~18.2.9: - version "18.2.9" - resolved "https://registry.yarnpkg.com/joi/-/joi-18.2.9.tgz#8f489aebefab85cfa9979ea4471e3eea022787b1" - integrity sha512-2mD929bUVKUhOLQQEVhlf6EZ0Mlo0DeRb5MO7cViR9AXLtBauuccEtB1py9Ocxpo/P7ucnh442iY/iOwrh3IQw== +joi@~18.3.2: + version "18.3.2" + resolved "https://registry.yarnpkg.com/joi/-/joi-18.3.2.tgz#ca16b431106d9af32a0436aff474d3992230c788" + integrity sha512-iUivApKYw5GpZmq2Sy6El99j7noo8QSUFZlyQtr3HCkosC/b5wKF6/Y3teiHIlaM8WI38sAT3P+51rB0lhAhJA== dependencies: "@hapi/address" "^5.1.1" "@hapi/formula" "^3.0.2" @@ -3707,10 +3715,10 @@ jws@^4.0.1: jwa "^2.0.1" safe-buffer "^5.0.1" -kareem@3.4.0: - version "3.4.0" - resolved "https://registry.yarnpkg.com/kareem/-/kareem-3.4.0.tgz#66b3d09ac43ba1c8611df2c69fe1424f0acd49b2" - integrity sha512-JAKhnR4S027v/8949QXNInRskgETCg9rFUMi1VjhGbjX+XltCAAEFcXykkSocNkom1kc66EMJfjWvhj87BDQKg== +kareem@3.4.1: + version "3.4.1" + resolved "https://registry.yarnpkg.com/kareem/-/kareem-3.4.1.tgz#468c10416476f86bcef127d00f937cbb0a029e3b" + integrity sha512-UlgCAFNAdk/HLSsbfkmbH8pJqpEN52Ek8RG53Ys1i3Q3gbCQruSrWpplZlgIGyDHX/LNoLW97ei3OG43s7UhUA== keyv@^5.6.0: version "5.6.0" @@ -4040,16 +4048,16 @@ mongoose-lean-virtuals@~2.1.0: dependencies: mpath "^0.8.4" -mongoose@~9.11.0: - version "9.11.0" - resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-9.11.0.tgz#f9517607b010747c54bc8c4054cd0f6cad1e879a" - integrity sha512-dclC0gx/AfasCMX0VChpv4FQ69ylEf3Crve0zKhmYM3VVBK8b0FU8VODx50Th7evM60JxVal8V/1XZQiwLHjwA== +mongoose@~9.11.4: + version "9.11.4" + resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-9.11.4.tgz#a15599b2ecb3d6885de9e0341f8dddc5513f9f7e" + integrity sha512-+xME0fduXl1sWF+NZpJHZaNcwQSt+X2vbJ/h7GRSZ/ltLycAkGZSEABhzic0+q3IMF66KqF0viEE5+frchKCAQ== dependencies: "@standard-schema/spec" "^1.1.0" - kareem "3.4.0" + kareem "3.4.1" mongodb "~7.7" mpath "0.9.0" - mquery "6.0.0" + mquery "6.0.1" ms "2.1.3" sift "17.1.3" @@ -4063,10 +4071,10 @@ mpath@^0.8.4: resolved "https://registry.yarnpkg.com/mpath/-/mpath-0.8.4.tgz#6b566d9581621d9e931dd3b142ed3618e7599313" integrity sha512-DTxNZomBcTWlrMW76jy1wvV37X/cNNxPW1y2Jzd4DZkAaC5ZGsm8bfGfNOthcDuRJujXLqiuS6o3Tpy0JEoh7g== -mquery@6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/mquery/-/mquery-6.0.0.tgz#ef6d744619ff13368c1b137d09a7adc5530fce9e" - integrity sha512-b2KQNsmgtkscfeDgkYMcWGn9vZI9YoXh802VDEwE6qc50zxBFQ0Oo8ROkawbPAsXCY1/Z1yp0MagqsZStPWJjw== +mquery@6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/mquery/-/mquery-6.0.1.tgz#4b98f9e19fc7b226c89bc06e5e11f254c16a4877" + integrity sha512-/Nijmq3JcpHwDM+5CwBp5yEl6fUa6jLsIhPsoQywlGXU/ZrKIvSpBzfaGnW9BLqcne/CoUwd1ch7MRqptDgFTA== ms@2.1.2: version "2.1.2" @@ -5763,4 +5771,3 @@ yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== -