Retail_manager/RMDataManager/Controllers/UserController.cs
2022-08-22 00:12:27 +02:00

100 lines
3.1 KiB
C#

using RMDataManagerLibrary.DataAcccess;
using System.Collections.Generic;
using System.Web.Http;
using RMDataManagerLibrary.Models;
using System.Web;
using Microsoft.AspNet.Identity;
using System.Linq;
using Microsoft.AspNet.Identity.EntityFramework;
using RMDataManager.Models;
namespace RMDataManager.Controllers
{
[Authorize]
public class UserController : ApiController
{
[HttpGet]
public UserModel GetById()
{
string userId = RequestContext.Principal.Identity.GetUserId();
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>();
using (var context = new ApplicationDbContext())
{
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var users = userManager.Users.ToList();
var roles = context.Roles.ToList();
foreach (var user in users)
{
ApplicationUserModel u = new ApplicationUserModel
{
Id = user.Id,
EmailAddress = user.Email
};
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()
{
using (var context = new ApplicationDbContext())
{
var roles = context.Roles.ToDictionary(x => x.Id, x => x.Name);
return roles;
}
}
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("api/User/Admin/AddRole")]
public void AddRole(UserRolePairModel pair)
{
using (var context = new ApplicationDbContext())
{
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(pair.UserId, pair.RoleName);
}
}
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("api/User/Admin/RemoveRole")]
public void RemoveRole(UserRolePairModel pair)
{
using (var context = new ApplicationDbContext())
{
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.RemoveFromRole(pair.UserId, pair.RoleName);
}
}
}
}