feat(auth): Verbesserung der Login-Logik mit erweiterter Validierung und Fehlerbehandlung

- Überprüfungen hinzugefügt, um sicherzustellen, dass entweder 'UserId' oder 'Username' angegeben ist, jedoch nicht beide.
- Fehlermeldungen verbessert, um eine bessere Klarheit zu gewährleisten.
- Benutzerabfrage-Logik in der Login-Methode refaktoriert, um vorhandene Benutzerdaten nach Möglichkeit zu nutzen.
- Konsistente Protokollierung von Hinweisen und Fehlern für eine bessere Nachverfolgbarkeit sichergestellt.
This commit is contained in:
Developer 02 2024-10-25 10:24:27 +02:00
parent 0495dc10de
commit f2ab2a9759
2 changed files with 25 additions and 11 deletions

View File

@ -6,10 +6,10 @@ using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.User;
using Microsoft.AspNetCore.Authorization;
using DigitalData.UserManager.Application;
using DigitalData.UserManager.Application.DTOs.Auth;
using DigitalData.Core.Abstractions.Application;
using Microsoft.Extensions.Localization;
using DigitalData.Core.DTO;
using WorkFlow.API.Models;
namespace WorkFlow.API.Controllers
{
@ -44,20 +44,39 @@ namespace WorkFlow.API.Controllers
{
try
{
bool isValid = _dirSearchService.ValidateCredentials(login.Username, login.Password);
var username = string.Empty;
DataResult<UserReadDto>? uRes = null;
if(login.Username is not null && login.UserId is not null)
return BadRequest("Invalid request: either 'UserId' or 'Username' must be provided, but not both.");
else if(login.Username is not null)
username = login.Username;
else if(login.UserId is int userId)
{
uRes = await _userService.ReadByIdAsync(userId);
if (!uRes.IsSuccess || uRes.Data is null)
{
return Unauthorized(uRes);
}
}
else
return BadRequest("Invalid request: either 'UserId' or 'Username' must be provided, but not both.");
bool isValid = _dirSearchService.ValidateCredentials(username, login.Password);
if (!isValid)
return Unauthorized(Result.Fail().Message(_localizer[Key.UserNotFound]));
var gouMsg = await _gouService.HasGroup(login.Username, "PM_USER", caseSensitive: false);
var gouMsg = await _gouService.HasGroup(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);
uRes ??= await _userService.ReadByUsernameAsync(username);
if (!uRes.IsSuccess || uRes.Data is null)
{
return Unauthorized(uRes);
_logger.LogNotice(uRes.Notices);
return Unauthorized();
}
UserReadDto user = uRes.Data;

View File

@ -1,9 +1,4 @@
namespace WorkFlow.API.Models
{
public record LogInDto(int? UserId, string? Username, string Password)
{
public bool HasUserId => UserId is not null;
public bool HasUsername => Username is not null;
public bool IsInvalid => !HasUserId && !HasUsername;
};
public record LogInDto(int? UserId, string? Username, string Password);
}