80 lines
1.8 KiB
C#
80 lines
1.8 KiB
C#
|
using Microsoft.AspNetCore.Authorization;
|
||
|
using Microsoft.AspNetCore.Identity;
|
||
|
using Microsoft.AspNetCore.Mvc;
|
||
|
using MyDarling.Models;
|
||
|
|
||
|
namespace MyDarling.Controllers;
|
||
|
|
||
|
public class AccountController : Controller
|
||
|
{
|
||
|
public UserManager<IdentityUser> UserManager { get; set; }
|
||
|
private SignInManager<IdentityUser> SignInManager;
|
||
|
|
||
|
public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
|
||
|
{
|
||
|
UserManager = userManager;
|
||
|
SignInManager = signInManager;
|
||
|
}
|
||
|
|
||
|
public IActionResult List()
|
||
|
{
|
||
|
return View(UserManager.Users);
|
||
|
}
|
||
|
|
||
|
public IActionResult Create()
|
||
|
{
|
||
|
return View(new IdentityUser());
|
||
|
}
|
||
|
|
||
|
[HttpPost]
|
||
|
public async Task<IActionResult> Create([Bind] IdentityUser user, [Bind] string Password)
|
||
|
{
|
||
|
if (ModelState.IsValid)
|
||
|
{
|
||
|
IdentityResult result = await UserManager.CreateAsync(user, Password);
|
||
|
if (result.Succeeded)
|
||
|
{
|
||
|
return RedirectToAction(nameof(List));
|
||
|
}
|
||
|
|
||
|
foreach (IdentityError error in result.Errors)
|
||
|
{
|
||
|
ModelState.AddModelError("", error.Description);
|
||
|
}
|
||
|
}
|
||
|
return View();
|
||
|
}
|
||
|
|
||
|
public ViewResult Login(string returlUrl)
|
||
|
{
|
||
|
return View(new LoginModel { ReturnUrl = returlUrl });
|
||
|
}
|
||
|
|
||
|
[HttpPost]
|
||
|
public async Task<IActionResult> Login(LoginModel loginModel)
|
||
|
{
|
||
|
if (ModelState.IsValid)
|
||
|
{
|
||
|
IdentityUser user = await UserManager.FindByNameAsync(loginModel.Name);
|
||
|
if (user != null)
|
||
|
{
|
||
|
await SignInManager.SignOutAsync();
|
||
|
if ((await SignInManager.PasswordSignInAsync(user,
|
||
|
loginModel.Password, false, false))
|
||
|
.Succeeded)
|
||
|
{
|
||
|
return Redirect(loginModel?.ReturnUrl ?? "/Bundle");
|
||
|
}
|
||
|
}
|
||
|
ModelState.AddModelError("", "Invalid name or password");
|
||
|
}
|
||
|
return View(loginModel);
|
||
|
}
|
||
|
|
||
|
[Authorize]
|
||
|
public async Task<RedirectResult> Logout(string returlUrl = "/Account/Login")
|
||
|
{
|
||
|
await SignInManager.SignOutAsync();
|
||
|
return Redirect(returlUrl);
|
||
|
}
|
||
|
}
|