152 lines
5.7 KiB
C#
152 lines
5.7 KiB
C#
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using DigitalData.UserManager.Application.Contracts;
|
|
using DigitalData.UserManager.Application.DTOs.User;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using DigitalData.UserManager.Application;
|
|
using DigitalData.Core.Abstractions.Application;
|
|
using Microsoft.Extensions.Localization;
|
|
using DigitalData.Core.DTO;
|
|
using WorkFlow.API.Models;
|
|
|
|
namespace WorkFlow.API.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class AuthController(IUserService userService, IGroupOfUserService gouService, IDirectorySearchService directorySearchService, IStringLocalizer<Resource> localizer, ILogger<AuthController> logger) : ControllerBase
|
|
{
|
|
private readonly IUserService _userService = userService;
|
|
private readonly IGroupOfUserService _gouService = gouService;
|
|
private readonly IDirectorySearchService _dirSearchService = directorySearchService;
|
|
private readonly IStringLocalizer<Resource> _localizer = localizer;
|
|
private readonly ILogger<AuthController> _logger = logger;
|
|
|
|
[AllowAnonymous]
|
|
[HttpGet("check")]
|
|
public IActionResult CheckAuthentication()
|
|
{
|
|
try
|
|
{
|
|
return Ok(User.Identity?.IsAuthenticated ?? false);
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
_logger.LogError(ex, "{Message}", ex.Message);
|
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[HttpPost("login")]
|
|
public async Task<IActionResult> Login([FromBody] Login login)
|
|
{
|
|
try
|
|
{
|
|
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(username, "PM_USER", caseSensitive: false);
|
|
if (!gouMsg.IsSuccess)
|
|
return Unauthorized(Result.Fail().Message(_localizer[Key.UnauthorizedUser]));
|
|
|
|
//find the user
|
|
uRes ??= await _userService.ReadByUsernameAsync(username);
|
|
if (!uRes.IsSuccess || uRes.Data is null)
|
|
{
|
|
_logger.LogNotice(uRes.Notices);
|
|
return Unauthorized();
|
|
}
|
|
|
|
UserReadDto user = uRes.Data;
|
|
|
|
// Create claimsIdentity
|
|
var claimsIdentity = new ClaimsIdentity(user.ToClaimList(), CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
// 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);
|
|
|
|
return Ok();
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
_logger.LogError(ex, "{Message}", ex.Message);
|
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpGet("user")]
|
|
public async Task<IActionResult> GetUserWithClaims()
|
|
{
|
|
try
|
|
{
|
|
// 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);
|
|
}
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPost("logout")]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
try
|
|
{
|
|
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
return Ok();
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
_logger.LogError(ex, "{Message}", ex.Message);
|
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
}
|
|
} |