dev #14

Merged
mfnefd merged 3 commits from dev into registration 2024-06-22 18:49:29 +04:00
12 changed files with 300 additions and 25 deletions

View File

@ -25,11 +25,14 @@ namespace BusinessLogic.BusinessLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IUserStorage _userStorage; private readonly IUserStorage _userStorage;
private readonly ITwoFactorAuthService _twoFactorAuthService;
public UserLogic(ILogger<UserLogic> logger, IUserStorage userStorage) public UserLogic(ILogger<UserLogic> logger, IUserStorage userStorage,
ITwoFactorAuthService twoFactorAuthService)
{ {
_logger = logger; _logger = logger;
_userStorage = userStorage; _userStorage = userStorage;
_twoFactorAuthService = twoFactorAuthService;
} }
public string Create(UserBindingModel model) public string Create(UserBindingModel model)
@ -53,6 +56,9 @@ namespace BusinessLogic.BusinessLogic
MailSender.Send(new MailRegistration(user)); MailSender.Send(new MailRegistration(user));
string code = _twoFactorAuthService.GenerateCode();
MailSender.Send(new MailTwoFactorCode(user, code));
return JwtProvider.Generate(user); return JwtProvider.Generate(user);
} }
@ -132,6 +138,10 @@ namespace BusinessLogic.BusinessLogic
{ {
throw new AccountException("The passwords don't match."); throw new AccountException("The passwords don't match.");
} }
string code = _twoFactorAuthService.GenerateCode();
MailSender.Send(new MailTwoFactorCode(user, code));
return JwtProvider.Generate(user); return JwtProvider.Generate(user);
} }
@ -166,5 +176,10 @@ namespace BusinessLogic.BusinessLogic
throw new AccountException("The email is not valid."); throw new AccountException("The email is not valid.");
} }
} }
public bool VerifyCode(string code)
{
return _twoFactorAuthService.Verify(code);
}
} }
} }

View File

@ -0,0 +1,21 @@
using Contracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic.Tools.Mail.MailTemplates
{
public class MailTwoFactorCode : Mail
{
public MailTwoFactorCode(UserBindingModel user, string code)
{
To = [user.Email];
Title = "Ваш код для подтверждения";
Body = $"Здравствуйте, {user.SecondName} {user.FirstName}! Вот Ваш код для подтверждения:\n" +
$"{code}\n" +
$"Если это не Вы, игноритруйте это сообщение.";
}
}
}

View File

@ -0,0 +1,42 @@
using Contracts.BusinessLogicContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic.Tools
{
public class TwoFactorAuthService : ITwoFactorAuthService
{
private string _code = string.Empty;
private const int LENGTH_CODE = 5;
public string GenerateCode()
{
_code = _getCode(LENGTH_CODE);
return _code;
}
private string _getCode(int length)
{
string res = "";
var rand = new Random();
for (int i = 0; i < length; i++)
{
res += rand.Next(0, 9).ToString();
}
return res;
}
public bool Verify(string code)
{
if (_code == string.Empty)
{
throw new Exception("Source code is not generated.");
}
return _code == code;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Contracts.BusinessLogicContracts
{
public interface ITwoFactorAuthService
{
string GenerateCode();
bool Verify(string code);
}
}

View File

@ -14,6 +14,8 @@ namespace Contracts.BusinessLogicContracts
{ {
string Login(string email, string password); string Login(string email, string password);
bool VerifyCode(string code);
string Create(UserBindingModel model); string Create(UserBindingModel model);
UserViewModel Update(UserBindingModel model); UserViewModel Update(UserBindingModel model);

View File

@ -32,7 +32,7 @@ namespace DatabaseImplement.Implements
public RoleBindingModel? GetElement(RoleSearchModel model) public RoleBindingModel? GetElement(RoleSearchModel model)
{ {
if (model.Id is null && string.IsNullOrWhiteSpace(model.Name)) if (model.Id is null && string.IsNullOrWhiteSpace(model?.Name))
{ {
return null; return null;
} }
@ -46,7 +46,7 @@ namespace DatabaseImplement.Implements
public IEnumerable<RoleBindingModel> GetList(RoleSearchModel? model) public IEnumerable<RoleBindingModel> GetList(RoleSearchModel? model)
{ {
var context = new Database(); var context = new Database();
if (model is null && string.IsNullOrWhiteSpace(model.Name)) if (model is null && string.IsNullOrWhiteSpace(model?.Name))
{ {
return context.Roles.Select(r => r.GetBindingModel()); return context.Roles.Select(r => r.GetBindingModel());
} }

View File

@ -46,6 +46,21 @@ namespace RestAPI.Controllers
} }
} }
[HttpPost]
public IResult VerifyCode([FromBody] VerifyCodeData data)
{
try
{
var res = _userLogic.VerifyCode(data.code);
return Results.Ok(res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error verify code");
return Results.Problem(ex.Message);
}
}
[HttpPost] [HttpPost]
public IResult Registration([FromBody] UserBindingModel model) public IResult Registration([FromBody] UserBindingModel model)
{ {
@ -128,4 +143,5 @@ namespace RestAPI.Controllers
} }
public record class UserData(string email, string password); public record class UserData(string email, string password);
public record class VerifyCodeData(string code);
} }

View File

@ -20,6 +20,7 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IRoleLogic, RoleLogic>(); builder.Services.AddTransient<IRoleLogic, RoleLogic>();
builder.Services.AddTransient<IUserLogic, UserLogic>(); builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddSingleton<ITwoFactorAuthService, TwoFactorAuthService>();
builder.Services.AddTransient<IRoleStorage, RoleStorage>(); builder.Services.AddTransient<IRoleStorage, RoleStorage>();
builder.Services.AddTransient<IUserStorage, UserStorage>(); builder.Services.AddTransient<IUserStorage, UserStorage>();

View File

@ -20,9 +20,9 @@ namespace WebApp.Pages
throw new Exception("Something wrong LOL!"); throw new Exception("Something wrong LOL!");
} }
this.SetJWT((string)response); TempData["jwt"] = (string)response;
return RedirectToPage("Index"); return RedirectToPage("TwoFactor");
} }
} }
} }

View File

@ -30,9 +30,9 @@ namespace WebApp.Pages
throw new Exception("Something wrong LOL!"); throw new Exception("Something wrong LOL!");
} }
this.SetJWT((string)response); TempData["jwt"] = (string)response;
return RedirectToPage("Index"); return RedirectToPage("TwoFactor");
} }
} }
} }

View File

@ -0,0 +1,128 @@
@page
@model WebApp.Pages.TwoFactorModel
<div class="row justify-content-center mt-7">
<style>
.icon-circle[class*=text-] [fill]:not([fill=none]), .icon-circle[class*=text-] svg:not([fill=none]), .svg-icon[class*=text-] [fill]:not([fill=none]), .svg-icon[class*=text-] svg:not([fill=none]) {
fill: currentColor !important;
}
.svg-icon-xl > svg {
width: 3.25rem;
height: 3.25rem;
}
.hover-lift-light {
transition: box-shadow .25s ease,transform .25s ease,color .25s ease,background-color .15s ease-in;
}
.mt-4 {
margin-top: 1.5rem !important;
}
.w-100 {
width: 100% !important;
}
.btn-group-lg > .btn, .btn-lg {
padding: 0.8rem 1.85rem;
font-size: 1.1rem;
border-radius: 0.3rem;
}
.btn-purple {
color: #fff;
background-color: #6672e8;
border-color: #6672e8;
}
.text-center {
text-align: center !important;
}
.py-4 {
padding-top: 1.5rem !important;
padding-bottom: 1.5rem !important;
}
.form-control-lg {
min-height: calc(1.5em + 1rem + 2px);
padding: 0.5rem 1rem;
font-size: 1.25rem;
border-radius: 0.3rem;
}
.form-control {
display: block;
width: 100%;
padding: 0.375rem 0.75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #1e2e50;
background-color: #f6f9fc;
background-clip: padding-box;
border: 1px solid #dee2e6;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border-radius: 0.25rem;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
</style>
<div class="col-lg-5 text-center">
<a href="index.html">
<img src="assets/img/svg/logo.svg" alt="">
</a>
<div class="card mt-5">
<div class="card-body py-5 px-lg-5">
<div class="svg-icon svg-icon-xl text-purple">
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><title>ionicons-v5-g</title><path d="M336,208V113a80,80,0,0,0-160,0v95" style="fill:none;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px"></path><rect x="96" y="208" width="320" height="272" rx="48" ry="48" style="fill:none;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px"></rect></svg>
</div>
<h3 class="fw-normal text-dark mt-4">
2-step verification
</h3>
<p class="mt-4 mb-1">
We sent a verification code to your email.
</p>
<p>
Please enter the code in the field below.
</p>
<form method="post">
<div class="row mt-4 pt-2">
<div class="col">
<input type="text" maxlength="1" class="form-control form-control-lg text-center py-4"
name="code" required autofocus>
</div>
<div class="col">
<input type="text" maxlength="1" class="form-control form-control-lg text-center py-4"
name="code" required>
</div>
<div class="col">
<input type="text" maxlength="1" class="form-control form-control-lg text-center py-4"
name="code" required>
</div>
<div class="col">
<input type="text" maxlength="1" class="form-control form-control-lg text-center py-4"
name="code" required>
</div>
<div class="col">
<input type="text" maxlength="1" class="form-control form-control-lg text-center py-4"
name="code" required>
</div>
</div>
<button type="submit" class="btn btn-purple btn-lg w-100 hover-lift-light mt-4">
Verify my account
</button>
</form>
</div>
</div>
<p class="text-center text-muted mt-4">
Didn't receive it?
<a href="#!" class="text-decoration-none ms-2">
Resend code
</a>
</p>
</div>
</div>

View File

@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApp.Pages
{
public class TwoFactorModel : PageModel
{
[BindProperty]
public int[] Code { get; set; } = [];
public void OnGet()
{
}
public IActionResult OnPost(string[] code)
{
var stringCode = string.Join(string.Empty, Code);
if (string.IsNullOrEmpty(stringCode))
{
throw new Exception("Looo");
}
var response = (string)APIClient.PostRequest("user/verifycode", new { code = stringCode });
var isCorrect = Convert.ToBoolean(response);
if (isCorrect)
{
this.SetJWT((string)TempData["jwt"]);
return RedirectToPage("Index");
}
else
{
throw new Exception("Wrong code! Please retry");
}
}
}
}