From d76623155a62befa056b460408183dac36a37b8e Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Mon, 1 Jul 2024 15:42:17 +0200 Subject: [PATCH] =?UTF-8?q?Logger=20zum=20AuthController=20hinzugef=C3=BCg?= =?UTF-8?q?t.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/AuthController.cs | 131 +++++++++++------- 1 file changed, 83 insertions(+), 48 deletions(-) diff --git a/DigitalData.UserManager.API/Controllers/AuthController.cs b/DigitalData.UserManager.API/Controllers/AuthController.cs index eeeb636..76b0f8c 100644 --- a/DigitalData.UserManager.API/Controllers/AuthController.cs +++ b/DigitalData.UserManager.API/Controllers/AuthController.cs @@ -20,43 +20,58 @@ namespace DigitalData.UserManager.API.Controllers private readonly IGroupOfUserService _gouService; private readonly IDirectorySearchService _dirSearchService; private readonly IStringLocalizer _localizer; + private readonly ILogger _logger; - public AuthController(IUserService userService, IGroupOfUserService gouService, IDirectorySearchService directorySearchService, IStringLocalizer localizer) + public AuthController(IUserService userService, IGroupOfUserService gouService, IDirectorySearchService directorySearchService, IStringLocalizer localizer, ILogger logger) { _userService = userService; _gouService = gouService; _dirSearchService = directorySearchService; _localizer = localizer; + _logger = logger; } [AllowAnonymous] [HttpGet("check")] - public IActionResult CheckAuthentication() => Ok(new AuthCheckDto(IsAuthenticated: User.Identity?.IsAuthenticated ?? false)); + public IActionResult CheckAuthentication() + { + try + { + return Ok(new AuthCheckDto(IsAuthenticated: User.Identity?.IsAuthenticated ?? false)); + } + catch(Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); + } + } [AllowAnonymous] [HttpPost("login")] public async Task Login([FromBody] LogInDto login) { - bool isValid = _dirSearchService.ValidateCredentials(login.Username, login.Password); + try + { + bool isValid = _dirSearchService.ValidateCredentials(login.Username, login.Password); - if (!isValid) - return Unauthorized(Result.Fail().Message(_localizer[Key.UserNotFound])); + if (!isValid) + return Unauthorized(Result.Fail().Message(_localizer[Key.UserNotFound])); - var gouMsg = await _gouService.HasGroup(login.Username, "PM_USER", caseSensitive:false); - if(!gouMsg.IsSuccess) - return Unauthorized(Result.Fail().Message(_localizer[Key.UnauthorizedUser])); + var gouMsg = await _gouService.HasGroup(login.Username, "PM_USER", caseSensitive: false); + if (!gouMsg.IsSuccess) + return Unauthorized(Result.Fail().Message(_localizer[Key.UnauthorizedUser])); - //find the user - var uRes = await _userService.ReadByUsernameAsync(login.Username); - if (!uRes.IsSuccess || uRes.Data is null) - { - return Unauthorized(uRes); - } + //find the user + var uRes = await _userService.ReadByUsernameAsync(login.Username); + if (!uRes.IsSuccess || uRes.Data is null) + { + return Unauthorized(uRes); + } - UserReadDto user = uRes.Data; + UserReadDto user = uRes.Data; - // Create claims - var claims = new List + // Create claims + var claims = new List { new (ClaimTypes.NameIdentifier, user.Id.ToString()), new (ClaimTypes.Name, user.Username), @@ -66,54 +81,74 @@ namespace DigitalData.UserManager.API.Controllers new (ClaimTypes.Role, "PM_USER") }; - // Create claimsIdentity - var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + // Create claimsIdentity + var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); - // Create authProperties - var authProperties = new AuthenticationProperties - { - IsPersistent = true, - AllowRefresh = true, - ExpiresUtc = DateTime.UtcNow.AddMinutes(60) - }; + // Create authProperties + var authProperties = new AuthenticationProperties + { + IsPersistent = true, + AllowRefresh = true, + ExpiresUtc = DateTime.UtcNow.AddMinutes(60) + }; - // Sign in - await HttpContext.SignInAsync( - CookieAuthenticationDefaults.AuthenticationScheme, - new ClaimsPrincipal(claimsIdentity), - authProperties); + // Sign in + await HttpContext.SignInAsync( + CookieAuthenticationDefaults.AuthenticationScheme, + new ClaimsPrincipal(claimsIdentity), + authProperties); - _dirSearchService.SetSearchRootCache(user.Username, login.Password); + _dirSearchService.SetSearchRootCache(user.Username, login.Password); - return Ok(); + return Ok(); + } + catch(Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); + } } [Authorize] [HttpGet("user")] public async Task GetUserWithClaims() { - // Extract the username from the Name claim. - string? username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value; - - if (string.IsNullOrEmpty(username)) - return Unauthorized(); - - var userDto = await _userService.ReadByUsernameAsync(username); - - if (!userDto.IsSuccess || userDto.Data is null) + try { - return NotFound(Result.Fail().Message(_localizer[Key.UserNotFound])); + // Extract the username from the Name claim. + string? username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value; + + if (string.IsNullOrEmpty(username)) + return Unauthorized(); + + return await _userService.ReadByUsernameAsync(username) + .ThenAsync(Ok, IActionResult (m, n) => + { + _logger.LogNotice(n); + return NotFound(Result.Fail().Message(_localizer[Key.UserNotFound])); + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); } - - return Ok(userDto.Data); } - [AllowAnonymous] + [Authorize] [HttpPost("logout")] public async Task Logout() { - await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - return Ok(); + try + { + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return Ok(); + } + catch(Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError); + } } } } \ No newline at end of file