namespace LaaProductionWeb.Services { using LaaProductionSQL.Interfaces; using LaaProductionWeb.Services.Interfaces; using LaaProductionWeb.Services.Models; using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; public class AccountService : IAccountService { private readonly ISQLConnection sqlConnection; public AccountService(ISQLConnection sqlConnection) => this.sqlConnection = sqlConnection; public Employee FindEmployee(short userId) => this.sqlConnection .CreateCommand($@" SELECT [Vorname] + ' ' + [Name] FROM [Mitarbeiter] WHERE [MitarbeiterNr] = @{nameof(userId)}") .SetParameter(nameof(userId), userId) .FirstOrDefault(x => new Employee { Name = x.GetString().Trim(), Permissions = this.sqlConnection .CreateCommand($@" SELECT DISTINCT [Recht] FROM [MitarbeiterRechte] WHERE [MitarbeiterNr] = @{nameof(userId)}") .SetParameter(nameof(userId), userId) .ExecuteReader(p => p.GetString()) }); public IEnumerable FindUserFunctions(short appId, string username, string password) => this.sqlConnection .CreateCommand($@" SELECT [SF].[Function] FROM [Mitarbeiter] AS [U] JOIN [UsersFunctions] AS [UF] ON [UF].[UserId] = [U].[MitarbeiterNr] JOIN [SoftwareFunctions] AS [SF] ON [SF].[Id] = [UF].[SoftwareFunctionId] WHERE [U].[Benutzername] = @{nameof(username)} AND [U].[PasswordHash] = @{nameof(password)} AND [SF].[AppId] = @{nameof(appId)}") .SetParameter(nameof(username), username) .SetParameter(nameof(password), password) .SetParameter(nameof(appId), appId) .ExecuteReader(x => x.GetString()); public short Login(string username, string password) => this.sqlConnection .CreateCommand($@" SELECT TOP 1 [MitarbeiterNr] FROM [Mitarbeiter] WHERE [Benutzername] LIKE @{nameof(username)} AND [PasswordHash] LIKE @{nameof(password)}") .SetParameter(nameof(username), username) .SetParameter(nameof(password), password) .FirstOrDefault(reader => reader.GetSmallint()); public int ResetPassword(string username) => this.sqlConnection .CreateCommand($@" UPDATE [Mitarbeiter] SET [PasswordHash] = NULL WHERE [Benutzername] = @{nameof(username)}") .SetParameter(nameof(username), username) .ExecuteNonQuery(); public int ResetPassword(string username, string password) => this.sqlConnection .CreateCommand($@" UPDATE [Mitarbeiter] SET [PasswordHash] = @{nameof(password)} WHERE [Benutzername] = @{nameof(username)}") .SetParameter(nameof(username), username) .SetParameter(nameof(password), password) .ExecuteNonQuery(); } public static class AccountExtensions { public static string ComputeHash(this HashAlgorithm hashAlgorithm, string value) { if (!string.IsNullOrWhiteSpace(value)) { var bytes = Encoding.UTF8.GetBytes(value); var hash = hashAlgorithm.ComputeHash(bytes); var base64 = Convert.ToBase64String(hash); return base64; } return value; } public static string ComputeHash(this string value) => SHA256.Create().ComputeHash(value); } }