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

parent 4798cd91
......@@ -2,6 +2,7 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Store.Models;
using Store.Repositories.Interfaces;
using Store.ViewModels.Auths;
......@@ -35,7 +36,7 @@ public class AccountsController : Controller
{
if (user.Password.Equals(model.Password))
{
await Authenticate(user.Email);
await AuthenticateAsync(user.Email);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "пароль введен неверно");
......@@ -61,25 +62,56 @@ public class AccountsController : Controller
return View();
}
private async Task Authenticate(string userName)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel viewModel)
{
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()
{
var claims = new List<Claim>()
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
private async Task AuthenticateAsync(string userName)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, userName)
};
var id = new ClaimsIdentity(
ClaimsIdentity id = new ClaimsIdentity(
claims,
"ApplicationCookie",
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(id),
new AuthenticationProperties
{
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
public static void AddAppServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<AppDbContext>(opt =>
opt.UseNpgsql("ConnectionString"));
opt.UseNpgsql(configuration.GetConnectionString("ConnectionString")));
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opt =>
{
......
......@@ -2,7 +2,6 @@ using Store.Extensions;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var app = builder.Build();
var configuration = builder.Configuration;
// Add services to the container.
......@@ -10,6 +9,7 @@ services.AddControllersWithViews();
services.AddAppServices(configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
......@@ -22,7 +22,7 @@ app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
......
@model dynamic
@using Microsoft.AspNetCore.Mvc.TagHelpers
@model Store.ViewModels.Auths.RegisterViewModel
@{
ViewBag.Title = "title";
Layout = "_Layout";
ViewBag.Title = "Регистрация";
}
<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 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</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>
</div>
</div>
</nav>
</header>
<div class="container">
......
......@@ -7,6 +7,6 @@
},
"AllowedHosts": "*",
"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