97 lines
3.4 KiB
C#

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using System.DirectoryServices.AccountManagement;
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.UserManager.Application.DTOs.Auth;
namespace DigitalData.UserManager.API.Controllers
{
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private IUserService _userService;
private IGroupOfUserService _gouService;
public AuthController(IUserService userService, IGroupOfUserService gouService)
{
_userService = userService;
_gouService = gouService;
}
[AllowAnonymous]
[HttpGet("check")]
public IActionResult CheckAuthentication() => Ok(new AuthCheckDto(IsAuthenticated: User.Identity?.IsAuthenticated ?? false));
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LogInDto login)
{
using var context = new PrincipalContext(ContextType.Domain);
bool isValid = context.ValidateCredentials(login.Username, login.Password);
if (!isValid)
return Unauthorized(_userService.Failed(MessageKey.UserNotFound.ToString()));
var gouMsg = await _gouService.HasGroup(login.Username, "PM_USER", caseSensitive:false);
if(!gouMsg.IsSuccess)
return Unauthorized(_userService.Failed(MessageKey.UnauthorizedUser.ToString()));
//find the user
var uRes = await _userService.ReadByUsernameAsync(login.Username);
if (!uRes.IsSuccess || uRes.Data is null)
{
return Unauthorized(uRes);
}
UserReadDto user = uRes.Data;
// Create claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Guid.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Surname, user.Name ?? ""),
new Claim(ClaimTypes.GivenName, user.Prename ?? ""),
new Claim(ClaimTypes.Email, user.Email ?? ""),
new Claim(ClaimTypes.Role, "PM_USER")
};
// Create claimsIdentity
var claimsIdentity = new ClaimsIdentity(claims, 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(2);
}
[Authorize]
[HttpGet("user")]
public IActionResult GetUser() => Ok(User.Claims.ToList());
[AllowAnonymous]
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
}