Добавить регистрацию

***
- Добавил регистрацию нового пользователя.
- Прокинул в DI AccountService.
***
parent 91daa311
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PhoneStore.Enums;
using PhoneStore.Helpers;
using PhoneStore.Services.Abstractions;
using PhoneStore.ViewModels.Account;
namespace PhoneStore.Controllers
{
public class AccountController : Controller
{
private readonly IAccountService _accountService;
public AccountController(IAccountService accountService)
{
_accountService = accountService;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
return View(model);
var result = await _accountService.Register(model);
if (result.StatusCodes == StatusCodes.Success)
return RedirectToAction("Index", "Phones");
if (result.ErrorMessages.Any())
ModelState.AddErrors(result.ErrorMessages);
return View(model);
}
}
}
\ No newline at end of file
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PhoneStore.Services.Abstractions;
using Order = PhoneStore.Enums.Order;
namespace PhoneStore.Controllers
{
public class UsersController : Controller
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
public async Task<IActionResult> Index(string filterByName, Order order = Order.AgeAsc, int page = 1)
{
ViewBag.NameSort = order == Order.NameAsc ? Order.NameDesc : Order.NameAsc;
ViewBag.AgeSort = order == Order.AgeAsc ? Order.AgeDesc : Order.AgeAsc;
var model = await _userService.GetAll(order, filterByName, page);
return View(model);
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using PhoneStore.Enums;
namespace PhoneStore.DataObjects
{
public class IdentityResult
{
public List<string> ErrorMessages { get; set; }
public StatusCodes StatusCodes { get; set; }
}
}
\ No newline at end of file
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace PhoneStore.Helpers
{
public static class ModelStateHelper
{
public static void AddErrors(this ModelStateDictionary self, List<string> errors)
{
errors.ForEach(e =>
{
self.AddModelError(string.Empty, e);
});
}
}
}
\ No newline at end of file
......@@ -21,6 +21,7 @@ namespace PhoneStore.Helpers
services.AddTransient<IUsersSortService, UsersSortService>();
services.AddTransient<IUsersFilter, UsersFilter>();
services.AddTransient<IPaginationService<User>, PaginationService<User>>();
services.AddTransient<IAccountService, AccountService>();
}
}
}
\ No newline at end of file
using System.Threading.Tasks;
using PhoneStore.DataObjects;
using PhoneStore.ViewModels.Account;
namespace PhoneStore.Services.Abstractions
{
public interface IAccountService
{
Task<IdentityResult> Register(RegisterViewModel model);
Task<IdentityResult> LogIn(LoginViewModel model);
Task<IdentityResult> LogOf();
}
}
\ No newline at end of file
using System.Threading.Tasks;
using PhoneStore.Enums;
using PhoneStore.ViewModels;
namespace PhoneStore.Services.Abstractions
{
public interface IUserService
{
Task<UsersViewModel> GetAll(Order order, string filterByName, int page);
}
}
\ No newline at end of file
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using PhoneStore.Enums;
using PhoneStore.Models;
using PhoneStore.Services.Abstractions;
using PhoneStore.ViewModels.Account;
using IdentityResult = PhoneStore.DataObjects.IdentityResult;
namespace PhoneStore.Services
{
public class AccountService : IAccountService
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
public AccountService(
UserManager<User> userManager,
SignInManager<User> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public async Task<IdentityResult> Register(RegisterViewModel model)
{
User user = new User
{
Email = model.Email,
UserName = model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, "user");
await _signInManager.SignInAsync(user, false);
return new IdentityResult{StatusCodes = StatusCodes.Success};
}
var errors = result.Errors.Select(error => error.Description).ToList();
return new IdentityResult
{
ErrorMessages = errors,
StatusCodes = StatusCodes.Error
};
}
public Task<IdentityResult> LogIn(LoginViewModel model)
{
throw new System.NotImplementedException();
}
public Task<IdentityResult> LogOf()
{
throw new System.NotImplementedException();
}
}
}
\ No newline at end of file
using System.ComponentModel.DataAnnotations;
namespace PhoneStore.ViewModels.Account
{
public class LoginViewModel
{
private const string RequiredErrorMessage = "Поле обязательно для заполнения";
[Required(ErrorMessage = RequiredErrorMessage)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = RequiredErrorMessage)]
[DataType(DataType.Password)]
[Display(Name = "Пароль")]
public string Password { get; set; }
[Display(Name = "Запомнить?")]
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
}
\ No newline at end of file
using System.ComponentModel.DataAnnotations;
namespace PhoneStore.ViewModels.Account
{
public class RegisterViewModel
{
//TODO: Добавить ограничение по минимальной и максимальной длине строк и возраста.
private const string RequiredErrorMessage = "Поле обязательно для заполнения";
[Required(ErrorMessage = RequiredErrorMessage)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = RequiredErrorMessage)]
[Display(Name = "Возраст")]
public int Age { get; set; }
[Required(ErrorMessage = RequiredErrorMessage)]
[Display(Name = "Имя")]
public string Name { get; set; }
[Required(ErrorMessage = RequiredErrorMessage)]
[DataType(DataType.Password)]
[Display(Name = "Пароль")]
public string Password { get; set; }
[Required(ErrorMessage = RequiredErrorMessage)]
[Compare(nameof(Password), ErrorMessage = "Пароли не совпадают")]
[DataType(DataType.Password)]
[Display(Name = "Подтвердить пароль")]
public string PasswordConfirm { get; set; }
}
}
\ No newline at end of file
@model RegisterViewModel
@{
ViewBag.Title = "title";
Layout = "_Layout";
}
<h2>Регистрация нового пользователя</h2>
<form method="post" asp-controller="Account" asp-action="Register">
<div asp-validation-summary="ModelOnly"></div>
<div>
<label asp-for="Email"></label><br />
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
</div>
<div>
<label asp-for="Name"></label><br />
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
</div>
<div>
<label asp-for="Age"></label><br />
<input asp-for="Age" />
<span asp-validation-for="Age"></span>
</div>
<div>
<label asp-for="Password"></label><br />
<input asp-for="Password" />
<span asp-validation-for="Password"></span>
</div>
<div>
<label asp-for="PasswordConfirm"></label><br />
<input asp-for="PasswordConfirm" />
<span asp-validation-for="PasswordConfirm"></span>
</div>
<div>
<input type="submit" value="Регистрация" />
</div>
</form>
......@@ -27,9 +27,6 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Brands" asp-action="Create">Добавить бренд</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Users" asp-action="Index">Пользователи</a>
</li>
</ul>
</div>
</div>
......
@model UsersViewModel
@{
ViewBag.Title = "Пользователи";
Layout = "_Layout";
}
<h2>Список пользователей</h2>
<div class="row">
<div class="phone_add_form col-md-6">
<form asp-action="Index" asp-controller="Users" method="get">
<div class="form_row">
<label for="name">
Имя:
<input
id="name"
type="text"
name="filterByName"
value="@Model.Filter">
</label>
<input type="text" hidden name="page" value="@Model.PageViewModel.Page">
<button class="btn btn-outline-warning">Отправить</button>
</div>
</form>
</div>
</div>
<table style="width: 100%">
<tr>
<th>
<a
asp-action="Index"
asp-controller="Users"
asp-route-order="@ViewBag.NameSort"
asp-route-filterByName="@Model.Filter">
Имя
</a>
</th>
<th>
<a
asp-action="Index"
asp-controller="Users"
asp-route-order="@ViewBag.AgeSort"
asp-route-filterByName="@Model.Filter">
Возраст
</a>
</th>
</tr>
@foreach (var user in Model.Users)
{
<tr>
<td>@user.Name</td>
<td>@user.Age</td>
</tr>
}
</table>
<nav aria-label="Page navigation">
<ul class="pagination justify-content-left">
@if (Model.PageViewModel.HasPrevious)
{
<li class="page-item">
<a
asp-action="Index"
asp-controller="Users"
class="page-link"
asp-route-page="@(Model.PageViewModel.Page - 1)"
asp-route-filterByName="@Model.Filter">Previous</a>
</li>
}
@if (Model.PageViewModel.HasNext)
{
<li class="page-item">
<a
class="page-link"
asp-action="Index"
asp-controller="Users"
asp-route-page="@(Model.PageViewModel.Page + 1)"
asp-route-filterByName="@Model.Filter">Next</a>
</li>
}
</ul>
</nav>
\ No newline at end of file
@using PhoneStore
@using PhoneStore.Models
@using PhoneStore.ViewModels
@using PhoneStore.ViewModels.Account
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
\ No newline at end of file
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