Skip to content

Commit

Permalink
Feature: Adicionado hash no password antes de salvar no banco.
Browse files Browse the repository at this point in the history
  • Loading branch information
LibardiFelipe committed Oct 8, 2022
1 parent 24f1fff commit ba96d5e
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 7 deletions.
7 changes: 5 additions & 2 deletions TemplateBase.Domain/Entities/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using TemplateBase.Domain.Entities.Base;
using TemplateBase.Domain.Enumerators;
using TemplateBase.Domain.Resources;
using TemplateBase.Domain.Utils;

namespace TemplateBase.Domain.Entities
{
Expand Down Expand Up @@ -84,10 +85,12 @@ public User ChangePassword(string value, bool fromConstructor = false)
if (!fromConstructor && (Password?.Equals(value) ?? false))
return this;

Password = value;
AddNotifications(new Contract<Notification>()
.Requires()
.IsNotNullOrWhiteSpace(Password, "Password", string.Format(DefaultMessages.CampoObrigatorio, "Senha")));
.IsNotNullOrWhiteSpace(value, "Password", string.Format(DefaultMessages.CampoObrigatorio, "Senha")));
// TODO: Adicionar verificação de segurança da senha

Password = Hasher.Hash(value);

FlagAsChanged();
return this;
Expand Down
6 changes: 4 additions & 2 deletions TemplateBase.Domain/Services/AuthenticationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using TemplateBase.Domain.Resources;
using TemplateBase.Domain.Services.Contracts;
using TemplateBase.Domain.Specifications;
using TemplateBase.Domain.Utils;

namespace TemplateBase.Domain.Services
{
Expand All @@ -32,8 +33,9 @@ public AuthenticationService(IUnitOfWork uow, IConfiguration configuration)
public async Task<AuthData> AuthenticateAsync(string email, string password, CancellationToken cancellationToken)
{
var userRepo = _uow.Repository<User>();
var user = (await userRepo.GetAllAsync(UserSpec.From(x => x.Email == email && x.Password == password), cancellationToken)).FirstOrDefault();
if (user == null)
var user = (await userRepo.GetAllAsync(UserSpec.From(x => x.Email == email), cancellationToken)).FirstOrDefault();

if (user == null || Hasher.Verify(password, user.Password) is false)
{
AddNotification("User", DefaultMessages.EmailOuSenhaIncorretos);
return null;
Expand Down
8 changes: 5 additions & 3 deletions TemplateBase.Domain/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ public async Task<User> RegisterUserAsync(string name, string email, string pass
return null;
}

public IReadOnlyCollection<Notification> GetNotifications() => Notifications;
public bool IsInvalid() => Notifications.Any();

#region Privados
private void SendVerificationEmail(string email)
{
var emailConfig = new EmailConfig
Expand Down Expand Up @@ -77,8 +81,6 @@ private void SendVerificationEmail(string email)
emailToSend.AddAddressee(email);
EmailService.Send(emailConfig, emailToSend);
}

public IReadOnlyCollection<Notification> GetNotifications() => Notifications;
public bool IsInvalid() => Notifications.Any();
#endregion
}
}
52 changes: 52 additions & 0 deletions TemplateBase.Domain/Utils/Hasher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Security.Cryptography;
using System;
using System.Linq;

namespace TemplateBase.Domain.Utils
{
public static class Hasher
{
private const int _saltSize = 16;
private const int _keySize = 32;
private const int _iterations = 100000;
private static readonly HashAlgorithmName _algorithm = HashAlgorithmName.SHA256;

private const char segmentDelimiter = ':';

public static string Hash(string secret)
{
var salt = RandomNumberGenerator.GetBytes(_saltSize);
var key = Rfc2898DeriveBytes.Pbkdf2(
secret,
salt,
_iterations,
_algorithm,
_keySize
);
return string.Join(
segmentDelimiter,
Convert.ToHexString(key),
Convert.ToHexString(salt),
_iterations,
_algorithm
);
}

public static bool Verify(string secret, string hash)
{
var segments = hash.Split(segmentDelimiter);
var key = Convert.FromHexString(segments[0]);
var salt = Convert.FromHexString(segments[1]);
var iterations = int.Parse(segments[2]);
var algorithm = new HashAlgorithmName(segments[3]);
var inputSecretKey = Rfc2898DeriveBytes.Pbkdf2(
secret,
salt,
iterations,
algorithm,
key.Length
);
return key.SequenceEqual(inputSecretKey);
}
}
}

0 comments on commit ba96d5e

Please sign in to comment.