add exception filter when user not connected default to needing authentication and apply anonymous to some actions add user in get requests add user relation in link, comment and vote signup and in are ok now!
100 lines
2.5 KiB
C#
100 lines
2.5 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using HN.Infrastructure;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Website.Models;
|
|
|
|
namespace Website.Controllers
|
|
{
|
|
public sealed class AccountsController : BaseController
|
|
{
|
|
private readonly UserManager<User> _userManager;
|
|
private readonly SignInManager<User> _signInManager;
|
|
|
|
public AccountsController(UserManager<User> userManager, SignInManager<User> signInManager)
|
|
{
|
|
_userManager = userManager;
|
|
_signInManager = signInManager;
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
public IActionResult Register()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
[HttpPost]
|
|
[ValidateAntiForgeryToken]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> Register(RegisterViewModel command)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return View(command);
|
|
}
|
|
|
|
var user = new User(command.Username);
|
|
var result = await _userManager.CreateAsync(user, command.Password);
|
|
|
|
if (!result.Succeeded)
|
|
{
|
|
ModelState.AddModelError(nameof(RegisterViewModel.Username), string.Join(", ", result.Errors.Select(e => e.Description)));
|
|
return View(command);
|
|
}
|
|
|
|
SetFlash("Account created, you can now sign in!");
|
|
|
|
return RedirectToAction(nameof(Login));
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
public IActionResult Login()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
[HttpPost]
|
|
[ValidateAntiForgeryToken]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> Login(LoginViewModel command)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return View();
|
|
}
|
|
|
|
var user = await _userManager.FindByNameAsync(command.Username);
|
|
|
|
if (user == null)
|
|
{
|
|
ModelState.AddModelError(nameof(LoginViewModel.Username), "Could not verify user identity");
|
|
return View();
|
|
}
|
|
|
|
var result = await _signInManager.PasswordSignInAsync(user, command.Password, true, false);
|
|
|
|
if (!result.Succeeded)
|
|
{
|
|
ModelState.AddModelError(nameof(LoginViewModel.Username), "Could not verify user identity");
|
|
return View();
|
|
}
|
|
|
|
SetFlash("Successfuly connected!");
|
|
|
|
return RedirectToAction(nameof(LinksController.Index), "Links");
|
|
}
|
|
|
|
[HttpPost]
|
|
[ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
await _signInManager.SignOutAsync();
|
|
|
|
SetFlash("Successfuly disconnected!");
|
|
|
|
return RedirectToAction(nameof(Login));
|
|
}
|
|
}
|
|
} |