From c45d248c3cd69711fc6da49e7a4aa6c2f208776f Mon Sep 17 00:00:00 2001 From: David Baldwynn Date: Fri, 27 Oct 2017 20:46:00 -0700 Subject: [PATCH] internationalized transactional emails --- .../users.authentication.server.controller.js | 9 ++- app/views/index.server.view.pug | 8 ++- config/express.js | 58 +++++++++++++------ config/locales/de.json | 6 +- config/locales/es.json | 6 +- config/locales/fr.json | 6 +- config/locales/it.json | 6 +- public/modules/users/config/i18n/german.js | 4 +- .../authentication.client.controller.js | 5 +- .../controllers/password.client.controller.js | 5 +- .../controllers/verify.client.controller.js | 5 +- 11 files changed, 85 insertions(+), 33 deletions(-) diff --git a/app/controllers/users/users.authentication.server.controller.js b/app/controllers/users/users.authentication.server.controller.js index 541950b8..a893a9af 100755 --- a/app/controllers/users/users.authentication.server.controller.js +++ b/app/controllers/users/users.authentication.server.controller.js @@ -116,8 +116,12 @@ exports.signup = function(req, res) { // Init Variables var user = new User(req.body); + // Set language to visitor's language + user.language = req.cookies['userLang']; + // Add missing user fields user.provider = 'local'; + // Then save the temporary user nev.createTempUser(user, function (err, existingPersistentUser, newTempUser) { if (err) { @@ -127,7 +131,6 @@ exports.signup = function(req, res) { }); } - // new user created if (newTempUser) { const fn = pug.compileFile(__dirname + "/../../views/verification.email.view.pug"); @@ -173,6 +176,8 @@ exports.signin = function(req, res, next) { message: errorHandler.getErrorMessage(loginErr) }); } + + res.cookie('langCookie', user.language, { maxAge: 90000, httpOnly: true }); return res.json(user); }); } @@ -183,9 +188,9 @@ exports.signin = function(req, res, next) { * Signout */ exports.signout = function(req, res) { + res.destroyCookie('langCookie'); req.logout(); return res.status(200).send('You have successfully logged out.'); - }; /** diff --git a/app/views/index.server.view.pug b/app/views/index.server.view.pug index f152379f..10c29935 100644 --- a/app/views/index.server.view.pug +++ b/app/views/index.server.view.pug @@ -15,6 +15,12 @@ block content var socketPort = false; var socketUrl = false; var subdomainsDisabled = !{subdomainsDisabled}; + var locale = "en"; + + //Embedding locale + if locale + script(type='text/javascript'). + locale = "!{locale}"; //Embedding socketPort if socketPort @@ -24,7 +30,7 @@ block content //Embedding socketUrl if socketUrl script(type='text/javascript'). - socketUrl = !{socketUrl} + socketUrl = "!{socketUrl}" //Socket.io Client Dependency script(src='https://cdn.socket.io/socket.io-1.4.5.js') diff --git a/config/express.js b/config/express.js index 2b44e8f5..a5be442c 100755 --- a/config/express.js +++ b/config/express.js @@ -36,6 +36,18 @@ var configureSocketIO = function (app, db) { return server; }; +var supportedLanguages = ['en', 'de', 'fr', 'it', 'es']; + +function containsAnySupportedLanguages(preferredLanguages){ + for (var i = 0; i < preferredLanguages.length; i++) { + var currIndex = supportedLanguages.indexOf(preferredLanguages[i]); + if (currIndex > -1) { + return supportedLanguages[currIndex]; + } + } + return null; +} + module.exports = function(db) { // Initialize express app var app = express(); @@ -153,21 +165,6 @@ module.exports = function(db) { } }); - //Setup i18n - i18n.configure({ - directory: __dirname + '/locales', - defaultLocale: 'en' - }); - - app.use(function(req, res, next) { - // express helper for natively supported engines - res.locals.__ = res.__ = function() { - return i18n.__.apply(req, arguments); - }; - - next(); - }); - //Setup Prerender.io app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN)); @@ -216,6 +213,7 @@ module.exports = function(db) { extended: true, limit: '100mb' })); + app.use(bodyParser.json({ limit: '100mb' })); app.use(methodOverride()); @@ -236,7 +234,6 @@ module.exports = function(db) { app.use(cookieParser()); // Express MongoDB session storage - app.use(session({ saveUninitialized: true, resave: true, @@ -253,14 +250,39 @@ module.exports = function(db) { app.use(passport.initialize()); app.use(passport.session()); + //Setup i18n + i18n.configure({ + locales: supportedLanguages, + directory: __dirname + '/locales', + defaultLocale: 'en', + cookie: 'userLang' + }); + + app.use(i18n.init); + + //Visitor Language Detection + app.use(function(req, res, next) { + var acceptLanguage = req.headers['accept-language']; + var languages = acceptLanguage.match(/[a-z]{2}(?!-)/g) || []; + + var supportedLanguage = containsAnySupportedLanguages(languages); + if(!req.user && supportedLanguage !== null){ + var currLanguage = res.cookie('userLang'); + + if(currLanguage && currLanguage !== supportedLanguage || !currLanguage){ + res.clearCookie('userLang'); + res.cookie('userLang', supportedLanguage, { maxAge: 90000, httpOnly: true }); + } + } + next(); + }); + // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); - // Add headers for Sentry - app.use(function (req, res, next) { // Website you wish to allow to connect diff --git a/config/locales/de.json b/config/locales/de.json index d00088e6..1cb88cf5 100644 --- a/config/locales/de.json +++ b/config/locales/de.json @@ -7,7 +7,11 @@ "VERIFICATION_EMAIL_PARAGRAPH_1": "Willkommen bei TellForm! Hier ist ein spezieller Link um deinen neuen Account zu aktivieren:", "VERIFICATION_EMAIL_LINK_TEXT": "Mein Konto aktivieren", "VERIFICATION_EMAIL_PARAGRAPH_2": "Vielen Dank für die Nutzung unserer Dienste! Wenn Sie Fragen oder Anregungen haben, senden Sie uns bitte eine E-Mail an", + "VERIFICATION_EMAIL_SUBJECT": "Aktiviere dein neues TellForm-Konto!", + "VERIFICATION_EMAIL_TEXT": "Bitte bestätigen Sie Ihren Account, indem Sie auf den folgenden Link klicken oder ihn in Ihren Browser kopieren und einfügen: $ {URL}", "EMAIL_SIGNATURE": "- Das TellForm-Team", "WELCOME_EMAIL_PARAGRAPH_1": "Wir möchten Sie als unser neustes Mitglied begrüßen!", - "WELCOME_EMAIL_PARAGRAPH_2": "Wir wünschen Ihnen viel Spaß mit TellForm! Wenn Sie Probleme haben, senden Sie uns bitte eine E-Mail an" + "WELCOME_EMAIL_PARAGRAPH_2": "Wir wünschen Ihnen viel Spaß mit TellForm! Wenn Sie Probleme haben, senden Sie uns bitte eine E-Mail an", + "WELCOME_EMAIL_SUBJECT": "Willkommen bei %s!", + "WELCOME_EMAIL_TEXT": "Ihr Konto wurde erfolgreich verifiziert." } \ No newline at end of file diff --git a/config/locales/es.json b/config/locales/es.json index 902b23e3..f05a79cc 100644 --- a/config/locales/es.json +++ b/config/locales/es.json @@ -7,7 +7,11 @@ "VERIFICATION_EMAIL_PARAGRAPH_1": "Bienvenido a TellForm. Aquí hay un enlace especial para activar su nueva cuenta:", "VERIFICATION_EMAIL_LINK_TEXT": "Activar mi cuenta", "VERIFICATION_EMAIL_PARAGRAPH_2": "¡Muchas gracias por utilizar nuestros servicios! Si tiene alguna pregunta o sugerencia, no dude en enviarnos un correo electrónico aquí", + "VERIFICATION_EMAIL_SUBJECT": "¡Active su nueva cuenta TellForm!", + "VERIFICATION_EMAIL_TEXT": "Verifique su cuenta haciendo clic en el siguiente enlace, o copiándolo y pegándolo en su navegador: $ {URL}", "EMAIL_SIGNATURE": "- El equipo de TellForm", "WELCOME_EMAIL_PARAGRAPH_1": "¡Nos gustaría darle la bienvenida como nuestro miembro más nuevo!", - "WELCOME_EMAIL_PARAGRAPH_2": "Esperamos que disfrute utilizando TellForm. Si tiene algún problema, no dude en enviarnos un correo electrónico aquí" + "WELCOME_EMAIL_PARAGRAPH_2": "Esperamos que disfrute utilizando TellForm. Si tiene algún problema, no dude en enviarnos un correo electrónico aquí", + "WELCOME_EMAIL_SUBJECT": "¡Bienvenido a %s!", + "WELCOME_EMAIL_TEXT": "Su cuenta ha sido verificada con éxito" } \ No newline at end of file diff --git a/config/locales/fr.json b/config/locales/fr.json index 5a890ca1..ff277576 100644 --- a/config/locales/fr.json +++ b/config/locales/fr.json @@ -7,7 +7,11 @@ "VERIFICATION_EMAIL_PARAGRAPH_1": "Bienvenue sur TellForm! Voici un lien spécial pour activer votre nouveau compte:", "VERIFICATION_EMAIL_LINK_TEXT": "Activer mon compte", "VERIFICATION_EMAIL_PARAGRAPH_2": "Merci beaucoup pour l'utilisation de nos services! Si vous avez des questions ou des suggestions, n'hésitez pas à nous envoyer un courriel ici", + "VERIFICATION_EMAIL_SUBJECT": "¡Active su nueva cuenta TellForm!", + "VERIFICATION_EMAIL_TEXT": "Verifique su cuenta haciendo clic en el siguiente enlace, o copiándolo y pegándolo en su navegador: $ {URL}", "EMAIL_SIGNATURE": "- L'équipe TellForm", "WELCOME_EMAIL_PARAGRAPH_1": "Nous aimerions vous accueillir en tant que nouveau membre!", - "WELCOME_EMAIL_PARAGRAPH_2": "Nous espérons que vous apprécierez l'utilisation de TellForm! Si vous avez des problèmes, n'hésitez pas à nous envoyer un e-mail ici" + "WELCOME_EMAIL_PARAGRAPH_2": "Nous espérons que vous apprécierez l'utilisation de TellForm! Si vous avez des problèmes, n'hésitez pas à nous envoyer un e-mail ici", + "WELCOME_EMAIL_SUBJECT": "Bienvenue dans %s!", + "WELCOME_EMAIL_TEXT": "Votre compte a été vérifié avec succès." } \ No newline at end of file diff --git a/config/locales/it.json b/config/locales/it.json index 46fc9db1..7840a21d 100644 --- a/config/locales/it.json +++ b/config/locales/it.json @@ -7,7 +7,11 @@ "VERIFICATION_EMAIL_PARAGRAPH_1": "Benvenuti a TellForm! Ecco un collegamento speciale per attivare il tuo nuovo account:", "VERIFICATION_EMAIL_LINK_TEXT": "Attiva il mio account", "VERIFICATION_EMAIL_PARAGRAPH_2": "Grazie mille per l'utilizzo dei nostri servizi! Se hai domande o suggerimenti, non esitate a contattarci via", + "VERIFICATION_EMAIL_SUBJECT": "Attiva il tuo nuovo account TellForm", + "VERIFICATION_EMAIL_TEXT": "Verifica il tuo account facendo clic sul seguente collegamento o copiandolo e incollandolo nel tuo browser: $ {URL}", "EMAIL_SIGNATURE": "- Il team TellForm", "WELCOME_EMAIL_PARAGRAPH_1": "Vorremmo darVi il benvenuto come il nostro nuovo membro!", - "WELCOME_EMAIL_PARAGRAPH_2": "Speriamo che ti piace usare TellForm! Se hai problemi, non esitate a contattarci via" + "WELCOME_EMAIL_PARAGRAPH_2": "Speriamo che ti piace usare TellForm! Se hai problemi, non esitate a contattarci via", + "WELCOME_EMAIL_SUBJECT": "Benvenuto a %s!", + "WELCOME_EMAIL_TEXT": "Il tuo account è stato verificato correttamente." } \ No newline at end of file diff --git a/public/modules/users/config/i18n/german.js b/public/modules/users/config/i18n/german.js index d4d5f144..5696d053 100644 --- a/public/modules/users/config/i18n/german.js +++ b/public/modules/users/config/i18n/german.js @@ -16,9 +16,9 @@ angular.module('users').config(['$translateProvider', function ($translateProvid LANGUAGE_LABEL: 'Sprache', EMAIL_LABEL: 'Email', - SIGNUP_ACCOUNT_LINK: 'Haben Sie kein Konto? Hier anmelden', + SIGNUP_ACCOUNT_LINK: 'Haben Sie kein Konto? Hier registrieren', SIGN_IN_ACCOUNT_LINK: 'Haben Sie bereits ein Konto? Hier anmelden', - SIGNUP_HEADER_TEXT: 'Anmelden', + SIGNUP_HEADER_TEXT: 'Registrieren', SIGNIN_HEADER_TEXT: 'Anmelden', SIGNUP_ERROR_TEXT: 'Konnte die Registrierung aufgrund von Fehlern nicht abschließen', diff --git a/public/modules/users/controllers/authentication.client.controller.js b/public/modules/users/controllers/authentication.client.controller.js index a677c15b..5d4f5a8f 100755 --- a/public/modules/users/controllers/authentication.client.controller.js +++ b/public/modules/users/controllers/authentication.client.controller.js @@ -1,7 +1,8 @@ 'use strict'; -angular.module('users').controller('AuthenticationController', ['$scope', '$location', '$state', '$rootScope', 'User', 'Auth', - function($scope, $location, $state, $rootScope, User, Auth) { +angular.module('users').controller('AuthenticationController', ['$scope', '$location', '$state', '$rootScope', 'User', 'Auth', '$translate', '$window', + function($scope, $location, $state, $rootScope, User, Auth, $translate, $window) { + $translate.use($window.locale); $scope = $rootScope; $scope.credentials = {}; diff --git a/public/modules/users/controllers/password.client.controller.js b/public/modules/users/controllers/password.client.controller.js index b14343d0..1df72fe7 100755 --- a/public/modules/users/controllers/password.client.controller.js +++ b/public/modules/users/controllers/password.client.controller.js @@ -1,7 +1,8 @@ 'use strict'; -angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User', - function($scope, $stateParams, $state, User) { +angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User', '$translate', '$window', + function($scope, $stateParams, $state, User, $translate, $window) { + $translate.use($window.locale); $scope.error = ''; diff --git a/public/modules/users/controllers/verify.client.controller.js b/public/modules/users/controllers/verify.client.controller.js index c7b6053d..0a865209 100644 --- a/public/modules/users/controllers/verify.client.controller.js +++ b/public/modules/users/controllers/verify.client.controller.js @@ -1,7 +1,8 @@ 'use strict'; -angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams', - function($scope, $state, $rootScope, User, Auth, $stateParams) { +angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams', '$translate', '$window', + function($scope, $state, $rootScope, User, Auth, $stateParams, $translate, $window) { + $translate.use($window.locale); $scope.isResetSent = false; $scope.credentials = {};