53 lines
2.2 KiB
C#
53 lines
2.2 KiB
C#
using System.Linq;
|
|
using gehGassi.Core.Interfaces;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace gehGassi.Web.Helper
|
|
{
|
|
/// <summary>
|
|
/// Attribut das die Lokalisierung einer URL durchführt.
|
|
/// Wenn keine Sprache angegeben ist, wird die des Benutzers eingestellt
|
|
/// </summary>
|
|
public class LocalizeAttribute : AuthorizeAttribute, IAuthorizationFilter
|
|
{
|
|
public LocalizeAttribute()
|
|
{
|
|
|
|
}
|
|
|
|
public void OnAuthorization(AuthorizationFilterContext context)
|
|
{
|
|
if (context.HttpContext.User.Identity.IsAuthenticated)
|
|
{
|
|
var userService = context.HttpContext.RequestServices.GetService<IUserService>();
|
|
var locOptions = context.HttpContext.RequestServices.GetService<IOptions<RequestLocalizationOptions>>();
|
|
var path = context.HttpContext.Request.Path.Value;
|
|
if (path.ToLower().Contains("globalize"))
|
|
return;
|
|
if (path.Length > 1)
|
|
{
|
|
if (locOptions.Value.SupportedCultures.Any(valueSupportedCulture => path.Contains($"/{valueSupportedCulture.TwoLetterISOLanguageName}/")))
|
|
{
|
|
return;
|
|
}
|
|
else if (locOptions.Value.SupportedCultures.Any(valueSupportedCulture => path.EndsWith($"/{valueSupportedCulture.TwoLetterISOLanguageName}")))
|
|
return;
|
|
var user = userService.GetByUsernameAsync(context.HttpContext.User.Identity.Name).Result;
|
|
context.Result = new LocalRedirectResult($"/{user.PreferredLanguage}{path}");
|
|
}
|
|
else
|
|
{
|
|
//ROOT Aufruf. Sprache des Benutzers holen und redirect
|
|
var user = userService.GetByUsernameAsync(context.HttpContext.User.Identity.Name).Result;
|
|
context.Result = new LocalRedirectResult($"/{user.PreferredLanguage}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|