Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/integration.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const server = Hapi.server({
collect: true,
},
cors: {
origin: ['*'],
origin: [process.env.WEBSITE_HOSTNAME, ...[process.env.MOBILE_WEBSITE_HOSTNAME].filter(Boolean)],

@manonpalin manonpalin Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pourquoi il faut le reecrire ? [process.env.WEBSITE_HOSTNAME, process.env.MOBILE_WEBSITE_HOSTNAME] ne suffit pas ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ça veut dire en gros :

  • WEBSITE_HOSTNAME obligatoire, le déploiement ne se fait pas si on a pas renseigné la variable d'env
  • MOBILE_WEBSITE_HOSTNAME est ajouté si définie sinon n'est pas prise en compte (dans le cas staging)

credentials: true,
additionalHeaders: ['accept-language', 'accept-encoding', 'access-control-request-headers', 'x-access-token'],
},
Expand Down
28 changes: 19 additions & 9 deletions src/helpers/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -40,7 +41,7 @@ exports.authenticate = async (payload) => {
firstMobileConnectionDate: CompaniDate().toISO(),
firstMobileConnectionMode: payload.mobileConnectionMode,
},
$unset: { loginCode: '' },
$unset: { loginCode: '', loginCodeLock: '' },
}
);
}
Expand Down Expand Up @@ -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 };
};

Expand All @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions src/helpers/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 18 additions & 9 deletions src/helpers/courses.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ const {
VENDOR_ADMIN,
TRAINING_ORGANISATION_MANAGER,
TRAINER,
CLIENT_ADMIN,
COACH,
REMOTE,
OPERATIONS,
HHhMM,
Expand Down Expand Up @@ -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([
Expand All @@ -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' },
},
{
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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 } });
}

Expand Down Expand Up @@ -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();

Expand All @@ -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 } });
}

Expand Down
2 changes: 2 additions & 0 deletions src/helpers/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down Expand Up @@ -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.',
Expand Down
2 changes: 2 additions & 0 deletions src/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions src/models/IdentityVerification.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
6 changes: 5 additions & 1 deletion src/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion src/routes/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -93,6 +93,7 @@ exports.plugin = {
}),
},
auth: false,
pre: [{ method: authorizeForgotPassword }],
},
handler: forgotPassword,
});
Expand Down
Loading
Loading