refactor(HomeController): remove culture binding as viewdata; bind via string localizer

This commit is contained in:
tekh 2025-08-23 00:14:43 +02:00
parent 0b33ba0fd8
commit d390802305
14 changed files with 190 additions and 153 deletions

View File

@ -1,82 +0,0 @@
namespace EnvelopeGenerator.Application;
/// <summary>
///
/// </summary>
public static class Key
{
/// <summary>
///
/// </summary>
public static readonly string InnerServiceError = nameof(InnerServiceError);
/// <summary>
///
/// </summary>
public static readonly string EnvelopeNotFound = nameof(EnvelopeNotFound);
/// <summary>
///
/// </summary>
public static readonly string EnvelopeReceiverNotFound = nameof(EnvelopeReceiverNotFound);
/// <summary>
///
/// </summary>
public static readonly string AccessCodeNull = nameof(AccessCodeNull);
/// <summary>
///
/// </summary>
public static readonly string WrongAccessCode = nameof(WrongAccessCode);
/// <summary>
///
/// </summary>
public static readonly string DataIntegrityIssue = nameof(DataIntegrityIssue);
/// <summary>
///
/// </summary>
public static readonly string SecurityBreachOrDataIntegrity = nameof(SecurityBreachOrDataIntegrity);
/// <summary>
///
/// </summary>
public static readonly string PossibleDataIntegrityIssue = nameof(PossibleDataIntegrityIssue);
/// <summary>
///
/// </summary>
public static readonly string SecurityBreach = nameof(SecurityBreach);
/// <summary>
///
/// </summary>
public static readonly string PossibleSecurityBreach = nameof(PossibleSecurityBreach);
/// <summary>
///
/// </summary>
public static readonly string WrongEnvelopeReceiverId = nameof(WrongEnvelopeReceiverId);
/// <summary>
///
/// </summary>
public static readonly string EnvelopeOrReceiverNonexists = nameof(EnvelopeOrReceiverNonexists);
/// <summary>
///
/// </summary>
public static readonly string PhoneNumberNonexists = nameof(PhoneNumberNonexists);
/// <summary>
///
/// </summary>
public static readonly string Default = nameof(Default);
/// <summary>
///
/// </summary>
public static readonly string DbMigrationTest = nameof(DbMigrationTest);
}

View File

@ -1,9 +1,137 @@
namespace EnvelopeGenerator.Application.Resources
using Microsoft.Extensions.Localization;
using System.Runtime.CompilerServices;
namespace EnvelopeGenerator.Application.Resources;
/// <summary>
/// The place holder class for Resource.*.resx
/// </summary>
public class Resource
{
}
//TODO: use code generator
/// <summary>
///
/// </summary>
public static class Extensions
{
/// <summary>
/// The place holder class for Resource.*.resx
///
/// </summary>
public class Resource
{
}
}
/// <param name="localizer"></param>
/// <returns></returns>
public static string InnerServiceError(this IStringLocalizer localizer) => localizer[nameof(InnerServiceError)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string EnvelopeNotFound(this IStringLocalizer localizer) => localizer[nameof(EnvelopeNotFound)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string EnvelopeReceiverNotFound(this IStringLocalizer localizer) => localizer[nameof(EnvelopeReceiverNotFound)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string AccessCodeNull(this IStringLocalizer localizer) => localizer[nameof(AccessCodeNull)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string WrongAccessCode(this IStringLocalizer localizer) => localizer[nameof(WrongAccessCode)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string DataIntegrityIssue(this IStringLocalizer localizer) => localizer[nameof(DataIntegrityIssue)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string SecurityBreachOrDataIntegrity(this IStringLocalizer localizer) => localizer[nameof(SecurityBreachOrDataIntegrity)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string PossibleDataIntegrityIssue(this IStringLocalizer localizer) => localizer[nameof(PossibleDataIntegrityIssue)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string SecurityBreach(this IStringLocalizer localizer) => localizer[nameof(SecurityBreach)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string PossibleSecurityBreach(this IStringLocalizer localizer) => localizer[nameof(PossibleSecurityBreach)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string WrongEnvelopeReceiverId(this IStringLocalizer localizer) => localizer[nameof(WrongEnvelopeReceiverId)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string EnvelopeOrReceiverNonexists(this IStringLocalizer localizer) => localizer[nameof(EnvelopeOrReceiverNonexists)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string PhoneNumberNonexists(this IStringLocalizer localizer) => localizer[nameof(PhoneNumberNonexists)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string Default(this IStringLocalizer localizer) => localizer[nameof(Default)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string DbMigrationTest(this IStringLocalizer localizer) => localizer[nameof(DbMigrationTest)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string Culture(this IStringLocalizer localizer) => localizer[nameof(Culture)];
/// <summary>
///
/// </summary>
/// <param name="localizer"></param>
/// <returns></returns>
public static string FiClass(this IStringLocalizer localizer) => localizer[nameof(FiClass)];
}

View File

@ -129,6 +129,9 @@
<data name="Confirmation" xml:space="preserve">
<value>Bestätigung</value>
</data>
<data name="Culture" xml:space="preserve">
<value>de-DE</value>
</data>
<data name="de-DE" xml:space="preserve">
<value>Deutch</value>
</data>
@ -150,6 +153,9 @@
<data name="EnvelopeInfo2" xml:space="preserve">
<value>Erstellt am {0} von {1}. Sie können den Absender über &lt;span class="highlight highlight-envelope-info-2"&gt;&lt;a class="mail-link" href="mailto:{2}?subject={3}&amp;body=Sehr%20geehrter%20{4}%20{5},%0A%0A%0A"&gt;{6}&lt;/a&gt;&lt;/span&gt; kontaktieren.</value>
</data>
<data name="FiClass" xml:space="preserve">
<value>fi-de</value>
</data>
<data name="Finalize" xml:space="preserve">
<value>Abschließen</value>
</data>

View File

@ -129,6 +129,9 @@
<data name="Confirmation" xml:space="preserve">
<value>Confirmation</value>
</data>
<data name="Culture" xml:space="preserve">
<value>en-US</value>
</data>
<data name="de-DE" xml:space="preserve">
<value>German</value>
</data>
@ -150,6 +153,9 @@
<data name="EnvelopeInfo2" xml:space="preserve">
<value>Created on {0} by {1}. You can contact the sender via &lt;span class="highlight highlight-envelope-info-2"&gt;&lt;a class="mail-link" href="mailto:{2}?subject={3}&amp;body=Dear%20{4}%20{5},%0A%0A%0A"&gt;{6}&lt;/a&gt;&lt;/span&gt;.</value>
</data>
<data name="FiClass" xml:space="preserve">
<value>fi-us</value>
</data>
<data name="Finalize" xml:space="preserve">
<value>Finalize</value>
</data>

View File

@ -36,7 +36,7 @@ public class EmailTemplateService : BasicCRUDService<IEmailTemplateRepository, E
var temp = await _repository.ReadByNameAsync(type);
return temp is null
? Result.Fail<EmailTemplateDto>()
.Message(Key.InnerServiceError)
.Message("InnerServiceError")
.Notice(LogLevel.Error, Flag.DataIntegrityIssue, $"EmailTemplateType '{type}' is not found in DB. Please, define required e-mail template.")
: Result.Success(_mapper.Map<EmailTemplateDto>(temp));
}

View File

@ -82,7 +82,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
var env_rcvs = await _repository.ReadByUuidAsync(uuid: uuid, withEnvelope: withEnvelope, withReceiver: withReceiver);
if( env_rcvs is null || !env_rcvs.Any())
return Result.Fail<IEnumerable<string?>>()
.Message(_localizer[Key.EnvelopeReceiverNotFound]);
.Message(_localizer.EnvelopeReceiverNotFound());
return Result.Success(env_rcvs.Select(er => er.AccessCode) ?? Enumerable.Empty<string?>());
}
@ -100,7 +100,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
var env_rcv = await _repository.ReadByUuidSignatureAsync(uuid: uuid, signature: signature, withEnvelope: withEnvelope, withReceiver: withReceiver, readOnly: readOnly);
if (env_rcv is null)
return Result.Fail<EnvelopeReceiverDto>()
.Message(Key.EnvelopeReceiverNotFound);
.Message("EnvelopeReceiverNotFound");
return Result.Success(_mapper.Map<EnvelopeReceiverDto>(env_rcv));
}
@ -119,7 +119,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
var env_rcv = await _repository.ReadByUuidSignatureAsync(uuid: uuid, signature: signature, withEnvelope: withEnvelope, withReceiver: withReceiver, readOnly: readOnly);
if (env_rcv is null)
return Result.Fail<EnvelopeReceiverSecretDto>()
.Message(Key.EnvelopeReceiverNotFound);
.Message("EnvelopeReceiverNotFound");
return Result.Success(_mapper.Map<EnvelopeReceiverSecretDto>(env_rcv));
}
@ -138,7 +138,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
if (uuid is null || signature is null)
return Result.Fail<EnvelopeReceiverDto>()
.Message(_localizer[Key.WrongEnvelopeReceiverId])
.Message(_localizer.WrongEnvelopeReceiverId())
.Notice(LogLevel.Warning, (uuid, signature).ToTitle())
.Notice(LogLevel.Warning, EnvelopeFlag.WrongEnvelopeReceiverId)
.Notice(LogLevel.Warning, Flag.PossibleSecurityBreach);
@ -159,7 +159,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
if (er is null)
return Result.Fail<bool>()
.Message(_localizer[Key.EnvelopeOrReceiverNonexists])
.Message(_localizer.EnvelopeOrReceiverNonexists())
.Notice(LogLevel.Warning, (uuid, signature).ToTitle())
.Notice(LogLevel.Warning, EnvelopeFlag.EnvelopeOrReceiverNonexists)
.Notice(LogLevel.Warning, Flag.PossibleDataIntegrityIssue);
@ -168,13 +168,13 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
if (actualAccessCode is null)
return Result.Fail<bool>()
.Message(_localizer[Key.AccessCodeNull])
.Message(_localizer.AccessCodeNull())
.Notice(LogLevel.Critical, (uuid, signature).ToTitle())
.Notice(LogLevel.Critical, EnvelopeFlag.AccessCodeNull)
.Notice(LogLevel.Critical, Flag.DataIntegrityIssue);
else if (accessCode != actualAccessCode)
return Result.Success(false).Message(_localizer[Key.WrongAccessCode]);
return Result.Success(false).Message(_localizer.WrongAccessCode());
else
return Result.Success(true);
}
@ -191,7 +191,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
if (uuid is null || signature is null)
return Result.Fail<bool>()
.Message(Key.WrongEnvelopeReceiverId)
.Message("WrongEnvelopeReceiverId")
.Notice(LogLevel.Critical, EnvelopeFlag.WrongEnvelopeReceiverId)
.Notice(LogLevel.Critical, Flag.SecurityBreach)
.Notice(LogLevel.Critical, "Attempt to verify access code detected. Such actions are generally not initiated by well-intentioned users. Potential security breach suspected. Immediate investigation required.");
@ -287,7 +287,7 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
if (uuid is null || signature is null)
return Result.Fail<SmsResponse>()
.Message(_localizer[Key.WrongEnvelopeReceiverId])
.Message(_localizer.WrongEnvelopeReceiverId())
.Notice(LogLevel.Warning, (uuid, signature).ToTitle())
.Notice(LogLevel.Warning, EnvelopeFlag.WrongEnvelopeReceiverId)
.Notice(LogLevel.Warning, Flag.PossibleSecurityBreach);
@ -295,11 +295,11 @@ public class EnvelopeReceiverService : BasicCRUDService<IEnvelopeReceiverReposit
var env_rcv = await _repository.ReadByUuidSignatureAsync(uuid: uuid, signature: signature, withEnvelope: false, withReceiver: false);
if (env_rcv is null)
return Result.Fail<SmsResponse>()
.Message(Key.EnvelopeReceiverNotFound);
.Message("EnvelopeReceiverNotFound");
if (env_rcv.PhoneNumber is null)
return Result.Fail<SmsResponse>()
.Message(Key.PhoneNumberNonexists)
.Message("PhoneNumberNonexists")
.Notice(LogLevel.Error, Flag.NotFound, $"An attempt was made to send sms to the user whose phone number is null. Envelope recipient ID is {envelopeReceiverId}, UUID is {uuid} and signature is {signature}.");
var res = await _smsSender.SendSmsAsync(recipient: env_rcv.PhoneNumber, message: message);

View File

@ -1,7 +1,8 @@
using EnvelopeGenerator.Application.Dto.EnvelopeReceiver;
using EnvelopeGenerator.Web.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
@ -55,6 +56,25 @@ namespace EnvelopeGenerator.Web.Controllers
}
#endregion
#region Cookie
public static string? GetCulture(this IRequestCookieCollection cookies)
=> cookies[CookieRequestCultureProvider.DefaultCookieName];
public static void SetCulture(this IResponseCookies cookies, string culture)
{
var cookieOptions = new CookieOptions
{
Secure = false,
SameSite = SameSiteMode.Strict,
HttpOnly = true
};
cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
cookieOptions);
}
#endregion
#region View error
//TODO: integrate localizer for ready-to-use views
//TODO: integrate to global exception handler middleware

View File

@ -58,8 +58,6 @@ public class HomeController : ViewControllerBase
[HttpGet("/")]
public IActionResult Main()
{
ViewData["UserCulture"] = _cultures[UserLanguage];
return View(new MainViewModel()
{
Title = _configuration["MainPageTitle"]
@ -118,8 +116,6 @@ public class HomeController : ViewControllerBase
{
try
{
ViewData["UserCulture"] = _cultures[UserLanguage];
return await _envRcvService.ReadByEnvelopeReceiverIdAsync(envelopeReceiverId: envelopeReceiverId).ThenAsync(
SuccessAsync: async er => {
if (User.IsInRole(ReceiverRole.FullyAuth))
@ -151,7 +147,6 @@ public class HomeController : ViewControllerBase
{
try
{
ViewData["UserCulture"] = _cultures[UserLanguage];
ViewData["EnvelopeKey"] = envelopeReceiverId;
envelopeReceiverId = _sanitizer.Sanitize(envelopeReceiverId);
@ -310,7 +305,6 @@ public class HomeController : ViewControllerBase
{
try
{
ViewData["UserCulture"] = _cultures[UserLanguage];
ViewData["EnvelopeKey"] = envelopeReceiverId;
envelopeReceiverId = _sanitizer.Sanitize(envelopeReceiverId);
@ -398,7 +392,6 @@ public class HomeController : ViewControllerBase
return base.Redirect($"/EnvelopeKey/{envelopeReceiverId}/Locked");
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
ViewData["UserCulture"] = _cultures[UserLanguage];
ViewData["EnvelopeKey"] = envelopeReceiverId;
return base.View();
}),
@ -428,8 +421,6 @@ public class HomeController : ViewControllerBase
return await _envRcvService.ReadByEnvelopeReceiverIdAsync(envelopeReceiverId).ThenAsync(
SuccessAsync: async (er) =>
{
ViewData["UserCulture"] = _cultures[UserLanguage];
ViewData["UserCulture"] = _cultures[UserLanguage];
return await _historyService.IsRejected(envelopeId: er.EnvelopeId)
? View(er)
: Redirect($"/EnvelopeKey/{envelopeReceiverId}/Locked");
@ -454,8 +445,6 @@ public class HomeController : ViewControllerBase
{
try
{
ViewData["UserCulture"] = _cultures[UserLanguage];
readOnlyKey = _sanitizer.Sanitize(readOnlyKey);
// check if the readOnlyId is valid
@ -530,26 +519,15 @@ public class HomeController : ViewControllerBase
return Ok(new { EnvelopeUuid = envelopeUuid, ReceiverSignature = receiverSignature });
}
[HttpPost("lang/{language}")]
public IActionResult SetLanguage([FromRoute] string language)
[HttpPost("lang/{culture}")]
public IActionResult SetLanguage([FromRoute] string culture)
{
try
{
language = _sanitizer.Sanitize(language);
if (!_cultures.Languages.Contains(language))
if (!_cultures.Languages.Contains(culture))
return BadRequest();
var cookieOptions = new CookieOptions()
{
Secure = false,
SameSite = SameSiteMode.Strict,
HttpOnly = true
};
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(language)),
cookieOptions);
Response.Cookies.SetCulture(culture);
return Redirect(Request.Headers["Referer"].ToString());
}
@ -563,7 +541,5 @@ public class HomeController : ViewControllerBase
[HttpGet("lang")]
public IActionResult GetLanguages() => Ok(_cultures.Languages);
private string? UserLanguage => Request.Cookies[CookieRequestCultureProvider.DefaultCookieName];
public IActionResult Error404() => this.ViewError404();
}

View File

@ -1,4 +1,5 @@
using EnvelopeGenerator.Web.Models;
using EnvelopeGenerator.Web.Controllers;
using EnvelopeGenerator.Web.Models;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Options;
using System.Globalization;
@ -23,20 +24,7 @@ public class CultureMiddleware
if (string.IsNullOrEmpty(cookieValue))
{
var culture = new RequestCulture(_cultures.Default.Language);
var cookieOptions = new CookieOptions
{
Secure = false,
SameSite = SameSiteMode.Strict,
HttpOnly = true
};
context.Response.Cookies.Append(
cookieName,
CookieRequestCultureProvider.MakeCookieValue(culture),
cookieOptions);
context.Response.Cookies.SetCulture(_cultures.Default.Language);
CultureInfo.CurrentCulture = new CultureInfo(_cultures.Default.Language);
CultureInfo.CurrentUICulture = new CultureInfo(_cultures.Default.Language);
}

View File

@ -90,7 +90,7 @@ try
//AddEF Core dbcontext
var useDbMigration = Environment.GetEnvironmentVariable("MIGRATION_TEST_MODE") == true.ToString() || config.GetValue<bool>("UseDbMigration");
var cnnStrName = useDbMigration ? Key.DbMigrationTest : Key.Default;
var cnnStrName = useDbMigration ? "DbMigrationTest" : "Default";
var connStr = config.GetConnectionString(cnnStrName)
?? throw new InvalidOperationException($"Connection string '{cnnStrName}' is missing in the application configuration.");

View File

@ -57,7 +57,7 @@ namespace EnvelopeGenerator.Web.Services
_logger = logger;
_logger.LogInformation("Establishing MSSQL Database connection..");
MSSQL = new MSSQLServer(logConfig, config.GetConnectionString(Key.Default));
MSSQL = new MSSQLServer(logConfig, config.GetConnectionString("Default"));
if (MSSQL.DBInitialized == true)
{

View File

@ -6,7 +6,6 @@
var nonce = _accessor.HttpContext?.Items["csp-nonce"] as string;
var cImg = _cImgOpt.Value;
ViewData["Title"] = _localizer[WebKey.DocProtected];
var userCulture = ViewData["UserCulture"] as Culture;
string codeType = ViewData["CodeType"] is string _codeType ? _codeType : "accessCode";
string codeKeyName = (char.ToUpper(codeType[0]) + codeType.Substring(1)).Replace("Code", "");
bool viaSms = codeType == "smsCode";

View File

@ -10,7 +10,6 @@
@using Newtonsoft.Json.Serialization
@model EnvelopeReceiverDto;
@{
var userCulture = ViewData["UserCulture"] as Culture;
var envelope = Model.Envelope;
var document = Model.Envelope?.Documents?.FirstOrDefault();
var sender = Model.Envelope?.User;

View File

@ -3,9 +3,6 @@
@using Newtonsoft.Json.Serialization
@{
var nonce = _accessor.HttpContext?.Items["csp-nonce"] as string;
var userCulture = ViewData["UserCulture"] as Culture;
//TODO: instead of default assignment add a middleware for culture
userCulture ??= _cultures.Default;
var isReadOnly = false;
if (ViewData["IsReadOnly"] is bool isReadOnly_bool)
isReadOnly = isReadOnly_bool;
@ -83,7 +80,7 @@
<span>&copy; SignFlow 2023-2024 <a href="https://digitaldata.works" target="_blank">Digital Data GmbH</a></span>
<div class="dropup flag-dropdown">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" id="langDropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fi @userCulture?.FIClass.TrySanitize(_sanitizer) me-2" id="selectedFlag"></span><span id="selectedLanguage"></span>
<span class="fi @_localizer.FiClass() me-2" id="selectedFlag"></span><span id="selectedLanguage"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="langDropdownMenuButton">
@foreach (var culture in _cultures)
@ -98,7 +95,7 @@
}
</ul>
</div>
<a href="/privacy-policy.@(userCulture?.Language).html" target="_blank">@_localizer[WebKey.Privacy]</a>
<a href="/privacy-policy.@(_localizer.Culture()).html" target="_blank">@_localizer[WebKey.Privacy]</a>
</footer>
</body>
</html>