From 844c81caa3760ee4b0093d8a2e346bce3d5c6f71 Mon Sep 17 00:00:00 2001 From: Stoyan Zlatev Date: Thu, 1 Jun 2023 13:08:05 +0200 Subject: [PATCH] runuable state --- .../CryptographyExtensions.cs | 7 + .../CryptographyExtensions.csproj | 48 +++++++ .../Properties/AssemblyInfo.cs | 36 +++++ .../AccountService.cs | 6 +- .../Interfaces/IAccountService.cs | 2 +- .../SoftwareService.cs | 11 +- LaaProductionWeb/LaaProductionWeb.sln | 6 + .../App_Infrastructure/AuthorizationFilter.cs | 22 +-- .../ControllersExtensions.cs | 122 +++++++++++++++++ .../App_Infrastructure/SessionUser.cs | 127 ------------------ .../Views/Software/SoftwareFunctions.cshtml | 2 +- .../Views/Software/Users.cshtml | 71 +++++++--- .../Views/Software/UsersFunctions.cshtml | 69 +++++++--- .../Controllers/HomeController.cs | 6 +- .../LaaProductionWeb/LaaProductionWeb.csproj | 4 +- .../Views/Home/Session.cshtml | 2 + LaaProductionWeb/LaaProductionWeb/Web.config | 15 ++- 17 files changed, 362 insertions(+), 194 deletions(-) create mode 100644 LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.cs create mode 100644 LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.csproj create mode 100644 LaaProductionWeb/CryptographyExtensions/Properties/AssemblyInfo.cs delete mode 100644 LaaProductionWeb/LaaProductionWeb/App_Infrastructure/SessionUser.cs create mode 100644 LaaProductionWeb/LaaProductionWeb/Views/Home/Session.cshtml diff --git a/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.cs b/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.cs new file mode 100644 index 00000000..3451432c --- /dev/null +++ b/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.cs @@ -0,0 +1,7 @@ +namespace CryptographyExtensions +{ + public static class CryptographyExtensions + { + + } +} diff --git a/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.csproj b/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.csproj new file mode 100644 index 00000000..dce86227 --- /dev/null +++ b/LaaProductionWeb/CryptographyExtensions/CryptographyExtensions.csproj @@ -0,0 +1,48 @@ + + + + + Debug + AnyCPU + {D4B6AF4B-AFD6-446B-92F0-F1388534A247} + Library + Properties + CryptographyExtensions + CryptographyExtensions + v4.8.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LaaProductionWeb/CryptographyExtensions/Properties/AssemblyInfo.cs b/LaaProductionWeb/CryptographyExtensions/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4709d2ad --- /dev/null +++ b/LaaProductionWeb/CryptographyExtensions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CryptographyExtensions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CryptographyExtensions")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d4b6af4b-afd6-446b-92f0-f1388534a247")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/LaaProductionWeb/LaaProductionWeb.Services/AccountService.cs b/LaaProductionWeb/LaaProductionWeb.Services/AccountService.cs index e132b04a..36e5a997 100644 --- a/LaaProductionWeb/LaaProductionWeb.Services/AccountService.cs +++ b/LaaProductionWeb/LaaProductionWeb.Services/AccountService.cs @@ -33,7 +33,7 @@ WHERE [MitarbeiterNr] = @{nameof(userId)}") .AddParameter(nameof(userId), userId) .ExecuteReader(p => p.GetString()) - }) ?? new Employee(); + }); public IEnumerable FindUserFunctions(short appId, string username, string password) => this.sqlClient @@ -52,7 +52,7 @@ .AddParameter(nameof(appId), appId) .ExecuteReader(x => x.GetString()); - public int Login(string username, string password) + public short Login(string username, string password) => this.sqlClient.FirstOrDefault($@" SELECT TOP 1 [MitarbeiterNr] FROM [Mitarbeiter] @@ -61,7 +61,7 @@ parameters => parameters .Add(nameof(username), username) .Add(nameof(password), password), - reader => reader.GetValue()); + reader => reader.GetSmallint()); public int ResetPassword(string username) => this.sqlClient diff --git a/LaaProductionWeb/LaaProductionWeb.Services/Interfaces/IAccountService.cs b/LaaProductionWeb/LaaProductionWeb.Services/Interfaces/IAccountService.cs index 0986beae..299a0bb7 100644 --- a/LaaProductionWeb/LaaProductionWeb.Services/Interfaces/IAccountService.cs +++ b/LaaProductionWeb/LaaProductionWeb.Services/Interfaces/IAccountService.cs @@ -10,7 +10,7 @@ IEnumerable FindUserFunctions(short appId, string username, string password); - int Login(string username, string password); + short Login(string username, string password); int ResetPassword(string username, string password); diff --git a/LaaProductionWeb/LaaProductionWeb.Services/SoftwareService.cs b/LaaProductionWeb/LaaProductionWeb.Services/SoftwareService.cs index ef7e1aad..1022c089 100644 --- a/LaaProductionWeb/LaaProductionWeb.Services/SoftwareService.cs +++ b/LaaProductionWeb/LaaProductionWeb.Services/SoftwareService.cs @@ -28,13 +28,22 @@ .ExecuteNonQuery(); public void DeleteFunction(int funcId) - => this.sqlClient + { + this.sqlClient .CreateCommand($@" DELETE FROM [SoftwareFunctions] WHERE [Id] = @{nameof(funcId)}") .AddParameter(nameof(funcId), funcId) .ExecuteNonQuery(); + this.sqlClient + .CreateCommand($@" + DELETE FROM [UsersFunctions] + WHERE [SoftwareFunctionId] = @{nameof(funcId)}") + .AddParameter(nameof(funcId), funcId) + .ExecuteNonQuery(); + } + public IEnumerable FindSoftwareForUser(short appId, string username, string password) { throw new NotImplementedException(); diff --git a/LaaProductionWeb/LaaProductionWeb.sln b/LaaProductionWeb/LaaProductionWeb.sln index 95ff4126..5a3c33ac 100644 --- a/LaaProductionWeb/LaaProductionWeb.sln +++ b/LaaProductionWeb/LaaProductionWeb.sln @@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Documents", "Documents", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LaaProductionWeb", "LaaProductionWeb\LaaProductionWeb.csproj", "{D1AD077B-00E3-4663-AB9F-23FF65D98D2F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CryptographyExtensions", "CryptographyExtensions\CryptographyExtensions.csproj", "{D4B6AF4B-AFD6-446B-92F0-F1388534A247}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -32,6 +34,10 @@ Global {D1AD077B-00E3-4663-AB9F-23FF65D98D2F}.Debug|Any CPU.Build.0 = Debug|Any CPU {D1AD077B-00E3-4663-AB9F-23FF65D98D2F}.Release|Any CPU.ActiveCfg = Release|Any CPU {D1AD077B-00E3-4663-AB9F-23FF65D98D2F}.Release|Any CPU.Build.0 = Release|Any CPU + {D4B6AF4B-AFD6-446B-92F0-F1388534A247}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4B6AF4B-AFD6-446B-92F0-F1388534A247}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4B6AF4B-AFD6-446B-92F0-F1388534A247}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4B6AF4B-AFD6-446B-92F0-F1388534A247}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/AuthorizationFilter.cs b/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/AuthorizationFilter.cs index fb7e67dc..01b80a83 100644 --- a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/AuthorizationFilter.cs +++ b/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/AuthorizationFilter.cs @@ -13,20 +13,22 @@ var httpContext = filterContext.HttpContext; var userId = httpContext.UserId(); var accountService = ServiceProvider.Current.GetService(); - - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] - { - new Claim(ClaimTypes.Name, string.Empty), - new Claim(ClaimTypes.Role, UserRoles.WEB_Anonymous), - }, nameof(Claim), ClaimTypes.Name, ClaimTypes.Role)); - var employee = accountService.FindEmployee(userId); - var claims = new List(); - if (employee.IsValid) + if (employee is null) { + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.NameIdentifier, "-1"), + new Claim(ClaimTypes.Name, string.Empty), + new Claim(ClaimTypes.Role, UserRoles.WEB_Anonymous), + }, nameof(ClaimTypes), ClaimTypes.Name, ClaimTypes.Role)); + } + else + { + var claims = new List(); claims.Add(new Claim(ClaimTypes.NameIdentifier, $"{userId}")); - claims.Add(new Claim(ClaimTypes.Name, employee.Name)); + claims.Add(new Claim(ClaimTypes.Name, employee.Name ?? string.Empty)); foreach (var permission in employee.Permissions) { diff --git a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/ControllersExtensions.cs b/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/ControllersExtensions.cs index cf241668..a1926528 100644 --- a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/ControllersExtensions.cs +++ b/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/ControllersExtensions.cs @@ -1,15 +1,24 @@ namespace LaaProductionWeb.App_Infrastructure { + using Newtonsoft.Json; + using System; using System.Linq; + using System.Net; using System.Security.Claims; using System.Security.Principal; + using System.Text; + using System.Web; /// /// Static class with extension methods that run on controller contexts. /// public static class ControllersExtensions { + const string ORDER_DATA = nameof(ORDER_DATA); + const string URL_REFERER = nameof(URL_REFERER); + const string SESSION_USER = nameof(SESSION_USER); + public static TDST Map(this TSRC model, Func mapper) where TDST : class where TSRC : class @@ -33,5 +42,118 @@ return ""; } + + public static string ClaimId(this IPrincipal principal) + { + if (principal is ClaimsPrincipal claimsPrincipal) + { + return claimsPrincipal + .FindAll(ClaimTypes.NameIdentifier) + .LastOrDefault()?.Value; + } + + return ""; + } + + public static string GetUrlReferer(this HttpContextBase httpContext) + => httpContext + .Request + .Cookies + .Get(URL_REFERER) + ?.Value ?? null; + + 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(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(json); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + } + } + + return default(T); + } + + public static short UserId(this HttpContextBase httpContext) + { + var requestCookies = httpContext.Request.Cookies; + var sessionUserCookie = requestCookies.Get(SESSION_USER); + + if (sessionUserCookie is null) + { + sessionUserCookie = new HttpCookie(SESSION_USER, string.Empty); + } + + var value = sessionUserCookie?.Value ?? string.Empty; + + if (!string.IsNullOrWhiteSpace(value)) + { + value = Encoding.UTF8.GetString(Convert.FromBase64String(value)); + } + + if (short.TryParse(value, out short userId)) + { + sessionUserCookie.Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout); + + requestCookies.Set(sessionUserCookie); + + return userId; + } + + return -1; + } + + public static void SignIn(this HttpContextBase httpContext, short userId) + { + if (userId > 0) + { + var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userId}")); + var cookie = new HttpCookie(SESSION_USER, base64) + { + Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout) + }; + + httpContext.Response.AppendCookie(cookie); + } + } + + public static void SignOut(this HttpContextBase httpContext) + => httpContext + .Response + .Cookies + .Remove(SESSION_USER); } } \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/SessionUser.cs b/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/SessionUser.cs deleted file mode 100644 index 26487955..00000000 --- a/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/SessionUser.cs +++ /dev/null @@ -1,127 +0,0 @@ -namespace LaaProductionWeb.App_Infrastructure -{ - using Newtonsoft.Json; - - using System; - using System.Net; - using System.Web; - - public class SessionUser - { - public SessionUser() - => this.UserId = -1; - - public SessionUser(int userId, DateTime expires) - { - this.UserId = userId; - this.Expires = expires; - } - - public int UserId { get; } - - public DateTime Expires { get; } - - public bool IsExpired => this.Expires < DateTime.Now.AddMinutes(30) || this.Expires > DateTime.Now; - } - - public static class SessionUserExtensions - { - public static short UserId(this HttpContextBase httpContext) - { - var cookies = httpContext.Request.Cookies; - var userCookie = cookies.Get(nameof(SessionUser)); - var cookieUserId = userCookie?.Value ?? string.Empty; - - if (short.TryParse(cookieUserId, out short userId)) - { - userCookie.Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout); - - cookies.Set(userCookie); - - return userId; - } - - return -1; - } - - public static bool SignIn(this HttpContextBase httpContext, int userId) - { - if (userId > 0) - { - httpContext.Response.AppendCookie(new HttpCookie(nameof(SessionUser), $"{userId}") - { - Expires = DateTime.Now.AddSeconds(Appsettings.LoginTimeout) - }); - - return true; - } - - return false; - } - - public static void SignOut(this HttpContextBase httpContext) - { - var cookieUserId = httpContext - .Response - .Cookies - .Get(nameof(SessionUser)) - ?.Value ?? string.Empty; - } - - const string DATA = nameof(DATA); - - public static void SetUserData(this HttpContextBase httpContext, object data) - { - if (data != null) - { - var userId = httpContext.UserId(); - var json = JsonConvert.SerializeObject(data); - var encoded = WebUtility.UrlEncode(json); - var cookie = new HttpCookie($"{DATA}_{userId}") - { - Value = encoded, - Expires = DateTime.Now.AddHours(7) - }; - - httpContext.Response.Cookies.Set(cookie); - } - } - - public static T GetUserData(this HttpContextBase httpContext) - { - var userId = httpContext.UserId(); - var cookie = httpContext.Request.Cookies.Get($"{DATA}_{userId}"); - - if (cookie != null && cookie.Value != null) - { - try - { - var json = WebUtility.UrlDecode(cookie.Value); - - return JsonConvert.DeserializeObject(json); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - } - - return default(T); - } - - const string URL_REFERER = nameof(URL_REFERER); - - public static void SetUrlReferer(this HttpContextBase httpContext) - => httpContext - .Response - .Cookies - .Add(new HttpCookie(URL_REFERER, $"{httpContext.Request.Url}")); - - public static string GetUrlReferer(this HttpContextBase httpContext) - => httpContext - .Request - .Cookies - .Get(URL_REFERER) - ?.Value ?? "/"; - } -} \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/SoftwareFunctions.cshtml b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/SoftwareFunctions.cshtml index 43d1c973..ea473b99 100644 --- a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/SoftwareFunctions.cshtml +++ b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/SoftwareFunctions.cshtml @@ -154,7 +154,7 @@ } - + diff --git a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/Users.cshtml b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/Users.cshtml index 2530d2c5..0c47994b 100644 --- a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/Users.cshtml +++ b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/Users.cshtml @@ -11,12 +11,11 @@ Users Functions Users
-
+
- - +
- +
@if (this.User.IsInRole(UserRoles.WEB_Admin)) { Update users passwords @@ -68,25 +67,53 @@ @section scripts { } \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/UsersFunctions.cshtml b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/UsersFunctions.cshtml index 4e309ce3..367679c3 100644 --- a/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/UsersFunctions.cshtml +++ b/LaaProductionWeb/LaaProductionWeb/Areas/Administration/Views/Software/UsersFunctions.cshtml @@ -10,12 +10,11 @@ Software Functions Users Functions
-
+
- - +
- +
Users
@@ -47,20 +46,22 @@ @@ -72,4 +73,36 @@ - \ No newline at end of file + + +@section scripts { + +} \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb/Controllers/HomeController.cs b/LaaProductionWeb/LaaProductionWeb/Controllers/HomeController.cs index 0b0e8b0b..769190b7 100644 --- a/LaaProductionWeb/LaaProductionWeb/Controllers/HomeController.cs +++ b/LaaProductionWeb/LaaProductionWeb/Controllers/HomeController.cs @@ -14,7 +14,7 @@ => this.accountService = ServiceProvider.Current.GetService(); [HttpGet] - public ActionResult Index() + public ActionResult Index() => this.View(); [HttpPost] @@ -33,8 +33,10 @@ { var userId = this.accountService.Login(username, password); - if (this.HttpContext.SignIn(userId)) + if (userId > 0) { + this.HttpContext.SignIn(userId); + return this.Redirect(this.HttpContext.GetUrlReferer()); } } diff --git a/LaaProductionWeb/LaaProductionWeb/LaaProductionWeb.csproj b/LaaProductionWeb/LaaProductionWeb/LaaProductionWeb.csproj index efe11f48..dc145f96 100644 --- a/LaaProductionWeb/LaaProductionWeb/LaaProductionWeb.csproj +++ b/LaaProductionWeb/LaaProductionWeb/LaaProductionWeb.csproj @@ -130,7 +130,6 @@ - @@ -245,6 +244,7 @@ + @@ -273,7 +273,7 @@ True True 57995 - / + /LaaProductionWeb http://localhost:54448/ False False diff --git a/LaaProductionWeb/LaaProductionWeb/Views/Home/Session.cshtml b/LaaProductionWeb/LaaProductionWeb/Views/Home/Session.cshtml new file mode 100644 index 00000000..a7681b7f --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb/Views/Home/Session.cshtml @@ -0,0 +1,2 @@ +

@this.Context.Session["xyz"]

+ diff --git a/LaaProductionWeb/LaaProductionWeb/Web.config b/LaaProductionWeb/LaaProductionWeb/Web.config index 751dd71c..ca4c3c9d 100644 --- a/LaaProductionWeb/LaaProductionWeb/Web.config +++ b/LaaProductionWeb/LaaProductionWeb/Web.config @@ -26,13 +26,13 @@ - + - - - - + + + + @@ -77,11 +77,12 @@ - + - + +