53 lines
No EOL
1.6 KiB
C#
53 lines
No EOL
1.6 KiB
C#
using System.Security.Claims;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Website.Data;
|
|
using Website.Models;
|
|
using Website.ViewModels;
|
|
|
|
namespace Website.Controllers {
|
|
public class AccountController:Controller {
|
|
private readonly UserRepository _repo;
|
|
|
|
public AccountController(UserRepository repo) => _repo = repo;
|
|
|
|
public IActionResult Index() => View();
|
|
|
|
[HttpGet]
|
|
public IActionResult Login(string returnUrl, bool failedAttempt = false) {
|
|
var model = new LoginViewModel {
|
|
ReturnUrl = returnUrl,
|
|
FailedAttempt = failedAttempt
|
|
};
|
|
return View(model);
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<IActionResult> Login(LoginRequest request) {
|
|
try {
|
|
var user = await _repo.GetUserByEmail(request.Username);
|
|
return user.ValidatePassword(request.Password)
|
|
? await SetIdentityAndRedirect(request.ReturnUrl, user)
|
|
: Login(request.ReturnUrl, true);
|
|
}
|
|
catch {
|
|
return Login(request.ReturnUrl, true);
|
|
}
|
|
}
|
|
|
|
private async Task<IActionResult> SetIdentityAndRedirect(string returnUrl, User user) {
|
|
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
|
|
identity.AddClaim(new Claim(ClaimTypes.Email, user.Username));
|
|
|
|
var principal = new ClaimsPrincipal(identity);
|
|
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
|
|
|
|
return string.IsNullOrEmpty(returnUrl)
|
|
? (IActionResult) RedirectToAction(nameof(Index))
|
|
: Redirect(returnUrl);
|
|
}
|
|
}
|
|
} |