public class APIResponse
{
public APIResponse()
{
ErrorMessages = new List<string>();
}
public HttpStatusCode StatusCode { get; set; }
public bool IsSuccess { get; set; } = true;
public List<string> ErrorMessages { get; set; }
public object Result { get; set; }
}
public async Task<ActionResult<APIResponse>> GetProductById(int id)
{
try
{
if (id == 0)
{
_response.StatusCode = HttpStatusCode.BadRequest;
return BadRequest(_response);
}
var product = await _productRepository.GetById(id);
if (product == null)
{
_response.StatusCode = HttpStatusCode.NotFound;
return NotFound(_response);
}
_response.Result = product;
_response.StatusCode = HttpStatusCode.OK;
return Ok(_response);
}
catch (Exception ex)
{
_response.IsSuccess = false;
_response.ErrorMessages
= new List<string>() { ex.ToString() };
}
return _response;
}
public async Task<LoginResponseDTO> Login(LoginRequestDTO loginRequestDTO)
{
var user = _db.LocalUsers.FirstOrDefault(u => u.UserName.ToLower() == loginRequestDTO.UserName.ToLower()
&& u.Password == loginRequestDTO.Password);
if (user == null)
{
return null;
}
//if user was found generate JWT Token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(secretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
LoginResponseDTO loginResponseDTO = new LoginResponseDTO()
{
Token = tokenHandler.WriteToken(token),
User = user
};
return loginResponseDTO;
}
public class AuthController : Controller
{
private readonly IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
[HttpGet]
public IActionResult Login()
{
LoginRequestDTO obj = new();
return View(obj);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginRequestDTO obj)
{
APIResponse response = await _authService.LoginAsync<APIResponse>(obj);
if (response != null && response.IsSuccess)
{
LoginResponseDTO model = JsonConvert.DeserializeObject<LoginResponseDTO>(Convert.ToString(response.Result));
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(model.Token);
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, jwt.Claims.FirstOrDefault(u => u.Type == "name").Value));
identity.AddClaim(new Claim(ClaimTypes.Role, jwt.Claims.FirstOrDefault(u=>u.Type=="role").Value));
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
HttpContext.Session.SetString(SD.SessionToken, model.Token);
return RedirectToAction("Index","Home");
}
else
{
ModelState.AddModelError("CustomError", response.ErrorMessages.FirstOrDefault());
return View(obj);
}
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterationRequestDTO obj)
{
APIResponse result = await _authService.RegisterAsync<APIResponse>(obj);
if (result != null && result.IsSuccess)
{
return RedirectToAction("Login");
}
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
HttpContext.Session.SetString(SD.SessionToken, "");
return RedirectToAction("Index","Home");
}
public IActionResult AccessDenied()
{
return View();
}
}