Fix custom email templates usage and add translation support for magic session keys

This commit is contained in:
Harsh Mahajan committed 2026-02-03 17:56:02 +05:30
1 parent def3ce056f
commit ae392fe9a5
5 files changed
+315 -33

No files matched your search

+3
View File
@@ -22,6 +22,9 @@
"emails.magicSession.securityPhrase": "Security phrase for this email is {{b}}{{phrase}}{{/b}}. You can trust this email if this phrase matches the phrase shown during sign in.",
"emails.magicSession.thanks": "Thanks,",
"emails.magicSession.signature": "{{project}} team",
"emails.magicsession.body": "Click the button below to securely sign in to your {{b}}{{project}}{{/b}} account. This link will expire in 1 hour.",
"emails.magicsession.footer": "If you are unable to sign in using the button above, please visit the following link:",
"emails.magicsession.clientInfo": "This sign in was requested using {{b}}{{agentClient}}{{/b}} on {{b}}{{agentDevice}}{{/b}} {{b}}{{agentOs}}{{/b}}. If you didn't request the sign in, you can safely ignore this email.",
"emails.sessionAlert.subject": "Security alert: new session on your {{project}} account",
"emails.sessionAlert.preview": "New login detected on {{project}} at {{time}} UTC.",
"emails.sessionAlert.hello": "Hello {{user}},",
+118 -22
View File
@@ -75,11 +75,97 @@ use Utopia\Validator\WhiteList;
$oauthDefaultSuccess = '/console/auth/oauth2/success';
$oauthDefaultFailure = '/console/auth/oauth2/failure';
if (!function_exists('getCustomTemplate')) {
function getCustomTemplate(Document $project, string $type, Locale $locale, string $prefix = 'email'): array
{
$templates = $project->getAttribute('templates', []);
$templateKey = $prefix . '.' . $type . '-' . $locale->default;
if (!empty($templates[$templateKey])) {
return $templates[$templateKey];
}
$templateLowerKey = $prefix . '.' . strtolower($type) . '-' . $locale->default;
return $templates[$templateLowerKey] ?? [];
}
}
if (!function_exists('normalizeEmailLocaleKey')) {
function normalizeEmailLocaleKey(string $key): string
{
if (!str_starts_with($key, 'emails.')) {
return $key;
}
$parts = explode('.', $key);
if (count($parts) < 3) {
return $key;
}
$type = strtolower($parts[1]);
$typeMap = [
'magicsession' => 'magicSession',
'otpsession' => 'otpSession',
'mfachallenge' => 'mfaChallenge',
'sessionalert' => 'sessionAlert',
];
if (isset($typeMap[$type])) {
$parts[1] = $typeMap[$type];
if (isset($parts[2]) && $type === 'magicsession') {
$fieldMap = [
'body' => 'optionButton',
'footer' => 'optionUrl',
];
$field = strtolower($parts[2]);
if (isset($fieldMap[$field])) {
$parts[2] = $fieldMap[$field];
}
}
return implode('.', $parts);
}
return $key;
}
}
if (!function_exists('translateEmailTemplate')) {
function translateEmailTemplate(string $content, Locale $locale): string
{
return preg_replace_callback('/\{\{\s*(emails\.[^}]+)\s*\}\}/i', function ($matches) use ($locale) {
$missing = '__missing_translation__';
$rawKey = trim($matches[1]);
$keyLower = strtolower($rawKey);
$candidates = [];
$candidates[] = normalizeEmailLocaleKey($rawKey);
if ($keyLower === 'emails.magicsession.body' || $keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.' . ($keyLower === 'emails.magicsession.body' ? 'optionButton' : 'optionUrl');
}
if ($keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.clientInfo';
}
foreach ($candidates as $key) {
$value = $locale->getText($key, $missing);
if ($value !== $missing) {
return $value;
}
}
return $matches[0];
}, $content) ?? $content;
}
}
function sendSessionAlert(Locale $locale, Document $user, Document $project, array $platform, Document $session, Mail $queueForMails)
{
$subject = $locale->getText("emails.sessionAlert.subject");
$preview = $locale->getText("emails.sessionAlert.preview");
$customTemplate = $project->getAttribute('templates', [])['email.sessionAlert-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'sessionAlert', $locale, 'email');
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
$validator = new FileName();
@@ -102,6 +188,11 @@ function sendSessionAlert(Locale $locale, Document $user, Document $project, arr
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -137,9 +228,6 @@ function sendSessionAlert(Locale $locale, Document $user, Document $project, arr
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -2206,7 +2294,7 @@ App::post('/v1/account/tokens/magic-url')
$subject = $locale->getText("emails.magicSession.subject");
$preview = $locale->getText("emails.magicSession.preview");
$customTemplate = $project->getAttribute('templates', [])['email.magicSession-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'magicSession', $locale, 'email');
$detector = new Detector($request->getUserAgent('UNKNOWN'));
$agentOs = $detector->getOS();
@@ -2231,6 +2319,11 @@ App::post('/v1/account/tokens/magic-url')
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -2267,9 +2360,6 @@ App::post('/v1/account/tokens/magic-url')
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -2487,7 +2577,7 @@ App::post('/v1/account/tokens/email')
$preview = $locale->getText("emails.otpSession.preview");
$heading = $locale->getText("emails.otpSession.heading");
$customTemplate = $project->getAttribute('templates', [])['email.otpSession-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'otpSession', $locale, 'email');
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
$validator = new FileName();
@@ -2518,6 +2608,11 @@ App::post('/v1/account/tokens/email')
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -2553,9 +2648,6 @@ App::post('/v1/account/tokens/email')
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -2876,7 +2968,7 @@ App::post('/v1/account/tokens/phone')
if ($sendSMS) {
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');
$customTemplate = $project->getAttribute('templates', [])['sms.login-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'login', $locale, 'sms');
if (!empty($customTemplate)) {
$message = $customTemplate['message'] ?? $message;
}
@@ -3606,7 +3698,7 @@ App::post('/v1/account/recovery')
$body = $locale->getText("emails.recovery.body");
$subject = $locale->getText("emails.recovery.subject");
$preview = $locale->getText("emails.recovery.preview");
$customTemplate = $project->getAttribute('templates', [])['email.recovery-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'recovery', $locale, 'email');
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-inner-base.tpl');
$message
@@ -3618,6 +3710,11 @@ App::post('/v1/account/recovery')
->setParam('{{signature}}', $locale->getText("emails.recovery.signature"));
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -3653,9 +3750,6 @@ App::post('/v1/account/recovery')
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -3913,7 +4007,7 @@ App::post('/v1/account/verifications/email')
$subject = $locale->getText("emails.verification.subject");
$heading = $locale->getText("emails.verification.heading");
$customTemplate = $project->getAttribute('templates', [])['email.verification-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'verification', $locale, 'email');
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
$validator = new FileName();
@@ -3934,6 +4028,11 @@ App::post('/v1/account/verifications/email')
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -3969,9 +4068,6 @@ App::post('/v1/account/verifications/email')
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -4212,7 +4308,7 @@ App::post('/v1/account/verifications/phone')
if ($sendSMS) {
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');
$customTemplate = $project->getAttribute('templates', [])['sms.verification-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'verification', $locale, 'sms');
if (!empty($customTemplate)) {
$message = $customTemplate['message'] ?? $message;
}
+14 -1
View File
@@ -2327,7 +2327,12 @@ App::get('/v1/projects/:projectId/templates/email/:type/:locale')
}
$templates = $project->getAttribute('templates', []);
$template = $templates['email.' . $type . '-' . $locale] ?? null;
$templateKey = 'email.' . $type . '-' . $locale;
$template = $templates[$templateKey] ?? null;
if (is_null($template)) {
$templateLowerKey = 'email.' . strtolower($type) . '-' . $locale;
$template = $templates[$templateLowerKey] ?? null;
}
$localeObj = new Locale($locale);
$localeObj->setFallback(System::getEnv('_APP_LOCALE', 'en'));
@@ -2497,6 +2502,14 @@ App::patch('/v1/projects/:projectId/templates/email/:type/:locale')
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$allowedTypes = Config::getParam('locale-templates')['email'] ?? [];
foreach ($allowedTypes as $allowedType) {
if (strcasecmp($allowedType, $type) === 0) {
$type = $allowedType;
break;
}
}
$templates = $project->getAttribute('templates', []);
$templates['email.' . $type . '-' . $locale] = [
'senderName' => $senderName,
+93 -5
View File
@@ -60,6 +60,92 @@ use Utopia\Validator\Boolean;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
if (!function_exists('getCustomTemplate')) {
function getCustomTemplate(Document $project, string $type, Locale $locale, string $prefix = 'email'): array
{
$templates = $project->getAttribute('templates', []);
$templateKey = $prefix . '.' . $type . '-' . $locale->default;
if (!empty($templates[$templateKey])) {
return $templates[$templateKey];
}
$templateLowerKey = $prefix . '.' . strtolower($type) . '-' . $locale->default;
return $templates[$templateLowerKey] ?? [];
}
}
if (!function_exists('normalizeEmailLocaleKey')) {
function normalizeEmailLocaleKey(string $key): string
{
if (!str_starts_with($key, 'emails.')) {
return $key;
}
$parts = explode('.', $key);
if (count($parts) < 3) {
return $key;
}
$type = strtolower($parts[1]);
$typeMap = [
'magicsession' => 'magicSession',
'otpsession' => 'otpSession',
'mfachallenge' => 'mfaChallenge',
'sessionalert' => 'sessionAlert',
];
if (isset($typeMap[$type])) {
$parts[1] = $typeMap[$type];
if (isset($parts[2]) && $type === 'magicsession') {
$fieldMap = [
'body' => 'optionButton',
'footer' => 'optionUrl',
];
$field = strtolower($parts[2]);
if (isset($fieldMap[$field])) {
$parts[2] = $fieldMap[$field];
}
}
return implode('.', $parts);
}
return $key;
}
}
if (!function_exists('translateEmailTemplate')) {
function translateEmailTemplate(string $content, Locale $locale): string
{
return preg_replace_callback('/\{\{\s*(emails\.[^}]+)\s*\}\}/i', function ($matches) use ($locale) {
$missing = '__missing_translation__';
$rawKey = trim($matches[1]);
$keyLower = strtolower($rawKey);
$candidates = [];
$candidates[] = normalizeEmailLocaleKey($rawKey);
if ($keyLower === 'emails.magicsession.body' || $keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.' . ($keyLower === 'emails.magicsession.body' ? 'optionButton' : 'optionUrl');
}
if ($keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.clientInfo';
}
foreach ($candidates as $key) {
$value = $locale->getText($key, $missing);
if ($value !== $missing) {
return $value;
}
}
return $matches[0];
}, $content) ?? $content;
}
}
App::post('/v1/teams')
->desc('Create team')
->groups(['api', 'teams'])
@@ -705,7 +791,7 @@ App::post('/v1/teams/:teamId/memberships')
$body = $locale->getText("emails.invitation.body");
$preview = $locale->getText("emails.invitation.preview");
$subject = $locale->getText("emails.invitation.subject");
$customTemplate = $project->getAttribute('templates', [])['email.invitation-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'invitation', $locale, 'email');
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-inner-base.tpl');
$message
@@ -717,6 +803,11 @@ App::post('/v1/teams/:teamId/memberships')
->setParam('{{signature}}', $locale->getText("emails.invitation.signature"));
$body = $message->render();
if (!empty($customTemplate)) {
$body = translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -752,9 +843,6 @@ App::post('/v1/teams/:teamId/memberships')
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails
@@ -788,7 +876,7 @@ App::post('/v1/teams/:teamId/memberships')
$message = Template::fromFile(__DIR__ . '/../../config/locale/templates/sms-base.tpl');
$customTemplate = $project->getAttribute('templates', [])['sms.invitation-' . $locale->default] ?? [];
$customTemplate = getCustomTemplate($project, 'invitation', $locale, 'sms');
if (!empty($customTemplate)) {
$message = $customTemplate['message'];
}
@@ -42,6 +42,86 @@ class Create extends Action
return 'createMFAChallenge';
}
protected function getCustomTemplate(Document $project, string $type, Locale $locale, string $prefix = 'email'): array
{
$templates = $project->getAttribute('templates', []);
$templateKey = $prefix . '.' . $type . '-' . $locale->default;
if (!empty($templates[$templateKey])) {
return $templates[$templateKey];
}
$templateLowerKey = $prefix . '.' . strtolower($type) . '-' . $locale->default;
return $templates[$templateLowerKey] ?? [];
}
protected function normalizeEmailLocaleKey(string $key): string
{
if (!str_starts_with($key, 'emails.')) {
return $key;
}
$parts = explode('.', $key);
if (count($parts) < 3) {
return $key;
}
$type = strtolower($parts[1]);
$typeMap = [
'magicsession' => 'magicSession',
'otpsession' => 'otpSession',
'mfachallenge' => 'mfaChallenge',
'sessionalert' => 'sessionAlert',
];
if (isset($typeMap[$type])) {
$parts[1] = $typeMap[$type];
if (isset($parts[2]) && $type === 'magicsession') {
$fieldMap = [
'body' => 'optionButton',
'footer' => 'optionUrl',
];
$field = strtolower($parts[2]);
if (isset($fieldMap[$field])) {
$parts[2] = $fieldMap[$field];
}
}
return implode('.', $parts);
}
return $key;
}
protected function translateEmailTemplate(string $content, Locale $locale): string
{
return preg_replace_callback('/\{\{\s*(emails\.[^}]+)\s*\}\}/i', function ($matches) use ($locale) {
$missing = '__missing_translation__';
$rawKey = trim($matches[1]);
$keyLower = strtolower($rawKey);
$candidates = [];
$candidates[] = $this->normalizeEmailLocaleKey($rawKey);
if ($keyLower === 'emails.magicsession.body' || $keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.' . ($keyLower === 'emails.magicsession.body' ? 'optionButton' : 'optionUrl');
}
if ($keyLower === 'emails.magicsession.footer') {
$candidates[] = 'emails.magicSession.clientInfo';
}
foreach ($candidates as $key) {
$value = $locale->getText($key, $missing);
if ($value !== $missing) {
return $value;
}
}
return $matches[0];
}, $content) ?? $content;
}
public function __construct()
{
$this
@@ -170,7 +250,7 @@ class Create extends Action
$message = Template::fromFile($templatesPath . '/sms-base.tpl');
$customTemplate = $project->getAttribute('templates', [])['sms.mfaChallenge-' . $locale->default] ?? [];
$customTemplate = $this->getCustomTemplate($project, 'mfaChallenge', $locale, 'sms');
if (!empty($customTemplate)) {
$message = $customTemplate['message'] ?? $message;
}
@@ -227,7 +307,7 @@ class Create extends Action
$preview = $locale->getText("emails.mfaChallenge.preview");
$heading = $locale->getText("emails.mfaChallenge.heading");
$customTemplate = $project->getAttribute('templates', [])['email.mfaChallenge-' . $locale->default] ?? [];
$customTemplate = $this->getCustomTemplate($project, 'mfaChallenge', $locale, 'email');
$smtpBaseTemplate = $project->getAttribute('smtpBaseTemplate', 'email-base');
$validator = new FileName();
@@ -252,6 +332,11 @@ class Create extends Action
$body = $message->render();
if (!empty($customTemplate)) {
$body = $this->translateEmailTemplate($customTemplate['message'] ?? $body, $locale);
$subject = $this->translateEmailTemplate($customTemplate['subject'] ?? $subject, $locale);
}
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
@@ -287,9 +372,6 @@ class Create extends Action
if (!empty($customTemplate['replyTo'])) {
$replyTo = $customTemplate['replyTo'];
}
$body = $customTemplate['message'] ?? '';
$subject = $customTemplate['subject'] ?? $subject;
}
$queueForMails