Skip to content

Commit

Permalink
Merge pull request #28 from lrodolfol/refactor/users
Browse files Browse the repository at this point in the history
Refactor/users
  • Loading branch information
lrodolfol authored Aug 22, 2024
2 parents f6d517f + 5837831 commit e1e1562
Show file tree
Hide file tree
Showing 43 changed files with 254 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public MonthlyClosingController(OperationsHandler handler, CViewModel viewModel,
_logger = logger;
}

[Authorize(Roles = "MINISTERIO")]
[Authorize(Roles = "M-SCT, M-TRS")]
[HttpPost("/api/v1/monthly-closing")]
public async Task<IActionResult> BlockMonth([FromBody] EditMonthWorkDto editMonthWorkDto)
{
Expand All @@ -35,7 +35,7 @@ public async Task<IActionResult> BlockMonth([FromBody] EditMonthWorkDto editMont
return StatusCode(_handler.GetStatusCode(), _viewModel);
}

[Authorize(Roles = "MINISTERIO")]
[Authorize(Roles = "M-SCT, M-TRS")]
[HttpDelete("/api/v1/monthly-closing/{id:int}")]
public async Task<IActionResult> UnblockMonth([FromRoute] int id)
{
Expand All @@ -50,7 +50,7 @@ public async Task<IActionResult> UnblockMonth([FromRoute] int id)
return StatusCode(_handler.GetStatusCode(), _viewModel);
}

[Authorize(Roles = "MINISTERIO,LOCAL")]
[Authorize(Roles = "L-SCT, M-SCT, M-TRS, L-TRS")]
[HttpGet("/api/v1/monthly-closing/{churchId:int}")]
public async Task<IActionResult> MonthWorkAll([FromRoute] int churchId)
{
Expand Down
15 changes: 15 additions & 0 deletions Registration/src/Domain/Registration.DomainBase/Aggregate/Email.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Text.RegularExpressions;

namespace Registration.DomainBase.Aggregate;
public class Email
{
public string Address { get; set; } = null!;

public Email(string? address)
{
if(address is not null)
Address = address;
}

public void Validate() => Regex.IsMatch(Address, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SecureIdentity.Password;
using Registration.DomainBase.Aggregate;
using SecureIdentity.Password;

namespace Registration.DomainBase.Entities.Registrations;
public class User : Entitie
Expand All @@ -7,6 +8,7 @@ public class User : Entitie
public string Name { get; private set; } = string.Empty;
public string PasswordHash { get; private set; } = string.Empty;
public int ChurchId { get; private set; }
public Email Email { get; private set; } = null!;
public Church? Church { get; private set; }

public List<UserRole>? UserRoles { get; set; }
Expand All @@ -18,6 +20,11 @@ public User(int id, string name, int churchId)
Name = name;
}

public void SetEmail(string? email)
{
Email = new Email(email);
}

public void UpdateChanges(User editUser)
{
Name = editUser.Name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.Extensions.Configuration;

namespace Registration.DomainCore;
public static class EnvironmentConfiguration
{
public static readonly IConfigurationRoot ConfigurationRoot = DefineConfiguration();

private static IConfigurationRoot DefineConfiguration()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ??
Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Dev";

if (environment is null)
return new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();

return new ConfigurationBuilder().AddJsonFile($"appsettings.{environment}.json", false, true).Build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public abstract class DomainBaseEvents
{
public DateTime OcurredOn { get; set; }

public DomainBaseEvents()
{
OcurredOn = DateTime.UtcNow;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Registration.DomainCore.Events;
public class UserCreatedEvent : DomainBaseEvents
{
public int Id { get; set; }
public string EmailAddress { get; set; } = null!;

public UserCreatedEvent(int id, string emailAddress) : base()
{
Id = id;
EmailAddress = emailAddress;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.Extensions.Configuration;

namespace Registration.Infrastructure.Config;
public static class EnvironmentConfiguration
{
public static readonly IConfigurationRoot ConfigurationRoot = DefineConfiguration();

private static IConfigurationRoot DefineConfiguration()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ??
Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Dev";

if(environment is null)
return new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build();

return new ConfigurationBuilder().AddJsonFile($"{environment}.json", false, true).Build();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using ChurchCashFlow.Profiles;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Registration.DomainBase.Aggregate;
using Registration.DomainBase.Entities.Registrations;
using SecureIdentity.Password;

Expand Down Expand Up @@ -43,6 +44,15 @@ public void Configure(EntityTypeBuilder<User> builder)
.HasConstraintName("Fk_User_Church")
.OnDelete(DeleteBehavior.NoAction);

builder.OwnsOne(x => x.Email, emailBuilder =>
{
emailBuilder.Property(e => e.Address)
.IsRequired()
.HasColumnName("email")
.HasColumnType("VARCHAR")
.IsRequired(false)
.HasMaxLength(255);
});

builder.HasIndex(x => x.Code, "IX_User_Code")
.IsUnique();
Expand All @@ -64,12 +74,12 @@ private static void InsertDataTemp(EntityTypeBuilder<User> builder)
user.GenerateCode();
builder.HasData(user);

user = new User(3, "Flavia Maciel", 1);
user = new User(3, "Cintia Gomes", 1);
user.GeneratePassWordHash(passWord);
user.GenerateCode();
builder.HasData(user);

user = new User(4, "Ricardo Groof", 1);
user = new User(4, "Fernando Groler", 1);
user.GeneratePassWordHash(passWord);
user.GenerateCode();
builder.HasData(user);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public MysqlBase(IConfiguration configuration)
{
_configuration = configuration;

//var conStr = _configuration.GetConnectionString("DefaultConnectionMySQL");
var conStr = _configuration.GetValue<string>("DefaultConnectionMySQL");
var conStr = _configuration.GetConnectionString("DefaultConnectionMySQL");
//var conStr = _configuration.GetValue<string>("DefaultConnectionMySQL");
_mysqlConnection = new MySqlConnection(conStr);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ protected BaseMessageBrokerClient(IConfiguration configuration)
public byte[] BodyMessage { get; protected set; } = new byte[0];

protected abstract byte[] BuildMessage();
protected abstract void LoadConfig();

public string CreateUrl()
{
Expand Down
4 changes: 4 additions & 0 deletions Registration/src/Service/MessageBroker/MessageBroker.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Domain\Registration.DomainCore\Registration.DomainCore.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
using System.Text;
using System.Text.Json;

namespace MessageBroker;
namespace MessageBroker.Messages;

public class BlockMonthWorkMessage : BaseMessageBrokerClient
{
{
public BlockMonthWorkMessage(IConfiguration configuration, int churchId, string competence) : base(configuration)
{
ChurchId = churchId;
Expand All @@ -17,7 +17,7 @@ public BlockMonthWorkMessage(IConfiguration configuration, int churchId, string
public int ChurchId { get; private set; }
public string YearMonth { get; private set; }

private void LoadConfig()
protected override void LoadConfig()
{
Exchange = _configuration["MonthWorkMessageBroker:Exchange"]!;
Host = _configuration["MonthWorkMessageBroker:Host"]!;
Expand All @@ -42,8 +42,8 @@ protected override byte[] BuildMessage()
{
var objBody = new
{
ChurchId = ChurchId,
YearMonth = YearMonth
ChurchId,
YearMonth
};

var serialize = JsonSerializer.Serialize(objBody);
Expand Down
51 changes: 51 additions & 0 deletions Registration/src/Service/MessageBroker/Messages/NewUserCreated.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Extensions.Configuration;
using Registration.DomainCore.Events;
using System.Text.Json;
using System.Text;

namespace MessageBroker.Messages;
public class NewUserCreated : BaseMessageBrokerClient
{
private readonly UserCreatedEvent _userCreated;

public NewUserCreated(IConfiguration configuration, UserCreatedEvent userCreated) : base(configuration)
{
_userCreated = userCreated;
LoadConfig();
}

public void PreparePublish()
{
IMessageBrokerClient rabbitClient = new RabbitMqClient<NewUserCreated>(this);

rabbitClient.Publish();
}

protected override byte[] BuildMessage()
{
var objBody = new
{
_userCreated.Id,
_userCreated.EmailAddress,
_userCreated.OcurredOn
};

var serialize = JsonSerializer.Serialize(objBody);
var body = Encoding.UTF8.GetBytes(serialize);

return body;
}
protected override void LoadConfig()
{
Host = _configuration["MessageBroker:Host"]!;
VirtualHost = _configuration["MessageBroker:VirtualHost"]!;
Port = _configuration["MessageBroker:Port"]!;
UserName = _configuration["MessageBroker:UserName"]!;
Password = _configuration["MessageBroker:Password"]!;
Exchange = _configuration["MessageBroker:UserCreated:Exchange"]!;
RoutingKey = _configuration["MessageBroker:UserCreated:RoutingKey"]!;
Queue = _configuration["MessageBroker:UserCreated:Queue"]!;

BodyMessage = BuildMessage();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
using Registration.Mapper.DTOs.Registration.User;
using Registration.Mapper.DTOs.Registration.UserLogin;
using Serilog;
using MessageBroker.Messages;
using Registration.DomainCore.Events;
using Registration.DomainCore;

namespace Registration.Handlers.Handlers.Registrations;
public class UserHandler : BaseNormalHandler
Expand All @@ -28,6 +31,12 @@ public UserHandler(IUserRepository context, IMapper mapper, CViewModel viewModel
_logger = logger;
}

private void SendNewUserCreated(User user)
{
var @event = new NewUserCreated(EnvironmentConfiguration.ConfigurationRoot, new UserCreatedEvent(user.Id, user.Email.Address));
@event.PreparePublish();
}

public async Task<CViewModel> GetAll(bool active = true)
{
try
Expand Down Expand Up @@ -99,6 +108,7 @@ public async Task<CViewModel> Create(EditUserCreateDto dto)
return _viewModel;

var user = _mapper.Map<User>(dto);
user.SetEmail(dto.Email);
user.GeneratePassWordHash(user.PasswordHash);
user.GenerateCode();

Expand All @@ -113,6 +123,8 @@ public async Task<CViewModel> Create(EditUserCreateDto dto)
_viewModel.SetData(userReadDto);
_logger.Information("The user {userName} was successfully created", user.Name);

SendNewUserCreated(user);

return _viewModel;
}
catch (DbUpdateException ex)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Flunt.Notifications;
using Flunt.Validations;
using Registration.DomainBase.Aggregate;
using Registration.DomainBase.Entities;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
Expand All @@ -15,6 +16,7 @@ public class EditUserCreateDto : ModelDto
[StringLength(8, MinimumLength = 6, ErrorMessage = "Name must be between 6 and 8 characters")]
public string PasswordHash { get; set; } = string.Empty;
public int ChurchId { get; set; }
public string? Email { get; set; }
public HashSet<int> RoleIds { get; set; }

public void Validate()
Expand All @@ -24,6 +26,7 @@ public void Validate()
.IsGreaterThan(Name, 2, "Name", "Name should have at least 3 chars")
.IsNotNullOrEmpty(PasswordHash, "PassWord", "The password can not be empty")
.IsNotNull(RoleIds, "RolesId", "User must have a role")
.IsEmailOrEmpty(Email, "Email", "Email is invalid")
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Registration.Mapper.DTOs.Registration.Address;
using Registration.Mapper.DTOs.Registration.ChurchAddress;

namespace ChurchCashFlow.Profiles;
namespace Registration.Mapper.Profiles;
public class AddressProfile : Profile
{
public AddressProfile()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Registration.Mapper.DTOs.Registration.Church;
using Registration.Mapper.DTOs.Registration.ChurchAddress;

namespace ChurchCashFlow.Profiles;
namespace Registration.Mapper.Profiles;
public class ChurchProfile : Profile
{
public ChurchProfile()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using Registration.DomainBase.Entities.Registrations;
using Registration.Mapper.DTOs.Registration.MeetingKind;

namespace ChurchCashFlow.Profiles;
namespace Registration.Mapper.Profiles;
public class MeetingKindProfile : Profile
{
public MeetingKindProfile()
Expand Down
Loading

0 comments on commit e1e1562

Please sign in to comment.