Retail_manager/RMApi/Controllers/UserController.cs

100 lines
3.1 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using RMApi.Data;
using RMApi.Models;
using RMDataManagerLibrary.DataAcccess;
using RMDataManagerLibrary.Models;
using System.Security.Claims;
namespace RMApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
public UserController(ApplicationDbContext context, UserManager<IdentityUser> userManager)
{
_context = context;
_userManager = userManager;
}
[HttpGet]
public UserModel GetById()
{
string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
UserData data = new UserData();
return data.GetUserById(userId).First();
}
[Authorize(Roles = "Admin")]
[HttpGet]
[Route("api/User/Admin/GetAllUsers")]
public List<ApplicationUserModel> GetAllUsers()
{
List<ApplicationUserModel> output = new List<ApplicationUserModel>();
var users = _context.Users.ToList();
var userRoles = from ur in _context.UserRoles
join r in _context.Roles on ur.RoleId equals r.Id
select new { ur.UserId, ur.RoleId, r.Name };
foreach (var user in users)
{
ApplicationUserModel u = new ApplicationUserModel
{
Id = user.Id,
EmailAddress = user.Email
};
u.Roles = userRoles.Where(x => x.UserId == u.Id).ToDictionary(key => key.RoleId, val => val.Name);
//foreach (var role in user.Roles)
//{
// u.Roles.Add(role.RoleId, roles.Where(x => x.Id == role.RoleId).First().Name);
//}
output.Add(u);
}
return output;
}
[Authorize(Roles = "Admin")]
[HttpGet]
[Route("api/User/Admin/GetAllRoles")]
public Dictionary<string, string> GetAllRoles()
{
var roles = _context.Roles.ToDictionary(x => x.Id, x => x.Name);
return roles;
}
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("api/User/Admin/AddRole")]
public async Task AddRole(UserRolePairModel pair)
{
var user = await _userManager.FindByIdAsync(pair.UserId);
await _userManager.AddToRoleAsync(user, pair.RoleName);
}
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("api/User/Admin/RemoveRole")]
public async Task RemoveRole(UserRolePairModel pair)
{
var user = await _userManager.FindByIdAsync(pair.UserId);
await _userManager.RemoveFromRoleAsync(user, pair.RoleName);
}
}
}