add two factor auth (API)

This commit is contained in:
mfnefd 2024-06-22 18:42:11 +04:00
parent 7d4c9dad87
commit 513f57ec72
7 changed files with 131 additions and 19 deletions

View File

@ -25,11 +25,14 @@ namespace BusinessLogic.BusinessLogic
{
private readonly ILogger _logger;
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;
_userStorage = userStorage;
_twoFactorAuthService = twoFactorAuthService;
}
public string Create(UserBindingModel model)
@ -53,6 +56,9 @@ namespace BusinessLogic.BusinessLogic
MailSender.Send(new MailRegistration(user));
string code = _twoFactorAuthService.GenerateCode();
MailSender.Send(new MailTwoFactorCode(user, code));
return JwtProvider.Generate(user);
}
@ -132,6 +138,10 @@ namespace BusinessLogic.BusinessLogic
{
throw new AccountException("The passwords don't match.");
}
string code = _twoFactorAuthService.GenerateCode();
MailSender.Send(new MailTwoFactorCode(user, code));
return JwtProvider.Generate(user);
}
@ -166,5 +176,10 @@ namespace BusinessLogic.BusinessLogic
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

@ -10,18 +10,20 @@ using System.Threading.Tasks;
namespace Contracts.BusinessLogicContracts
{
public interface IUserLogic
{
string Login(string email, string password);
public interface IUserLogic
{
string Login(string email, string password);
string Create(UserBindingModel model);
bool VerifyCode(string code);
UserViewModel Update(UserBindingModel model);
string Create(UserBindingModel model);
UserViewModel ReadElement(UserSearchModel model);
UserViewModel Update(UserBindingModel model);
IEnumerable<UserViewModel> ReadElements(UserSearchModel? model);
UserViewModel ReadElement(UserSearchModel model);
UserViewModel Delete(UserSearchModel model);
}
IEnumerable<UserViewModel> ReadElements(UserSearchModel? model);
UserViewModel Delete(UserSearchModel model);
}
}

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]
public IResult Registration([FromBody] UserBindingModel model)
{
@ -128,4 +143,5 @@ namespace RestAPI.Controllers
}
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<IUserLogic, UserLogic>();
builder.Services.AddSingleton<ITwoFactorAuthService, TwoFactorAuthService>();
builder.Services.AddTransient<IRoleStorage, RoleStorage>();
builder.Services.AddTransient<IUserStorage, UserStorage>();
@ -34,7 +35,7 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc(VERSION, new OpenApiInfo { Title = TITLE, Version = VERSION });
c.SwaggerDoc(VERSION, new OpenApiInfo { Title = TITLE, Version = VERSION });
});
var app = builder.Build();
@ -46,15 +47,15 @@ var mailSender = app.Services.GetService<MailSender>();
string? getSection(string section) => builder.Configuration?.GetSection(section)?.Value?.ToString();
jwtProvider?.SetupJwtOptions(new()
{
SecretKey = getSection("JwtOptions:SecretKey") ?? string.Empty,
ExpiresHours = Convert.ToInt16(getSection("JwtOptions:ExpiresHours"))
SecretKey = getSection("JwtOptions:SecretKey") ?? string.Empty,
ExpiresHours = Convert.ToInt16(getSection("JwtOptions:ExpiresHours"))
});
mailSender?.SetupMailOptions(new()
{
Email = getSection("MailOptions:Email") ?? string.Empty,
Password = getSection("MailOptions:Password") ?? string.Empty,
SmtpClientHost = getSection("MailOptions:SmtpClientHost") ?? string.Empty,
SmtpClientPort = Convert.ToInt16(getSection("MailOptions:SmtpClientPort"))
Email = getSection("MailOptions:Email") ?? string.Empty,
Password = getSection("MailOptions:Password") ?? string.Empty,
SmtpClientHost = getSection("MailOptions:SmtpClientHost") ?? string.Empty,
SmtpClientPort = Convert.ToInt16(getSection("MailOptions:SmtpClientPort"))
});
#endregion Setup config
@ -62,8 +63,8 @@ mailSender?.SetupMailOptions(new()
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint($"/swagger/{VERSION}/swagger.json", $"{TITLE} {VERSION}"));
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint($"/swagger/{VERSION}/swagger.json", $"{TITLE} {VERSION}"));
}
app.UseHttpsRedirection();