project structure and namespaces

This commit is contained in:
Stoyan Zlatev
2023-06-19 15:43:55 +02:00
parent 2624dd7c87
commit 5446342fbd
198 changed files with 310 additions and 528 deletions
@@ -0,0 +1,30 @@
namespace LaaProduction.Web.App_Infrastructure
{
using LaaProduction.Personalization;
using System.Web.Mvc;
using ClaimsPrincipal = System.Security.Claims.ClaimsPrincipal;
public class AllowedRolesAttribute : AuthorizeAttribute
{
public AllowedRolesAttribute(params string[] roles)
=> this.Roles = string.Join(",", roles);
public AllowedRolesAttribute(params UsersRoles[] roles)
=> this.Roles = string.Join(",", roles);
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User is ClaimsPrincipal claimsPrincipal)
{
filterContext.Controller.TempData["Unauthorized"] = "Dir fehlen berechtigungen.";
filterContext.Result = new RedirectResult("~/");
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
}
@@ -0,0 +1,18 @@
namespace LaaProduction.Web.App_Infrastructure
{
using System.Configuration;
public class Appsettings
{
public static string APIURL
#if DEBUG
=> ConfigurationManager.AppSettings.Get("Localhost");
#else
=> ConfigurationManager.AppSettings.Get(nameof(APIURL));
#endif
public static string ConnectionString => ConfigurationManager.AppSettings.Get(nameof(ConnectionString));
public static int LoginTimeout => int.TryParse(ConfigurationManager.AppSettings.Get(nameof(LoginTimeout)), out int time) ? time : 0;
}
}
@@ -0,0 +1,23 @@
namespace LaaProduction.Web.App_Infrastructure
{
using LaaProduction.Personalization.Interfaces;
using IAuthorizationFilter = System.Web.Mvc.IAuthorizationFilter;
using AuthorizationContext = System.Web.Mvc.AuthorizationContext;
public class AuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var httpContext = filterContext.HttpContext;
var sessionUser = httpContext.GetSessionUser();
var accountManagement = ServiceProvider.GetService<IAccountManager>();
httpContext.User = accountManagement.GetClaimsPrincipal(sessionUser);
if (httpContext.User.Identity.IsAuthenticated)
{
httpContext.SetUrlReferer();
}
}
}
}
@@ -0,0 +1,24 @@
namespace LaaProduction.Web.App_Infrastructure
{
using LaaProduction.Personalization.Interfaces;
using System.Web.Http;
using System.Web.Http.Controllers;
public class AuthorizeBearerAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization?.Scheme == "Bearer")
{
var accountManager = ServiceProvider.GetService<IAccountManager>();
var bearer = actionContext.Request.Headers.Authorization.Parameter;
var principal = accountManager.GetClaimsPrincipal(bearer);
return principal.Identity.IsAuthenticated;
}
return false;
}
}
}
@@ -0,0 +1,12 @@
namespace LaaProduction.Web.App_Infrastructure
{
using System.Web.Mvc;
public class ExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.Result = new RedirectResult("/");
}
}
}
@@ -0,0 +1,207 @@
namespace LaaProduction.Web.App_Infrastructure
{
using LaaProductionHttp.Interfaces;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
/// <summary>
/// Static class with extension methods that run on controller contexts.
/// </summary>
public static class HttpExtensions
{
const string ORDER_DATA = nameof(ORDER_DATA);
const string URL_REFERER = nameof(URL_REFERER);
const string LAA_USER = nameof(LAA_USER);
public static TDST Map<TSRC, TDST>(this TSRC model, Func<TSRC, TDST> mapper)
where TDST : class
where TSRC : class
{
if (model is null)
{
return default(TDST);
}
return mapper(model);
}
public static bool IsInRole<T>(this IPrincipal principal, T role)
=> principal.IsInRole($"{role}");
public static string GetNameIdentifier(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal
.FindFirst(ClaimTypes.NameIdentifier)
?.Value;
}
return default(string);
}
public static string FullName(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal
.FindAll(nameof(FullName))
.LastOrDefault()?.Value;
}
return "<unknown>";
}
public static string ClaimId(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal
.FindAll(ClaimTypes.NameIdentifier)
.LastOrDefault()?.Value;
}
return "<unknown>";
}
public static string GetUrlReferer(this HttpContextBase httpContext)
=> httpContext
.Request
.Cookies
.Get(URL_REFERER)
?.Value ?? "~/";
public static void SetUrlReferer(this HttpContextBase httpContext)
=> httpContext
.Response
.Cookies
.Add(new HttpCookie(URL_REFERER, $"{httpContext.Request.Url}"));
public static void SetUserData(this HttpContextBase httpContext, object data)
{
if (data != null)
{
var userId = httpContext.User.ClaimId();
var json = JsonConvert.SerializeObject(data);
var encoded = WebUtility.UrlEncode(json);
var cookie = new HttpCookie($"{ORDER_DATA}_{userId}")
{
Value = encoded,
Expires = DateTime.Now.AddHours(7)
};
httpContext.Response.Cookies.Set(cookie);
}
}
public static T GetUserData<T>(this HttpContextBase httpContext)
{
var userId = httpContext.User.ClaimId();
var cookie = httpContext.Request.Cookies.Get($"{ORDER_DATA}_{userId}");
if (cookie != null && cookie.Value != null)
{
try
{
var json = WebUtility.UrlDecode(cookie.Value);
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return default(T);
}
public static string GetSessionUser(this HttpContextBase httpContext)
{
var requestCookies = httpContext.Request.Cookies;
var sessionUser = requestCookies.Get(LAA_USER);
if (sessionUser is null)
{
sessionUser = new HttpCookie(LAA_USER, string.Empty);
requestCookies.Add(sessionUser);
}
sessionUser.Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout);
requestCookies.Set(sessionUser);
return sessionUser.Value;
}
public static void SignIn(this HttpContextBase httpContext, string sessionUser)
{
httpContext.SignOut();
httpContext.Response.AppendCookie(new HttpCookie(LAA_USER, sessionUser)
{
Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout)
});
}
public static void SignOut(this HttpContextBase httpContext)
{
httpContext.Request.Cookies.Remove(LAA_USER);
httpContext.Response.Cookies.Remove(LAA_USER);
}
public static string ComputeHash(this string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
var bytes = Encoding.UTF8.GetBytes(value);
var hash = SHA256.Create().ComputeHash(bytes);
var base64 = Convert.ToBase64String(hash);
return base64;
}
return value;
}
public static void AddModelErrors(this ModelStateDictionary modelState, IHttpErrorResponse response)
{
if (response != null)
{
if (response.Errors != null)
{
foreach (var error in response.Errors)
{
modelState.AddModelError(error.Key, error.Value);
}
}
if (!string.IsNullOrWhiteSpace(response.Message))
{
modelState.AddModelError(nameof(response.Message), response.Message);
}
}
}
public static short GetAppId(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
if (short.TryParse($"{claimsPrincipal.FindFirst("AppId")?.Value}", out short appId))
{
return appId;
}
}
return default(short);
}
}
}
@@ -0,0 +1,41 @@
namespace LaaProduction.Web.App_Infrastructure
{
using Newtonsoft.Json;
using System.Linq;
using System.Web.Mvc;
public class RouteParameterAttribute : ActionFilterAttribute
{
private readonly string parameterName;
public RouteParameterAttribute(string parameterName)
=> this.parameterName = parameterName;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (filterContext.ActionParameters.ContainsKey(this.parameterName))
{
var parameter = filterContext
.ActionDescriptor
.GetParameters()
.FirstOrDefault();
var parameterValue = parameter.DefaultValue;
try
{
var routeValue = filterContext
.RouteData
.GetRequiredString("id");
parameterValue = JsonConvert.DeserializeObject(routeValue, parameter.ParameterType);
}
catch { }
filterContext.ActionParameters[this.parameterName] = parameterValue;
}
}
}
}
@@ -0,0 +1,39 @@
namespace LaaProduction
{
using LaaProduction.Personalization;
using LaaProduction.Search;
using LaaProductionHttp;
using LaaProductionSQL;
using LaaProduction.Web.App_Infrastructure;
using LaaProduction.Services;
using LaaProduction.Services.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using System;
public class ServiceProvider
{
private static IServiceProvider serviceProvider;
public static T GetService<T>() where T : class
=> serviceProvider.GetService<T>();
public static void RegisterServices()
=> serviceProvider = new ServiceCollection()
.AddSingleton(_ => SQLConnection.CreateConnection(Appsettings.ConnectionString))
.AddSingleton(_ => HttpClient.CreateHttpClient(Appsettings.APIURL))
.AddAdministration(Appsettings.ConnectionString)
.AddSearching(Appsettings.ConnectionString)
.AddScoped<IAccountService, AccountService>()
.AddScoped<IApprovalsService, ApprovalsService>()
.AddScoped<ILoggerService, LoggerService>()
.AddScoped<IOrdersService, OrdersService>()
.AddScoped<IProtocolService, ProtocolService>()
.AddScoped<IReportService, ReportService>()
.AddScoped<ISearchService, SearchService>()
.AddScoped<IShipmentsService, ShipmentsService>()
.AddScoped<ISoftwareService, SoftwareService>()
.BuildServiceProvider();
}
}