94 lines
2.3 KiB
C#
94 lines
2.3 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using System.Web.Mvc;
|
|
using AutoMapper;
|
|
using AutoMapper.QueryableExtensions;
|
|
using InventoryTraker.Web.Attributes;
|
|
using InventoryTraker.Web.Core;
|
|
using InventoryTraker.Web.Identity;
|
|
using InventoryTraker.Web.Models;
|
|
using Microsoft.AspNet.Identity;
|
|
using Microsoft.AspNet.Identity.Owin;
|
|
using Microsoft.Owin.Security.DataProtection;
|
|
|
|
namespace InventoryTraker.Web.Controllers
|
|
{
|
|
public class UserController : ControllerBase
|
|
{
|
|
private readonly ApplicationUserManager _userManager;
|
|
|
|
public UserController(ApplicationUserManager userManager)
|
|
{
|
|
_userManager = userManager;
|
|
}
|
|
|
|
public ActionResult Index()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
public JsonResult All()
|
|
{
|
|
var users =
|
|
_userManager
|
|
.Users
|
|
.ProjectTo<UserViewModel>()
|
|
.OrderBy(u => u.UserName);
|
|
|
|
return BetterJson(users);
|
|
}
|
|
|
|
[ActionLog]
|
|
[HttpPost]
|
|
public async Task<JsonResult> Create(UserEditForm form)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
return GetModelStateErrorListJson();
|
|
|
|
var user =
|
|
new User
|
|
{
|
|
Email = form.Email,
|
|
UserName = form.UserName
|
|
};
|
|
|
|
var identityResult = await _userManager.CreateAsync(user, form.Password);
|
|
|
|
if (!identityResult.Succeeded)
|
|
return GetErrorListJson(identityResult.Errors.ToArray());
|
|
|
|
return BetterJson(Mapper.Map<UserViewModel>(user));
|
|
}
|
|
|
|
[ActionLog]
|
|
[HttpPost]
|
|
public async Task<JsonResult> Edit(UserEditForm form)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
return GetModelStateErrorListJson();
|
|
|
|
var user = _userManager.FindByEmail(form.Email);
|
|
|
|
user.UserName = form.UserName;
|
|
user.Email = form.Email;
|
|
|
|
if (!string.IsNullOrEmpty(form.Password))
|
|
{
|
|
var provider = new DpapiDataProtectionProvider("Inventory Traker");
|
|
_userManager.UserTokenProvider = new DataProtectorTokenProvider<User>(
|
|
provider.Create("EmailConfirmation"));
|
|
var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user.Id);
|
|
var resetResult = await _userManager.ResetPasswordAsync(user.Id, resetToken, form.Password);
|
|
if (!resetResult.Succeeded)
|
|
return GetErrorListJson(resetResult.Errors.ToArray());
|
|
}
|
|
|
|
var identityResult = _userManager.Update(user);
|
|
|
|
if (!identityResult.Succeeded)
|
|
return GetErrorListJson(identityResult.Errors.ToArray());
|
|
|
|
return BetterJson(Mapper.Map<UserViewModel>(user));
|
|
}
|
|
}
|
|
} |