Add authentication
This commit is contained in:
parent
8f0c4c0a45
commit
a2d84e182d
11 changed files with 206 additions and 21 deletions
54
Website/Controllers/AccountController.cs
Normal file
54
Website/Controllers/AccountController.cs
Normal file
|
@ -0,0 +1,54 @@
|
|||
using System;
|
||||
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 (Exception e) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue