Skip to content

Commit

Permalink
Merge pull request #9149 from weseek/imprv/125884-154071-eliminate-re…
Browse files Browse the repository at this point in the history
…q.t()

imprv: Avoid using req.t()
  • Loading branch information
mergify[bot] authored Nov 5, 2024
2 parents 338859f + ddb0874 commit fabb4d2
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 24 deletions.
8 changes: 0 additions & 8 deletions apps/app/src/server/crowi/express-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,4 @@ module.exports = function(crowi, app) {
app.use(registerSafeRedirect);
app.use(injectCurrentuserToLocalvars);
app.use(autoReconnectToS2sMsgServer);

// TODO: Remove this workaround implementation when i18n works correctly.
// For now, req.t returns string given to req.t(string)
app.use((req, res, next) => {
req.t = str => (typeof str === 'string' ? str : '');

next();
});
};
29 changes: 24 additions & 5 deletions apps/app/src/server/routes/apiv3/app-settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { body } from 'express-validator';
import { i18n } from '^/config/next-i18next.config';

import { SupportedAction } from '~/interfaces/activity';
import { getTranslation } from '~/server/service/i18next';
import { accessTokenParser } from '~/server/middlewares/access-token-parser';
import loggerFactory from '~/utils/logger';

Expand Down Expand Up @@ -182,10 +183,26 @@ module.exports = (crowi) => {
body('gcsBucket').trim(),
body('gcsUploadNamespace').trim(),
body('gcsReferenceFileWithRelayMode').if(value => value != null).isBoolean(),
body('s3Region').trim().if(value => value !== '').matches(/^[a-z]+-[a-z]+-\d+$/)
.withMessage((value, { req }) => req.t('validation.aws_region')),
body('s3CustomEndpoint').trim().if(value => value !== '').matches(/^(https?:\/\/[^/]+|)$/)
.withMessage((value, { req }) => req.t('validation.aws_custom_endpoint')),
body('s3Region')
.trim()
.if(value => value !== '')
.custom(async(value) => {
const { t } = await getTranslation();
if (!/^[a-z]+-[a-z]+-\d+$/.test(value)) {
throw new Error(t('validation.aws_region'));
}
return true;
}),
body('s3CustomEndpoint')
.trim()
.if(value => value !== '')
.custom(async(value) => {
const { t } = await getTranslation();
if (!/^(https?:\/\/[^/]+|)$/.test(value)) {
throw new Error(t('validation.aws_custom_endpoint'));
}
return true;
}),
body('s3Bucket').trim(),
body('s3AccessKeyId').trim().if(value => value !== '').matches(/^[\da-zA-Z]+$/),
body('s3SecretAccessKey').trim(),
Expand Down Expand Up @@ -552,14 +569,16 @@ module.exports = (crowi) => {
* description: Succeeded to send test mail for smtp
*/
router.post('/smtp-test', loginRequiredStrictly, adminRequired, addActivity, async(req, res) => {
const { t } = await getTranslation();

try {
await sendTestEmail(req.user.email);
const parameters = { action: SupportedAction.ACTION_ADMIN_MAIL_TEST_SUBMIT };
activityEvent.emit('update', res.locals.activity._id, parameters);
return res.apiv3({});
}
catch (err) {
const msg = req.t('validation.failed_to_send_a_test_email');
const msg = t('validation.failed_to_send_a_test_email');
logger.error('Error', err);
logger.debug('Error validate mail setting: ', err);
return res.apiv3Err(new ErrorV3(msg, 'send-email-with-smtp-failed'));
Expand Down
10 changes: 6 additions & 4 deletions apps/app/src/server/routes/apiv3/security-settings/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { generateAddActivityMiddleware } from '~/server/middlewares/add-activity
import { apiV3FormValidator } from '~/server/middlewares/apiv3-form-validator';
import ShareLink from '~/server/models/share-link';
import { configManager } from '~/server/service/config-manager';
import { getTranslation } from '~/server/service/i18next';
import loggerFactory from '~/utils/logger';
import { validateDeleteConfigs, prepareDeleteConfigValuesForCalc } from '~/utils/page-delete-config';

Expand Down Expand Up @@ -931,6 +932,7 @@ module.exports = (crowi) => {
* $ref: '#/components/schemas/SamlAuthSetting'
*/
router.put('/saml', loginRequiredStrictly, adminRequired, addActivity, validator.samlAuth, apiV3FormValidator, async(req, res) => {
const { t } = await getTranslation();

// For the value of each mandatory items,
// check whether it from the environment variables is empty and form value to update it is empty
Expand All @@ -940,12 +942,12 @@ module.exports = (crowi) => {
const key = configKey.replace('security:passport-saml:', '');
const formValue = req.body[key];
if (configManager.getConfigFromEnvVars('crowi', configKey) === null && formValue == null) {
const formItemName = req.t(`security_setting.form_item_name.${key}`);
invalidValues.push(req.t('form_validation.required', formItemName));
const formItemName = t(`security_setting.form_item_name.${key}`);
invalidValues.push(t('form_validation.required', formItemName));
}
}
if (invalidValues.length !== 0) {
return res.apiv3Err(req.t('form_validation.error_message'), 400, invalidValues);
return res.apiv3Err(t('form_validation.error_message'), 400, invalidValues);
}

const rule = req.body.ABLCRule;
Expand All @@ -956,7 +958,7 @@ module.exports = (crowi) => {
crowi.passportService.parseABLCRule(rule);
}
catch (err) {
return res.apiv3Err(req.t('form_validation.invalid_syntax', req.t('security_settings.form_item_name.ABLCRule')), 400);
return res.apiv3Err(t('form_validation.invalid_syntax', t('security_settings.form_item_name.ABLCRule')), 400);
}
}

Expand Down
13 changes: 8 additions & 5 deletions apps/app/src/server/routes/apiv3/user-activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { SupportedAction } from '~/interfaces/activity';
import { RegistrationMode } from '~/interfaces/registration-mode';
import UserRegistrationOrder from '~/server/models/user-registration-order';
import { configManager } from '~/server/service/config-manager';
import { getTranslation } from '~/server/service/i18next';
import loggerFactory from '~/utils/logger';

const logger = loggerFactory('growi:routes:apiv3:user-activation');
Expand Down Expand Up @@ -75,6 +76,8 @@ export const completeRegistrationAction = (crowi) => {
} = crowi;

return async function(req, res) {
const { t } = await getTranslation();

if (req.user != null) {
return res.apiv3Err(new ErrorV3('You have been logged in', 'registration-failed'), 403);
}
Expand Down Expand Up @@ -103,16 +106,16 @@ export const completeRegistrationAction = (crowi) => {
let errorMessage = '';
if (!User.isEmailValid(email)) {
isError = true;
errorMessage += req.t('message.email_address_could_not_be_used');
errorMessage += t('message.email_address_could_not_be_used');
}
if (!isRegisterable) {
if (!errOn.username) {
isError = true;
errorMessage += req.t('message.user_id_is_not_available');
errorMessage += t('message.user_id_is_not_available');
}
if (!errOn.email) {
isError = true;
errorMessage += req.t('message.email_address_is_already_registered');
errorMessage += t('message.email_address_is_already_registered');
}
}
if (isError) {
Expand All @@ -122,10 +125,10 @@ export const completeRegistrationAction = (crowi) => {
User.createUserByEmailAndPassword(name, username, email, password, undefined, async(err, userData) => {
if (err) {
if (err.name === 'UserUpperLimitException') {
errorMessage = req.t('message.can_not_register_maximum_number_of_users');
errorMessage = t('message.can_not_register_maximum_number_of_users');
}
else {
errorMessage = req.t('message.failed_to_register');
errorMessage = t('message.failed_to_register');
}
return res.apiv3Err(new ErrorV3(errorMessage, 'registration-failed'), 403);
}
Expand Down
7 changes: 5 additions & 2 deletions apps/app/src/server/routes/login-passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ErrorV3 } from '@growi/core/dist/models';

import { SupportedAction } from '~/interfaces/activity';
import { ExternalAccountLoginError } from '~/models/vo/external-account-login-error';
import { getTranslation } from '~/server/service/i18next';
import { createRedirectToForUnauthenticated } from '~/server/util/createRedirectToForUnauthenticated';
import loggerFactory from '~/utils/logger';

Expand Down Expand Up @@ -239,12 +240,14 @@ module.exports = function(crowi, app) {
* @param {*} req
* @param {*} res
*/
const testLdapCredentials = (req, res) => {
const testLdapCredentials = async(req, res) => {
const { t } = await getTranslation();

if (!passportService.isLdapStrategySetup) {
logger.debug('LdapStrategy has not been set up');
return res.json(ApiResponse.success({
status: 'warning',
message: req.t('message.strategy_has_not_been_set_up', { strategy: 'LdapStrategy' }),
message: t('message.strategy_has_not_been_set_up', { strategy: 'LdapStrategy' }),
}));
}

Expand Down

0 comments on commit fabb4d2

Please sign in to comment.