92 lines
2.8 KiB
C#
92 lines
2.8 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using FaKrosnoApi.Models;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using OrdersManagementDataModel.Dtos;
|
|
using OrdersManagementDataModel.Services;
|
|
|
|
namespace FaKrosnoApi.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class UsersController(IUserService service, IConfiguration configuration) : Controller
|
|
{
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<UserDto>>> GetAll()
|
|
{
|
|
IEnumerable<UserDto?> users = await service.GetAll();
|
|
return Ok(users);
|
|
}
|
|
|
|
[HttpGet("by-id")]
|
|
public async Task<ActionResult<UserDto?>> GetById([FromQuery] Guid id)
|
|
{
|
|
UserDto? user = await service.GetById(id);
|
|
return user != null ? Ok(user) : NotFound();
|
|
}
|
|
|
|
[HttpGet("by-username")]
|
|
public async Task<ActionResult<UserDto?>> GetByUsername([FromQuery] string username)
|
|
{
|
|
UserDto? user = await service.GetByUsername(username);
|
|
return user != null ? Ok(user) : NotFound();
|
|
}
|
|
|
|
[HttpPost("login")]
|
|
public async Task<IActionResult> Login([FromBody] AuthenticateRequestModel loginDto)
|
|
{
|
|
// Sprawdź poprawność użytkownika (np. w bazie danych)
|
|
var user = await service.GetByUsername(loginDto.Login);
|
|
|
|
if(user == null || !BCrypt.Net.BCrypt.Verify(loginDto.Password, user.PasswordHash))
|
|
{
|
|
return Unauthorized("Nieprawidłowa nazwa użytkownika lub hasło.");
|
|
}
|
|
|
|
var claims = new[]
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, user.Login),
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: configuration["Jwt:Issuer"],
|
|
audience: configuration["Jwt:Audience"],
|
|
claims: claims,
|
|
expires: DateTime.Now.AddHours(1), // Token ważny przez 1 godzinę
|
|
signingCredentials: creds);
|
|
|
|
return Ok(new
|
|
{
|
|
token = new JwtSecurityTokenHandler().WriteToken(token),
|
|
expires = token.ValidTo
|
|
});
|
|
}
|
|
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<UserDto>> Add([FromBody] UserDto user)
|
|
{
|
|
await service.Add(user);
|
|
return Ok(user);
|
|
}
|
|
|
|
[HttpPut]
|
|
public async Task<ActionResult<UserDto>> Update([FromBody] UserDto user)
|
|
{
|
|
await service.Update(user);
|
|
return Ok(user);
|
|
}
|
|
|
|
[HttpDelete]
|
|
public async Task<ActionResult<UserDto>> Delete([FromQuery] Guid id)
|
|
{
|
|
await service.Delete(id);
|
|
return Ok();
|
|
}
|
|
} |