From 5bd57a9fef7da8cc14f23c45ca7c610797ddc12a Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Mon, 21 Feb 2022 18:27:33 +0100 Subject: [PATCH] Improved permissions --- gswi.Interface/Services/IAuthService.cs | 6 +- gswi.Model/AuthRoles.cs | 4 +- gswi.Service/AuthServiceImpl.cs | 294 ++++++++---------------- gswi/Controllers/AuthController.cs | 65 ++---- gswi/DataSeeder.cs | 69 +++--- 5 files changed, 150 insertions(+), 288 deletions(-) diff --git a/gswi.Interface/Services/IAuthService.cs b/gswi.Interface/Services/IAuthService.cs index 0172a14..3fd70e3 100644 --- a/gswi.Interface/Services/IAuthService.cs +++ b/gswi.Interface/Services/IAuthService.cs @@ -4,10 +4,8 @@ using System.Threading.Tasks; using gswi.Model.DTOs; using gswi.Share.Common; -namespace gswi.Interface.Services -{ - public interface IAuthService - { +namespace gswi.Interface.Services { + public interface IAuthService { Task> GetAllAuthUsersAsync(); Task GetFilteredAuthUsersAsync(AuthUserSelectCriterion selectCriterion); Task GetAuthUserByEMailAsync(string email); diff --git a/gswi.Model/AuthRoles.cs b/gswi.Model/AuthRoles.cs index 8c908b9..071c87e 100644 --- a/gswi.Model/AuthRoles.cs +++ b/gswi.Model/AuthRoles.cs @@ -4,8 +4,8 @@ namespace gswi.Model { public enum AuthRoles { - User = 0, - Supporter = 1, + Supporter = 0, + User = 1, Admin = 2 } } diff --git a/gswi.Service/AuthServiceImpl.cs b/gswi.Service/AuthServiceImpl.cs index f3b3aca..12bbddc 100644 --- a/gswi.Service/AuthServiceImpl.cs +++ b/gswi.Service/AuthServiceImpl.cs @@ -6,8 +6,6 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; -using Microsoft.IdentityModel.Tokens; -using NLog; using gswi.Configuration; using gswi.Interface.Repositories; using gswi.Interface.Services; @@ -17,11 +15,11 @@ using gswi.Model.Filters; using gswi.Share.Common; using gswi.SMTP.Interface; using gswi.SMTP.Model; +using Microsoft.IdentityModel.Tokens; +using NLog; -namespace gswi.Service -{ - public class AuthServiceImpl : IAuthService - { +namespace gswi.Service { + public class AuthServiceImpl : IAuthService { private readonly IAuthUserRepository _authUserRepository; private readonly IUnitOfWork _unitOfWork; private readonly AuthentificationSettings _authSettings; @@ -36,8 +34,7 @@ namespace gswi.Service AuthentificationSettings authSettings, ISMTPClient smtpClient, FrontendSettings frontendSettings - ) - { + ) { _unitOfWork = unitOfWork; _authUserRepository = authUserRepository; _authSettings = authSettings; @@ -45,15 +42,13 @@ namespace gswi.Service _frontendSettings = frontendSettings; } - private static string _randomString(int length) - { + private static string _randomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } - private string _generateToken(IEnumerable claims) - { + private string _generateToken(IEnumerable claims) { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authSettings.SecretKey)); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); @@ -68,18 +63,15 @@ namespace gswi.Service return new JwtSecurityTokenHandler().WriteToken(tokenOptions); } - private string _generateRefreshToken() - { + private string _generateRefreshToken() { var randomNumber = new byte[32]; - using (var rng = RandomNumberGenerator.Create()) - { + using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomNumber); return Convert.ToBase64String(randomNumber); } } - private async Task _createAndSaveRefreshToken(AuthUser user) - { + private async Task _createAndSaveRefreshToken(AuthUser user) { var refreshToken = this._generateRefreshToken(); user.RefreshToken = refreshToken; @@ -90,10 +82,8 @@ namespace gswi.Service return refreshToken; } - private ClaimsPrincipal _getPrincipalFromExpiredToken(string token) - { - var tokenValidationParameters = new TokenValidationParameters - { + private ClaimsPrincipal _getPrincipalFromExpiredToken(string token) { + var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, //you might want to validate the audience and issuer depending on your use case ValidateIssuer = false, ValidateIssuerSigningKey = true, @@ -109,64 +99,52 @@ namespace gswi.Service return principal; } - private async Task _createAndSaveConfirmationId(AuthUser user) - { + private async Task _createAndSaveConfirmationId(AuthUser user) { bool end = false; - while (!end) - { + while (!end) { string id = _randomString(16); var userFromDb = await _authUserRepository.FindAuthUserByEMailConfirmationIdAsync(id); - if (userFromDb is null) - { + if (userFromDb is null) { end = true; user.ConfirmationId = id; } } } - private async Task _createAndSaveForgotPasswordId(AuthUser user) - { + private async Task _createAndSaveForgotPasswordId(AuthUser user) { bool end = false; - while (!end) - { + while (!end) { string id = _randomString(16); var userFromDb = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(id); - if (userFromDb is null) - { + if (userFromDb is null) { end = true; user.ForgotPasswordId = id; } } } - private async Task _sendConfirmationIdToUser(AuthUser user) - { + private async Task _sendConfirmationIdToUser(AuthUser user) { string url = _frontendSettings.URL.EndsWith("/") ? _frontendSettings.URL : $"{_frontendSettings}/"; - await _smtpClient.SendEmailAsync(new EMail() - { + await _smtpClient.SendEmailAsync(new EMail() { Receiver = user.EMail, Subject = $"E-Mail für {user.FirstName} {user.LastName} bestätigen", Message = $"{url}auth/register/{user.ConfirmationId}" }); } - private async Task _sendForgotPasswordIdToUser(AuthUser user) - { + private async Task _sendForgotPasswordIdToUser(AuthUser user) { string url = _frontendSettings.URL.EndsWith("/") ? _frontendSettings.URL : $"{_frontendSettings}/"; - await _smtpClient.SendEmailAsync(new EMail() - { + await _smtpClient.SendEmailAsync(new EMail() { Receiver = user.EMail, Subject = $"Passwort für {user.FirstName} {user.LastName} zurücksetzen", Message = $"{url}auth/forgot-password/{user.ForgotPasswordId}" }); } - public async Task> GetAllAuthUsersAsync() - { + public async Task> GetAllAuthUsersAsync() { var authUserDTOs = new List(); var authUsers = await _authUserRepository.GetAllAuthUsersAsync(); - authUsers.ForEach(authUser => - { + authUsers.ForEach(authUser => { authUserDTOs.Add(authUser.ToAuthUserDTO()); }); return authUserDTOs; @@ -180,38 +158,31 @@ namespace gswi.Service users.ForEach(user => { result.Add(user.ToAuthUserDTO()); }); - + return new GetFilteredAuthUsersResultDTO() { Users = result, TotalCount = totalCount }; } - public async Task GetAuthUserByEMailAsync(string email) - { - try - { + public async Task GetAuthUserByEMailAsync(string email) { + try { var authUser = await _authUserRepository.GetAuthUserByEMailAsync(email); return authUser.ToAuthUserDTO(); - } - catch (Exception e) - { + } catch (Exception e) { _logger.Error(e); throw new ServiceException(ServiceErrorCode.InvalidData, $"AuthUser with email {email} not found"); } } - public async Task FindAuthUserByEMailAsync(string email) - { + public async Task FindAuthUserByEMailAsync(string email) { var authUser = await _authUserRepository.FindAuthUserByEMailAsync(email); return authUser != null ? authUser.ToAuthUserDTO() : null; } - public async Task AddAuthUserAsync(AuthUserDTO authUserDTO) - { + public async Task AddAuthUserAsync(AuthUserDTO authUserDTO) { var authUserDb = await _authUserRepository.FindAuthUserByEMailAsync(authUserDTO.EMail); - if (authUserDb != null) - { + if (authUserDb != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists"); } @@ -220,32 +191,26 @@ namespace gswi.Service var authUser = authUserDTO.ToAuthUser(); - if (!IsValidEmail(authUser.EMail)) - { + if (!IsValidEmail(authUser.EMail)) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail"); } - try - { + try { _authUserRepository.AddAuthUser(authUser); await _createAndSaveConfirmationId(authUser); await _sendConfirmationIdToUser(authUser); await _unitOfWork.SaveChangesAsync(); _logger.Info($"Added authUser with email: {authUser.EMail}"); return authUser.Id; - } - catch (Exception e) - { + } catch (Exception e) { _logger.Error(e); throw new ServiceException(ServiceErrorCode.UnableToAdd, $"Cannot add authUser {authUserDTO.EMail}"); } } - public async Task ConfirmEMail(string id) - { + public async Task ConfirmEMail(string id) { var user = await _authUserRepository.FindAuthUserByEMailConfirmationIdAsync(id); - if (user.ConfirmationId == id) - { + if (user.ConfirmationId == id) { user.ConfirmationId = null; await _unitOfWork.SaveChangesAsync(); return true; @@ -253,27 +218,22 @@ namespace gswi.Service return false; } - public async Task Login(AuthUserDTO userDTO) - { - if (userDTO == null) - { + public async Task Login(AuthUserDTO userDTO) { + if (userDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty"); } var userFromDb = await _authUserRepository.FindAuthUserByEMailAsync(userDTO.EMail); - if (userFromDb == null) - { + if (userFromDb == null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found"); } - if (userFromDb.ConfirmationId != null) - { + if (userFromDb.ConfirmationId != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed"); } userDTO.Password = ComputeHash(userDTO.Password, new SHA256CryptoServiceProvider()); - if (userFromDb.Password != userDTO.Password) - { + if (userFromDb.Password != userDTO.Password) { throw new ServiceException(ServiceErrorCode.InvalidUser, "Wrong password"); } @@ -284,24 +244,20 @@ namespace gswi.Service var refreshString = await this._createAndSaveRefreshToken(userFromDb); - if (userFromDb.ForgotPasswordId != null) - { + if (userFromDb.ForgotPasswordId != null) { userFromDb.ForgotPasswordId = null; await _unitOfWork.SaveChangesAsync(); } - return new TokenDTO - { + return new TokenDTO { Token = tokenString, RefreshToken = refreshString }; } - public async Task ForgotPassword(string email) - { + public async Task ForgotPassword(string email) { var user = await _authUserRepository.FindAuthUserByEMailAsync(email); - if (user is null) - { + if (user is null) { return; } await _createAndSaveForgotPasswordId(user); @@ -309,30 +265,24 @@ namespace gswi.Service await _unitOfWork.SaveChangesAsync(); } - public async Task ConfirmForgotPassword(string id) - { + public async Task ConfirmForgotPassword(string id) { var user = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(id); - return new EMailStringDTO() - { + return new EMailStringDTO() { EMail = user.EMail }; } - public async Task ResetPassword(ResetPasswordDTO rpDTO) - { + public async Task ResetPassword(ResetPasswordDTO rpDTO) { var user = await _authUserRepository.FindAuthUserByEMailForgotPasswordIdAsync(rpDTO.Id); - if (user == null) - { + if (user == null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found"); } - if (user.ConfirmationId != null) - { + if (user.ConfirmationId != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed"); } - if (rpDTO.Password == null || rpDTO.Password == "") - { + if (rpDTO.Password == null || rpDTO.Password == "") { throw new ServiceException(ServiceErrorCode.InvalidData, "Password is empty"); } @@ -341,57 +291,46 @@ namespace gswi.Service await _unitOfWork.SaveChangesAsync(); } - public async Task UpdateUser(UpdateUserDTO updateUserDTO) - { - if (updateUserDTO == null) - { + public async Task UpdateUser(UpdateUserDTO updateUserDTO) { + if (updateUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty"); } - if (updateUserDTO.AuthUserDTO == null) - { + if (updateUserDTO.AuthUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Existing user is empty"); } - if (updateUserDTO.NewAuthUserDTO == null) - { + if (updateUserDTO.NewAuthUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"New user is empty"); } - if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) - { + if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail"); } var user = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.AuthUserDTO.EMail); - if (user == null) - { + if (user == null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found"); } - if (user.ConfirmationId != null) - { + if (user.ConfirmationId != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "E-Mail not confirmed"); } // update first name - if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) - { + if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) { user.FirstName = updateUserDTO.NewAuthUserDTO.FirstName; } // update last name - if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) - { + if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) { user.LastName = updateUserDTO.NewAuthUserDTO.LastName; } // update E-Mail - if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) - { + if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) { var userByNewEMail = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.NewAuthUserDTO.EMail); - if (userByNewEMail != null) - { + if (userByNewEMail != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists"); } user.EMail = updateUserDTO.NewAuthUserDTO.EMail; @@ -400,66 +339,53 @@ namespace gswi.Service bool isExistingPasswordSet = false; bool isnewPasswordSet = false; // hash passwords in DTOs - if (updateUserDTO.AuthUserDTO.Password != null && updateUserDTO.AuthUserDTO.Password != "") - { + if (updateUserDTO.AuthUserDTO.Password != null && updateUserDTO.AuthUserDTO.Password != "") { isExistingPasswordSet = true; updateUserDTO.AuthUserDTO.Password = ComputeHash(updateUserDTO.AuthUserDTO.Password, new SHA256CryptoServiceProvider()); } - if (updateUserDTO.AuthUserDTO.Password != user.Password) - { + if (updateUserDTO.AuthUserDTO.Password != user.Password) { throw new ServiceException(ServiceErrorCode.InvalidUser, "Wrong password"); } - if (updateUserDTO.NewAuthUserDTO.Password != null && updateUserDTO.NewAuthUserDTO.Password != "") - { + if (updateUserDTO.NewAuthUserDTO.Password != null && updateUserDTO.NewAuthUserDTO.Password != "") { isnewPasswordSet = true; updateUserDTO.NewAuthUserDTO.Password = ComputeHash(updateUserDTO.NewAuthUserDTO.Password, new SHA256CryptoServiceProvider()); } // update password - if (isExistingPasswordSet && isnewPasswordSet && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) - { + if (isExistingPasswordSet && isnewPasswordSet && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) { user.Password = updateUserDTO.NewAuthUserDTO.Password; } await _unitOfWork.SaveChangesAsync(); } - public async Task UpdateUserAsAdmin(AdminUpdateUserDTO updateUserDTO) - { - if (updateUserDTO == null) - { + public async Task UpdateUserAsAdmin(AdminUpdateUserDTO updateUserDTO) { + if (updateUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"User is empty"); } - if (updateUserDTO.AuthUserDTO == null) - { + if (updateUserDTO.AuthUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Existing user is empty"); } - if (updateUserDTO.NewAuthUserDTO == null) - { + if (updateUserDTO.NewAuthUserDTO == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"New user is empty"); } - if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) - { + if (!IsValidEmail(updateUserDTO.AuthUserDTO.EMail) || !IsValidEmail(updateUserDTO.NewAuthUserDTO.EMail)) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Invalid E-Mail"); } var user = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.AuthUserDTO.EMail); - if (user == null) - { + if (user == null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User not found"); } - if (user.ConfirmationId != null && updateUserDTO.NewAuthUserDTO.IsConfirmed) - { + if (user.ConfirmationId != null && updateUserDTO.NewAuthUserDTO.IsConfirmed) { user.ConfirmationId = null; - } - else if (user.ConfirmationId == null && !updateUserDTO.NewAuthUserDTO.IsConfirmed) - { + } else if (user.ConfirmationId == null && !updateUserDTO.NewAuthUserDTO.IsConfirmed) { await _createAndSaveConfirmationId(user); } @@ -469,47 +395,39 @@ namespace gswi.Service // } // update first name - if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) - { + if (updateUserDTO.NewAuthUserDTO.FirstName != null && updateUserDTO.AuthUserDTO.FirstName != updateUserDTO.NewAuthUserDTO.FirstName) { user.FirstName = updateUserDTO.NewAuthUserDTO.FirstName; } // update last name - if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) - { + if (updateUserDTO.NewAuthUserDTO.LastName != null && updateUserDTO.NewAuthUserDTO.LastName != "" && updateUserDTO.AuthUserDTO.LastName != updateUserDTO.NewAuthUserDTO.LastName) { user.LastName = updateUserDTO.NewAuthUserDTO.LastName; } // update E-Mail - if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) - { + if (updateUserDTO.NewAuthUserDTO.EMail != null && updateUserDTO.NewAuthUserDTO.EMail != "" && updateUserDTO.AuthUserDTO.EMail != updateUserDTO.NewAuthUserDTO.EMail) { var userByNewEMail = await _authUserRepository.FindAuthUserByEMailAsync(updateUserDTO.NewAuthUserDTO.EMail); - if (userByNewEMail != null) - { + if (userByNewEMail != null) { throw new ServiceException(ServiceErrorCode.InvalidUser, "User already exists"); } user.EMail = updateUserDTO.NewAuthUserDTO.EMail; } // update password - if (updateUserDTO.ChangePassword && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) - { + if (updateUserDTO.ChangePassword && updateUserDTO.AuthUserDTO.Password != updateUserDTO.NewAuthUserDTO.Password) { user.Password = ComputeHash(updateUserDTO.NewAuthUserDTO.Password, new SHA256CryptoServiceProvider()); } // update role - if (user.AuthRole == updateUserDTO.AuthUserDTO.AuthRole && user.AuthRole != updateUserDTO.NewAuthUserDTO.AuthRole) - { + if (user.AuthRole == updateUserDTO.AuthUserDTO.AuthRole && user.AuthRole != updateUserDTO.NewAuthUserDTO.AuthRole) { user.AuthRole = updateUserDTO.NewAuthUserDTO.AuthRole; } await _unitOfWork.SaveChangesAsync(); } - public async Task Refresh(TokenDTO tokenDTO) - { - if (tokenDTO is null) - { + public async Task Refresh(TokenDTO tokenDTO) { + if (tokenDTO is null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is empty"); } @@ -517,25 +435,21 @@ namespace gswi.Service var email = principal.Identity.Name; var user = await this._authUserRepository.FindAuthUserByEMailAsync(email); - if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) - { + if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is expired"); } var newToken = this._generateToken(principal.Claims); var newRefreshToken = await this._createAndSaveRefreshToken(user); - return new TokenDTO() - { + return new TokenDTO() { Token = newToken, RefreshToken = newRefreshToken }; } - public async Task Revoke(TokenDTO tokenDTO) - { - if (tokenDTO == null || tokenDTO.Token == null || tokenDTO.RefreshToken == null) - { + public async Task Revoke(TokenDTO tokenDTO) { + if (tokenDTO == null || tokenDTO.Token == null || tokenDTO.RefreshToken == null) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is empty"); }; @@ -543,60 +457,46 @@ namespace gswi.Service var email = principal.Identity.Name; var user = await this._authUserRepository.FindAuthUserByEMailAsync(email); - if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) - { + if (user == null || user.RefreshToken != tokenDTO.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { throw new ServiceException(ServiceErrorCode.InvalidData, $"Token is expired"); } user.RefreshToken = null; await _unitOfWork.SaveChangesAsync(); } - public async Task DeleteAuthUserByEMailAsync(string email) - { - try - { + public async Task DeleteAuthUserByEMailAsync(string email) { + try { await _authUserRepository.DeleteAuthUserByEMailAsync(email); await _unitOfWork.SaveChangesAsync(); _logger.Info($"Deleted authUser with email: {email}"); - } - catch (Exception e) - { + } catch (Exception e) { _logger.Error(e); throw new ServiceException(ServiceErrorCode.UnableToDelete, $"Cannot delete authUser with email {email}"); } } - public async Task DeleteAuthUserAsync(AuthUserDTO authUserDTO) - { - try - { + public async Task DeleteAuthUserAsync(AuthUserDTO authUserDTO) { + try { _authUserRepository.DeleteAuthUser(authUserDTO.ToAuthUser()); await _unitOfWork.SaveChangesAsync(); _logger.Info($"Deleted authUser {authUserDTO.EMail}"); - } - catch (Exception e) - { + } catch (Exception e) { _logger.Error(e); throw new ServiceException(ServiceErrorCode.UnableToDelete, $"Cannot delete authUser {authUserDTO.EMail}"); } } - private string ComputeHash(string input, HashAlgorithm algorithm) - { + private string ComputeHash(string input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes); } - private bool IsValidEmail(string email) - { - try - { + private bool IsValidEmail(string email) { + try { var addr = new System.Net.Mail.MailAddress(email); return addr.Address == email; - } - catch - { + } catch { return false; } } diff --git a/gswi/Controllers/AuthController.cs b/gswi/Controllers/AuthController.cs index 189bdd0..999a8b5 100644 --- a/gswi/Controllers/AuthController.cs +++ b/gswi/Controllers/AuthController.cs @@ -4,25 +4,22 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.IdentityModel.Tokens; using gswi.Interface.Services; using gswi.Model.DTOs; using gswi.Share.Common; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; -namespace gswi.Controllers -{ +namespace gswi.Controllers { [Route("api/auth")] [ApiController] - public class AuthController : ControllerBase - { + public class AuthController : ControllerBase { private readonly IAuthService _authService; public AuthController( IAuthService authServce - ) - { + ) { _authService = authServce; } @@ -30,118 +27,102 @@ namespace gswi.Controllers // Get /api/auth/users [HttpGet("users")] [Authorize] - public async Task> GetAllAuthUsers() - { + public async Task> GetAllAuthUsers() { return await _authService.GetAllAuthUsersAsync(); } - + // POST /api/auth/users/get/filtered [HttpPost("users/get/filtered")] [Authorize] - public async Task GetFilteredAuthUsers(AuthUserSelectCriterion selectCriterion) - { + public async Task GetFilteredAuthUsers(AuthUserSelectCriterion selectCriterion) { return await _authService.GetFilteredAuthUsersAsync(selectCriterion); } // Get /api/auth/users/get/ [HttpGet("users/get/{email}")] [Authorize] - public async Task GetUserFromEMail(string email) - { + public async Task GetUserFromEMail(string email) { return await _authService.GetAuthUserByEMailAsync(email); } // Get /api/auth/users/find/ [HttpGet("users/find/{email}")] [Authorize] - public async Task FindUserFromEMail(string email) - { + public async Task FindUserFromEMail(string email) { return await _authService.FindAuthUserByEMailAsync(email); } /* Auth requests */ // POST /api/auth/register [HttpPost("register")] - public async Task Register(AuthUserDTO userDTO) - { + public async Task Register(AuthUserDTO userDTO) { await _authService.AddAuthUserAsync(userDTO); } // POST /api/auth/register/ [HttpPost("register/{id}")] - public async Task ConfirmEMail(string id) - { + public async Task ConfirmEMail(string id) { return await _authService.ConfirmEMail(id); } // POST /api/auth/login [HttpPost("login")] - public async Task Login(AuthUserDTO userDTO) - { + public async Task Login(AuthUserDTO userDTO) { return await _authService.Login(userDTO); } // POST /api/auth/forgot-password [HttpPost("forgot-password")] - public async Task ForgotPassword([FromBody] string email) - { + public async Task ForgotPassword([FromBody] string email) { await _authService.ForgotPassword(email); } // POST /api/auth/confirm-forgot-password [HttpPost("confirm-forgot-password")] - public async Task ConfirmForgotPassword([FromBody] string id) - { + public async Task ConfirmForgotPassword([FromBody] string id) { return await _authService.ConfirmForgotPassword(id); } // POST /api/auth/reset-password [HttpPost("reset-password")] - public async Task ResetPassword(ResetPasswordDTO rpDTO) - { + public async Task ResetPassword(ResetPasswordDTO rpDTO) { await _authService.ResetPassword(rpDTO); } // POST /api/auth/update-user [HttpPost("update-user")] - public async Task UpdateUser(UpdateUserDTO updateUserDTO) - { + public async Task UpdateUser(UpdateUserDTO updateUserDTO) { await _authService.UpdateUser(updateUserDTO); } // POST /api/auth/update-user-as-admin [HttpPost("update-user-as-admin")] [Authorize] - public async Task UpdateUserAsAdmin(AdminUpdateUserDTO updateUserDTO) - { + public async Task UpdateUserAsAdmin(AdminUpdateUserDTO updateUserDTO) { await _authService.UpdateUserAsAdmin(updateUserDTO); } // POST /api/auth/refresh [HttpPost("refresh")] - public async Task Refresh(TokenDTO tokenDTO) - { + public async Task Refresh(TokenDTO tokenDTO) { return await _authService.Refresh(tokenDTO); } // POST /api/auth/revoke [HttpPost("revoke")] - public async Task Revoke(TokenDTO tokenDTO) - { + public async Task Revoke(TokenDTO tokenDTO) { await _authService.Revoke(tokenDTO); } // POST /api/auth/delete-user [HttpPost("delete-user")] - public async Task DeleteAuthUserAsync(AuthUserDTO userDTO) - { + public async Task DeleteAuthUserAsync(AuthUserDTO userDTO) { await _authService.DeleteAuthUserAsync(userDTO); } // POST /api/auth/delete-user [HttpPost("delete-user-by-mail/{mail}")] - public async Task DeleteAuthUserByEMailAsync(string mail) - { + public async Task DeleteAuthUserByEMailAsync(string mail) { await _authService.DeleteAuthUserByEMailAsync(mail); } } diff --git a/gswi/DataSeeder.cs b/gswi/DataSeeder.cs index 3960455..31e2638 100644 --- a/gswi/DataSeeder.cs +++ b/gswi/DataSeeder.cs @@ -1,73 +1,56 @@ using System; using System.Linq; +using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; -using System.Security.Cryptography; -using Microsoft.EntityFrameworkCore; using gswi.Data; using gswi.Model; +using Microsoft.EntityFrameworkCore; -namespace gswi -{ - public class DataSeeder - { +namespace gswi { + public class DataSeeder { private readonly DatabaseContext _databaseContext; - public DataSeeder(DatabaseContext databaseContext) - { + public DataSeeder(DatabaseContext databaseContext) { _databaseContext = databaseContext; } - public void SeedData() - { + public void SeedData() { _databaseContext.Database.EnsureCreated(); - if (!_databaseContext.AuthUsers.Any()) - { - - var admin = new AuthUser() - { + if (!_databaseContext.AuthUsers.Any()) { + var admin = new AuthUser() { FirstName = "Admin", - LastName = "Administator", - EMail = "admin@localhost", - Password = ComputeHash("Administator", new SHA256CryptoServiceProvider()), + LastName = "Admin", + EMail = "admin@localhost.local", + Password = ComputeHash("localhost.local", new SHA256CryptoServiceProvider()), AuthRole = AuthRoles.Admin }; - var authUser = new AuthUser() - { - FirstName = "Max", - LastName = "Mustermann", - EMail = "max.mustermann@gmail.com", - Password = ComputeHash("test1234", new SHA256CryptoServiceProvider()), + var support = new AuthUser() { + FirstName = "Support", + LastName = "Supporter", + EMail = "support@localhost.local", + Password = ComputeHash("localhost.local", new SHA256CryptoServiceProvider()), + AuthRole = AuthRoles.Supporter }; - var authUser1 = new AuthUser() - { - FirstName = "Max", - LastName = "Tester", - EMail = "max.mustermann@mustermail.com", - Password = ComputeHash("test1234", new SHA256CryptoServiceProvider()), - }; - - var authUser2 = new AuthUser() - { - FirstName = "Max", - LastName = "Muster", - EMail = "max.mustermann@yahoo.com", - Password = ComputeHash("test1234", new SHA256CryptoServiceProvider()), + var user = new AuthUser() { + FirstName = "User", + LastName = "User", + EMail = "user@localhost.local", + Password = ComputeHash("localhost.local", new SHA256CryptoServiceProvider()), + AuthRole = AuthRoles.User }; _databaseContext.AuthUsers.Add(admin); - _databaseContext.AuthUsers.Add(authUser); - _databaseContext.AuthUsers.Add(authUser1); - _databaseContext.AuthUsers.Add(authUser2); + _databaseContext.AuthUsers.Add(support); + _databaseContext.AuthUsers.Add(user); } _databaseContext.SaveChanges(); } - public string ComputeHash(string input, HashAlgorithm algorithm) - { + public string ComputeHash(string input, HashAlgorithm algorithm) { Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return BitConverter.ToString(hashedBytes);