Добавили регистрацию и подключили аутентификацию

parent 4798cd91
...@@ -2,6 +2,7 @@ using System.Security.Claims; ...@@ -2,6 +2,7 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Store.Models;
using Store.Repositories.Interfaces; using Store.Repositories.Interfaces;
using Store.ViewModels.Auths; using Store.ViewModels.Auths;
...@@ -35,7 +36,7 @@ public class AccountsController : Controller ...@@ -35,7 +36,7 @@ public class AccountsController : Controller
{ {
if (user.Password.Equals(model.Password)) if (user.Password.Equals(model.Password))
{ {
await Authenticate(user.Email); await AuthenticateAsync(user.Email);
return RedirectToAction("Index", "Home"); return RedirectToAction("Index", "Home");
} }
ModelState.AddModelError("", "пароль введен неверно"); ModelState.AddModelError("", "пароль введен неверно");
...@@ -61,25 +62,56 @@ public class AccountsController : Controller ...@@ -61,25 +62,56 @@ public class AccountsController : Controller
return View(); return View();
} }
private async Task Authenticate(string userName) [HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel viewModel)
{ {
var claims = new List<Claim>() if (ModelState.IsValid)
{
var user = _userRepository.GetUserByEmail(viewModel.Email);
if (user is null)
{
_userRepository.Create(new User
{
Email = viewModel.Email,
Password = viewModel.Password
});
_userRepository.Save();
await AuthenticateAsync(viewModel.Email);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "пользователь с таким email уже существует");
}
return View(viewModel);
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
private async Task AuthenticateAsync(string userName)
{
var claims = new List<Claim>
{ {
new Claim(ClaimsIdentity.DefaultNameClaimType, userName) new Claim(ClaimsIdentity.DefaultNameClaimType, userName)
}; };
ClaimsIdentity id = new ClaimsIdentity(
var id = new ClaimsIdentity(
claims, claims,
"ApplicationCookie", "ApplicationCookie",
ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType); ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(id), new ClaimsPrincipal(id),
new AuthenticationProperties new AuthenticationProperties
{ {
IsPersistent = true, IsPersistent = true,
ExpiresUtc = DateTimeOffset.Now.AddMinutes(1) ExpiresUtc = DateTime.UtcNow.AddMinutes(1)
}); }
);
} }
} }
\ No newline at end of file
...@@ -11,7 +11,7 @@ public static class ServicesAppExtension ...@@ -11,7 +11,7 @@ public static class ServicesAppExtension
public static void AddAppServices(this IServiceCollection services, IConfiguration configuration) public static void AddAppServices(this IServiceCollection services, IConfiguration configuration)
{ {
services.AddDbContext<AppDbContext>(opt => services.AddDbContext<AppDbContext>(opt =>
opt.UseNpgsql("ConnectionString")); opt.UseNpgsql(configuration.GetConnectionString("ConnectionString")));
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opt => .AddCookie(opt =>
{ {
......
...@@ -2,7 +2,6 @@ using Store.Extensions; ...@@ -2,7 +2,6 @@ using Store.Extensions;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
var services = builder.Services; var services = builder.Services;
var app = builder.Build();
var configuration = builder.Configuration; var configuration = builder.Configuration;
// Add services to the container. // Add services to the container.
...@@ -10,6 +9,7 @@ services.AddControllersWithViews(); ...@@ -10,6 +9,7 @@ services.AddControllersWithViews();
services.AddAppServices(configuration); services.AddAppServices(configuration);
var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
...@@ -22,7 +22,7 @@ app.UseHttpsRedirection(); ...@@ -22,7 +22,7 @@ app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllerRoute( app.MapControllerRoute(
......
@model dynamic @using Microsoft.AspNetCore.Mvc.TagHelpers
@model Store.ViewModels.Auths.RegisterViewModel
@{ @{
ViewBag.Title = "title"; ViewBag.Title = "Регистрация";
Layout = "_Layout";
} }
<h2>title</h2> <h2>Регистрация</h2>
<form asp-action="Register" asp-controller="Accounts" asp-anti-forgery="true">
<div class="validation" asp-validation-summary="ModelOnly"></div>
<div>
<div>
<label asp-for="Email">Введите Email</label><br />
<input type="text" asp-for="Email" />
<span asp-validation-for="Email"></span>
</div>
<div>
<label asp-for="Password">Введите пароль</label><br />
<input asp-for="Password" />
<span asp-validation-for="Password"></span>
</div>
<div>
<label asp-for="ConfirmPassword">Повторите пароль</label><br />
<input asp-for="ConfirmPassword" />
<span asp-validation-for="ConfirmPassword"></span>
</div>
<div>
<input type="submit" value="Регистрация" />
</div>
</div>
</form>
\ No newline at end of file
...@@ -25,9 +25,25 @@ ...@@ -25,9 +25,25 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li> </li>
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Accounts" asp-action="Logout">Выход</a>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Accounts" asp-action="Login">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Accounts" asp-action="Register">Регистрация</a>
</li>
}
</ul> </ul>
</div> </div>
</div> </div>
</nav> </nav>
</header> </header>
<div class="container"> <div class="container">
......
...@@ -7,6 +7,6 @@ ...@@ -7,6 +7,6 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"ConnectionString": "Server=localhost;Port=5432;Database=shops;UserId=postgres;" "ConnectionString": "Server=localhost;Port=5432;Database=auths;UserId=postgres;"
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment