Update Patch AccountController in API
All checks were successful
CI/CD Pipeline / Build and Deploy with Docker Compose (push) Successful in 3m3s
All checks were successful
CI/CD Pipeline / Build and Deploy with Docker Compose (push) Successful in 3m3s
This commit is contained in:
parent
33b52a84df
commit
366bc0c0d3
@ -2,6 +2,7 @@
|
|||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using phronCare.API.Models.Account;
|
using phronCare.API.Models.Account;
|
||||||
|
using phronCare.API.Models.Security; // Importá donde tengas ApplicationUser
|
||||||
|
|
||||||
namespace phronCare.API.Controllers
|
namespace phronCare.API.Controllers
|
||||||
{
|
{
|
||||||
@ -11,69 +12,41 @@ namespace phronCare.API.Controllers
|
|||||||
public class AccountController : ControllerBase
|
public class AccountController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly RoleManager<IdentityRole> _roleManager;
|
private readonly RoleManager<IdentityRole> _roleManager;
|
||||||
private readonly UserManager<IdentityUser> _userManager;
|
private readonly UserManager<ApplicationUser> _userManager;
|
||||||
|
|
||||||
public AccountController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
|
public AccountController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
|
||||||
{
|
{
|
||||||
_roleManager = roleManager;
|
_roleManager = roleManager;
|
||||||
_userManager = userManager;
|
_userManager = userManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Endpoint para obtener todos los roles
|
|
||||||
[HttpGet("GetAllRoles")]
|
[HttpGet("GetAllRoles")]
|
||||||
public IActionResult GetAllRoles()
|
public IActionResult GetAllRoles()
|
||||||
{
|
{
|
||||||
var roles = _roleManager.Roles.ToList();
|
var roles = _roleManager.Roles.ToList();
|
||||||
return Ok(roles);
|
return Ok(roles);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("GetRoleById/{id}")]
|
[HttpGet("GetRoleById/{id}")]
|
||||||
public IActionResult GetRoleById(string id)
|
public IActionResult GetRoleById(string id)
|
||||||
{
|
{
|
||||||
var role = _roleManager.Roles
|
var role = _roleManager.Roles.FirstOrDefault(r => r.Id == id.TrimStart('{').TrimEnd('}'));
|
||||||
.Where(_ => _.Id == id.TrimStart('{').TrimEnd('}'))
|
|
||||||
.FirstOrDefault();
|
|
||||||
return Ok(role);
|
return Ok(role);
|
||||||
}
|
}
|
||||||
[HttpPut("UpdateRole/{id}")]
|
|
||||||
public async Task<IActionResult> UpdateRole(string id, Role model)
|
|
||||||
{
|
|
||||||
var role = await _roleManager.FindByIdAsync(id);
|
|
||||||
if (role == null)
|
|
||||||
{
|
|
||||||
return NotFound("Rol no encontrado");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Actualizar propiedades del rol
|
|
||||||
role.Name = model.Name;
|
|
||||||
role.NormalizedName = model.NormalizedName;
|
|
||||||
|
|
||||||
// Actualizar el rol en la base de datos
|
|
||||||
var result = await _roleManager.UpdateAsync(role);
|
|
||||||
|
|
||||||
if (result.Succeeded)
|
|
||||||
{
|
|
||||||
return Ok("Rol actualizado exitosamente");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return BadRequest("Error al actualizar el rol");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[HttpPost("CreateRole")]
|
[HttpPost("CreateRole")]
|
||||||
public async Task<IActionResult> CreateRole(Role model)
|
public async Task<IActionResult> CreateRole(Role model)
|
||||||
{
|
{
|
||||||
// Verifica si el rol ya existe
|
|
||||||
var existingRole = await _roleManager.FindByNameAsync(model.Name);
|
var existingRole = await _roleManager.FindByNameAsync(model.Name);
|
||||||
if (existingRole != null)
|
if (existingRole != null)
|
||||||
{
|
{
|
||||||
return BadRequest("El rol ya existe.");
|
return BadRequest("El rol ya existe.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea un nuevo rol
|
|
||||||
var newRole = new IdentityRole
|
var newRole = new IdentityRole
|
||||||
{
|
{
|
||||||
Name = model.Name,
|
Name = model.Name,
|
||||||
NormalizedName = model.Name.ToUpper(), // Normaliza el nombre, generalmente a mayúsculas
|
NormalizedName = model.Name.ToUpper(),
|
||||||
ConcurrencyStamp = Guid.NewGuid().ToString()
|
ConcurrencyStamp = Guid.NewGuid().ToString()
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -85,30 +58,51 @@ namespace phronCare.API.Controllers
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Manejar errores en la creación del rol
|
|
||||||
var errors = result.Errors.Select(e => e.Description);
|
var errors = result.Errors.Select(e => e.Description);
|
||||||
return BadRequest("Error al crear el rol: " + string.Join(", ", errors));
|
return BadRequest($"Error al crear el rol: {string.Join(", ", errors)}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Endpoint para eliminar un rol
|
|
||||||
[HttpDelete("DeleteRole/{roleId}")]
|
[HttpPut("UpdateRole/{id}")]
|
||||||
public IActionResult DeleteRole(string roleId)
|
public async Task<IActionResult> UpdateRole(string id, Role model)
|
||||||
{
|
{
|
||||||
// Verifica si el rol existe
|
var role = await _roleManager.FindByIdAsync(id);
|
||||||
var existingRole = _roleManager.FindByIdAsync(roleId).Result;
|
if (role == null)
|
||||||
|
{
|
||||||
|
return NotFound("Rol no encontrado");
|
||||||
|
}
|
||||||
|
|
||||||
|
role.Name = model.Name;
|
||||||
|
role.NormalizedName = model.NormalizedName;
|
||||||
|
|
||||||
|
var result = await _roleManager.UpdateAsync(role);
|
||||||
|
|
||||||
|
if (result.Succeeded)
|
||||||
|
{
|
||||||
|
return Ok("Rol actualizado exitosamente");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return BadRequest("Error al actualizar el rol");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("DeleteRole/{roleId}")]
|
||||||
|
public async Task<IActionResult> DeleteRole(string roleId)
|
||||||
|
{
|
||||||
|
var existingRole = await _roleManager.FindByIdAsync(roleId);
|
||||||
if (existingRole == null)
|
if (existingRole == null)
|
||||||
{
|
{
|
||||||
return NotFound("El rol no se encontró.");
|
return NotFound("El rol no se encontró.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Evita la eliminación del rol "Admin"
|
|
||||||
if (existingRole.Name.ToLower() == "admin")
|
if (existingRole.Name.ToLower() == "admin")
|
||||||
{
|
{
|
||||||
return BadRequest("No se puede eliminar el rol 'Admin'.");
|
return BadRequest("No se puede eliminar el rol 'Admin'.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Realiza la eliminación del rol en la base de datos
|
var result = await _roleManager.DeleteAsync(existingRole);
|
||||||
var result = _roleManager.DeleteAsync(existingRole).Result;
|
|
||||||
if (result.Succeeded)
|
if (result.Succeeded)
|
||||||
{
|
{
|
||||||
return Ok("El rol se eliminó exitosamente.");
|
return Ok("El rol se eliminó exitosamente.");
|
||||||
@ -118,43 +112,42 @@ namespace phronCare.API.Controllers
|
|||||||
return BadRequest("Error al eliminar el rol.");
|
return BadRequest("Error al eliminar el rol.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Endpoint para obtener todos los usuarios
|
|
||||||
[HttpGet("GetAllUsers")]
|
[HttpGet("GetAllUsers")]
|
||||||
public IActionResult GetAllUsers()
|
public IActionResult GetAllUsers()
|
||||||
{
|
{
|
||||||
var users = _userManager.Users.ToList();
|
var users = _userManager.Users.ToList();
|
||||||
return Ok(users);
|
return Ok(users);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("GetUserById/{id}")]
|
[HttpGet("GetUserById/{id}")]
|
||||||
public IActionResult GetUserById(string id)
|
public IActionResult GetUserById(string id)
|
||||||
{
|
{
|
||||||
var user = _userManager.Users
|
var user = _userManager.Users.FirstOrDefault(u => u.Id == id.TrimStart('{').TrimEnd('}'));
|
||||||
.Where(_ => _.Id == id.TrimStart('{').TrimEnd('}'))
|
|
||||||
.FirstOrDefault();
|
|
||||||
return Ok(user);
|
return Ok(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPut("UpdateUser/{id}")]
|
[HttpPut("UpdateUser/{id}")]
|
||||||
public async Task<IActionResult> UpdateUser(string id, UserUpdate? model)
|
public async Task<IActionResult> UpdateUser(string id, UserUpdate model)
|
||||||
{
|
{
|
||||||
var user = await _userManager.FindByIdAsync(id);
|
var user = await _userManager.FindByIdAsync(id);
|
||||||
if (user == null)
|
if (user == null)
|
||||||
{
|
{
|
||||||
return NotFound("Usuario no encontrado");
|
return NotFound("Usuario no encontrado");
|
||||||
}
|
}
|
||||||
// Actualizar propiedades del rol
|
|
||||||
user.UserName = model.UserName;
|
user.UserName = model.UserName;
|
||||||
user.NormalizedUserName = model.UserName.ToLower();
|
user.NormalizedUserName = model.UserName.ToUpper();
|
||||||
user.Email = model.Email;
|
user.Email = model.Email;
|
||||||
user.NormalizedEmail = model.Email.ToLower();
|
user.NormalizedEmail = model.Email.ToUpper();
|
||||||
user.TwoFactorEnabled = model.TwoFactorEnabled;
|
user.TwoFactorEnabled = model.TwoFactorEnabled;
|
||||||
user.LockoutEnabled = model.LockoutEnabled;
|
user.LockoutEnabled = model.LockoutEnabled;
|
||||||
|
|
||||||
// Actualizar el usuario en la base de datos
|
|
||||||
var result = await _userManager.UpdateAsync(user);
|
var result = await _userManager.UpdateAsync(user);
|
||||||
|
|
||||||
if (result.Succeeded)
|
if (result.Succeeded)
|
||||||
{
|
{
|
||||||
return Ok("usuario actualizado exitosamente");
|
return Ok("Usuario actualizado exitosamente");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@ -162,25 +155,22 @@ namespace phronCare.API.Controllers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Endpoint para eliminar un usuario
|
|
||||||
[HttpDelete("DeleteUser/{userId}")]
|
[HttpDelete("DeleteUser/{userId}")]
|
||||||
public IActionResult DeleteUser(string UserId)
|
public async Task<IActionResult> DeleteUser(string userId)
|
||||||
{
|
{
|
||||||
// Verifica si el usuario existe
|
var existingUser = await _userManager.FindByIdAsync(userId);
|
||||||
var existingUser = _userManager.FindByIdAsync(UserId).Result;
|
|
||||||
if (existingUser == null)
|
if (existingUser == null)
|
||||||
{
|
{
|
||||||
return NotFound("El usuario no se encontró.");
|
return NotFound("El usuario no se encontró.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Evita la eliminación del usuario "SuperAdmin"
|
if (existingUser.UserName.ToLower() == "superadmin")
|
||||||
if (existingUser.UserName.ToLower() == "superdmin")
|
|
||||||
{
|
{
|
||||||
return BadRequest("No se puede eliminar el usuario 'SuperAdmin'.");
|
return BadRequest("No se puede eliminar el usuario 'SuperAdmin'.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Realiza la eliminación del rol en la base de datos
|
var result = await _userManager.DeleteAsync(existingUser);
|
||||||
var result = _userManager.DeleteAsync(existingUser).Result;
|
|
||||||
if (result.Succeeded)
|
if (result.Succeeded)
|
||||||
{
|
{
|
||||||
return Ok("El usuario se eliminó exitosamente.");
|
return Ok("El usuario se eliminó exitosamente.");
|
||||||
|
|||||||
@ -156,15 +156,16 @@ builder.Services.AddCors(options =>
|
|||||||
/*
|
/*
|
||||||
Version para despliegue
|
Version para despliegue
|
||||||
*/
|
*/
|
||||||
policy
|
// policy
|
||||||
.WithOrigins("http://dev.biodec.saludlab.com.ar", "http://phroncareUI:80", "http://192.168.10.110:9002")
|
// .WithOrigins("http://dev.biodec.saludlab.com.ar", "http://phroncareUI:80", "http://192.168.10.110:9002")
|
||||||
.AllowAnyMethod()
|
// .AllowAnyMethod()
|
||||||
.AllowAnyHeader()
|
// .AllowAnyHeader()
|
||||||
.AllowCredentials();
|
// .AllowCredentials();
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Version para desarrollo
|
Version para desarrollo
|
||||||
*/
|
*/
|
||||||
//policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
|
policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@ -40,7 +40,7 @@
|
|||||||
"Order": 0,
|
"Order": 0,
|
||||||
"Parameters": [
|
"Parameters": [
|
||||||
{
|
{
|
||||||
"Name": "UserId",
|
"Name": "userId",
|
||||||
"Type": "System.String",
|
"Type": "System.String",
|
||||||
"IsRequired": true
|
"IsRequired": true
|
||||||
}
|
}
|
||||||
@ -136,7 +136,7 @@
|
|||||||
{
|
{
|
||||||
"Name": "model",
|
"Name": "model",
|
||||||
"Type": "phronCare.API.Models.Account.UserUpdate",
|
"Type": "phronCare.API.Models.Account.UserUpdate",
|
||||||
"IsRequired": false
|
"IsRequired": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"ReturnTypes": []
|
"ReturnTypes": []
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user