Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correções, adição das funções do usuário. #15

Merged
merged 10 commits into from
Sep 10, 2024
Merged
13 changes: 8 additions & 5 deletions Blazing.Api/Controllers/Category/CategoryController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Blazing.Application.Dto;
using Blazing.Ecommerce.Repository;
using Blazing.Ecommerce.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -14,7 +14,6 @@ public class CategoryController(ILogger<CategoryController> logger, ICategoryInf
private readonly ILogger<CategoryController> _logger = logger;
private readonly ICategoryInfrastructureRepository _categoriaRepository = categoriaRepository;


/// <summary>
/// Adds a list of new categories.
/// </summary>
Expand Down Expand Up @@ -59,7 +58,7 @@ public class CategoryController(ILogger<CategoryController> logger, ICategoryInf
/// <returns>List of category DTOs to delete.</returns>
[Authorize]
[HttpDelete("delete")]
public async Task<ActionResult<CategoryDto?>> DeleteCategories(IEnumerable<Guid> id, CancellationToken cancellationToken)
public async Task<ActionResult<CategoryDto?>> DeleteCategories([FromQuery]IEnumerable<Guid> id, CancellationToken cancellationToken)
{
var categoriesDeleted = await _categoriaRepository.DeleteCategory(id, cancellationToken);

Expand Down Expand Up @@ -92,9 +91,13 @@ public async Task<ActionResult<CategoryDto>> GetCategoryById([FromQuery] IEnumer
/// <returns>List of category DTOs.</returns>
[Authorize]
[HttpGet]
public async Task<ActionResult<IEnumerable<CategoryDto>>> GetAllCategories(CancellationToken cancellationToken)
public async Task<ActionResult<IEnumerable<CategoryDto>>> GetAllCategories([FromQuery]int page, int pageSize, CancellationToken cancellationToken)
{
var categories = await _categoriaRepository.GetAll(cancellationToken);
if (pageSize > 50)
{
pageSize = 50;
}
var categories = await _categoriaRepository.GetAll(page, pageSize,cancellationToken);

_logger.LogInformation("Categoria recuperados com sucesso. Total de categorias: {TotalCategories}",
categories.Count());
Expand Down
12 changes: 8 additions & 4 deletions Blazing.Api/Controllers/Product/ProductController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using Blazing.Application.Dto;
using Blazing.Ecommerce.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using Blazing.Ecommerce.Interface;

namespace Blazing.Api.Controllers.Product
{
Expand All @@ -15,7 +15,7 @@ namespace Blazing.Api.Controllers.Product
/// This class requires an instance of ILogger and IProductAppService to be passed in the constructor.
/// </remarks>
/// <typeparam name="_logger">The type of the logger.</typeparam>
/// <typeparam name="_productInfraRepository">The type of the product infrastructure service.</typeparam>
/// <typeparam name="produtoRepository">The type of the product infrastructure service.</typeparam>
[Route("api/[controller]")]
[ApiController]
public class ProductController(ILogger<ProductController> logger, IProductInfrastructureRepository produtoRepository) : ControllerBase
Expand Down Expand Up @@ -103,8 +103,8 @@ public async Task<ActionResult<IEnumerable<ProductDto>>> DeleteProducts([FromBod
/// <param name="id">the identifier of the productDto.</param>
/// <returns>productDto.</returns>
[Authorize]
[HttpGet("productId")]
public async Task<ActionResult<IEnumerable<ProductDto?>>> GetProductById([FromQuery] IEnumerable<Guid> id, CancellationToken cancellationToken)
[HttpGet("id")]
public async Task<ActionResult<IEnumerable<ProductDto?>>> GetProductById([FromQuery]IEnumerable<Guid> id, CancellationToken cancellationToken)
{
var productsById = await _productInfraRepository.GetProductById(id, cancellationToken);

Expand All @@ -122,6 +122,10 @@ public async Task<ActionResult<IEnumerable<ProductDto>>> DeleteProducts([FromBod
[HttpGet]
public async Task<ActionResult<IEnumerable<ProductDto>>> GetAll([FromQuery]int page, int pageSize, CancellationToken cancellationToken)
{
if (pageSize > 50)
pageSize = 50;


var products = await _productInfraRepository.GetAll(page, pageSize, cancellationToken);

_logger.LogInformation("Produtos recuperados com sucesso. Total de produtos: {TotalProducts}.",
Expand Down
42 changes: 42 additions & 0 deletions Blazing.Api/Controllers/User/RoleController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Blazing.Identity.Dto;
using Blazing.Identity.Interface;
using Blazing.Identity.Repository;
using Microsoft.AspNetCore.Mvc;

namespace Blazing.Api.Controllers.User
{
[ApiController]
[Route("api/[controller]")]
public class RoleController(ILogger<RoleController> logger,IRoleInfrastructureRepository roleInfrastructureRepository) : ControllerBase
{
private readonly ILogger<RoleController> _logger = logger;
private readonly IRoleInfrastructureRepository _roleInfrastructureRepository = roleInfrastructureRepository;

[HttpPost]
public async Task<ActionResult> AddRole(IEnumerable<ApplicationRoleDto> roleDto,
CancellationToken cancellationToken)
{
var result = await _roleInfrastructureRepository.Add(roleDto, cancellationToken);
_logger.LogInformation("Funções adicionadas com sucesso. Total adicionado: {result}", result.Count());
return Ok(result);
}

[HttpPut("Update")]
public async Task<ActionResult> UpdateRole(IEnumerable<ApplicationRoleDto> roleDto,
CancellationToken cancellationToken)
{
var id = roleDto.Select(r => r.Id).AsEnumerable();
var result = await _roleInfrastructureRepository.Update(id ,roleDto, cancellationToken);
_logger.LogInformation("Funções atualizadas com sucesso. Total atualizado: {result}", result.Count());
return Ok(result);
}

[HttpGet]
public async Task<ActionResult<IEnumerable<ApplicationRoleDto>>> GetAllRole(int page, int pageSize, CancellationToken cancellationToken)
{
var result = await _roleInfrastructureRepository.GetAll(page, pageSize, cancellationToken);
_logger.LogInformation("Funções recuperadas com sucesso. Total recuperado: {result}", result.Count());
return Ok(result);
}
}
}
35 changes: 20 additions & 15 deletions Blazing.Api/Controllers/User/UserController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Blazing.Application.Dto;
using Blazing.Domain.Exceptions.User;
using Blazing.Identity.Entities;
using Blazing.Identity.Interface;
using Blazing.Identity.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
Expand Down Expand Up @@ -102,8 +103,8 @@ public async Task<ActionResult> DeleteUsers(IEnumerable<string> id,
/// This method requires the user to be authenticated.
/// </remarks>
[Authorize]
[HttpGet("Id")]
public async Task<ActionResult<UserDto>> GetUserById(IEnumerable<Guid> id,
[HttpGet("id")]
public async Task<ActionResult<UserDto>> GetUserById([FromQuery]IEnumerable<Guid> id,
CancellationToken cancellationToken)
{
var result = await _userInfrastructureRepository.GetUsersByIdAsync(id, cancellationToken);
Expand All @@ -120,14 +121,19 @@ public async Task<ActionResult<UserDto>> GetUserById(IEnumerable<Guid> id,
/// <summary>
/// Retrieves all users from the database.
/// </summary>
/// <param name="pageSize"></param>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <param name="page"></param>
/// <returns>An asynchronous task that represents the operation. The task result contains an action result indicating the success of the operation.
/// The result contains a list of all users.</returns>
[Authorize]
[HttpGet]
public async Task<ActionResult<ApplicationUser>> GetAllUser(CancellationToken cancellationToken)
public async Task<ActionResult<ApplicationUser>> GetAllUser([FromQuery]int page, int pageSize, CancellationToken cancellationToken)
{
var result = await _userInfrastructureRepository.GetAllUsersAsync(cancellationToken);
if (pageSize > 50)
pageSize = 50;

var result = await _userInfrastructureRepository.GetAllUsersAsync(page, pageSize, cancellationToken);

_logger.LogInformation("A recuperação dos usuários foi realizada com sucesso. Total Usuários: {TotalUsuários}",
result.Count());
Expand All @@ -138,7 +144,7 @@ public async Task<ActionResult<ApplicationUser>> GetAllUser(CancellationToken ca
/// <summary>
/// Asynchronously handles the login request.
/// </summary>
/// <param name="login.email">The email of the user.</param>
/// <param name="login.LoginIdentifier ">The email of the user.</param>
/// <param name="login.password">The password of the user.</param>
/// <param name="login.rememberMe">A boolean indicating whether the user wants to be remembered.</param>
/// <param name="cancellationToken">The cancellation token.</param>
Expand All @@ -155,43 +161,42 @@ public async Task<ActionResult<SignInResult>> LoginAsync(Login login,
switch (result)
{
case { Succeeded: true }:
if (!string.IsNullOrEmpty(login.Email) && login.Email.Contains("@"))
if (!string.IsNullOrEmpty(login.LoginIdentifier) && login.LoginIdentifier.Contains("@"))
{
_logger.LogInformation("O login foi realizado com sucesso. E-mail: {email}", login.Email);
_logger.LogInformation("O login foi realizado com sucesso. E-mail: {email}", login.LoginIdentifier);
return Ok(new { status = "success", message = "Login bem-sucedido." });
}
else
{
_logger.LogInformation("O login foi realizado com sucesso. Nome do usuário: {userName}", login.Email);
_logger.LogInformation("O login foi realizado com sucesso. Nome do usuário: {userName}", login.LoginIdentifier );
return Ok(new { status = "success", message = "Login bem-sucedido." });
}

case { IsNotAllowed: true }:
_logger.LogWarning("Tentativa de login falhou. O login não é permitido para este usuário. E-mail: {email}", login.Email);
_logger.LogWarning("Tentativa de login falhou. O login não é permitido para este usuário. E-mail: {email}", login.LoginIdentifier );
return Unauthorized(new { status = "error", message = "Login não permitido para este usuário." });

case { RequiresTwoFactor: true }:
_logger.LogInformation("Tentativa de login requer autenticação de dois fatores. E-mail: {email}", login.Email);
_logger.LogInformation("Tentativa de login requer autenticação de dois fatores. E-mail: {email}", login.LoginIdentifier );
return Unauthorized(new { status = "2fa_required", message = "Autenticação de dois fatores é necessária." });

case { Succeeded: false }:
if (!string.IsNullOrEmpty(login.Email) && login.Email.Contains("@"))
if (!string.IsNullOrEmpty(login.LoginIdentifier ) && login.LoginIdentifier .Contains("@"))
{
_logger.LogWarning("Tentativa de login falhou. Credenciais inválidas. E-mail: {email}", login.Email);
_logger.LogWarning("Tentativa de login falhou. Credenciais inválidas. E-mail: {email}", login.LoginIdentifier );
return Unauthorized(new { status = "error", message = "Credenciais inválidas." });
}
else
{
_logger.LogWarning("Tentativa de login falhou. Credenciais inválidas. Nome do usuário: {email}", login.Email);
_logger.LogWarning("Tentativa de login falhou. Credenciais inválidas. Nome do usuário: {email}", login.LoginIdentifier );
return Unauthorized(new { status = "error", message = "Credenciais inválidas." });
}

default:
_logger.LogWarning("Falha no login. Credenciais inválidas. E-mail: {email}", login.Email);
_logger.LogWarning("Falha no login. Credenciais inválidas. E-mail: {email}", login.LoginIdentifier );
return Unauthorized(new { status = "error", message = "Credenciais inválidas." });
}


}

/// <summary>
Expand Down
28 changes: 28 additions & 0 deletions Blazing.Api/Dependencies/ConfigServiceCollectionExtensionsAPi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Blazing.Application.Dto;
using Blazing.Application.Mappings;
using Blazing.Application.Services;
using Blazing.Domain.Entities;
using Blazing.Domain.Interfaces.Services;
using Blazing.Domain.Services;
using Blazing.Ecommerce.Data;
using Blazing.Identity.Data;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using System.Text.Json.Serialization;


namespace Blazing.Api.Dependencies
{
public static class ConfigServiceCollectionExtensionsAPi
{
public static IServiceCollection AddConfigApi(
this IServiceCollection services, IConfiguration config)
{
services.AddAutoMapper(typeof(BlazingProfile));

services.AddSwaggerGen();

return services;
}
}
}
39 changes: 0 additions & 39 deletions Blazing.Api/Dependencies/ConfigServiceCollectionExtensiosApi.cs

This file was deleted.

1 change: 1 addition & 0 deletions Blazing.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.Identity.Web;
using Serilog;
using System.Text.Json.Serialization;
using Blazing.Ecommerce.Dependencies;


var builder = WebApplication.CreateBuilder(args);
Expand Down
6 changes: 3 additions & 3 deletions Blazing.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"ConnectionStrings": {
"Blazing": "Server=host.docker.internal,1200;Database=Blazing;User Id=sa;Password=019Uf%HG0!{;TrustServerCertificate=True"
"Blazing": "Server=192.168.0.10,1200;Database=Blazing;User Id=sa;Password=019Uf%HG0!{;TrustServerCertificate=True"
},

"AzureAd": {
Expand Down Expand Up @@ -44,13 +44,13 @@ For more info see https://aka.ms/dotnet-template-ms-identity-platform
"path": "./Logs/log-development-.json",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
//"formatter": "Blazing.Api.FormatterLogs.CompactJsonFormatter, Blazing.Api"
"formatter": "Blazing.Api.FormatterLogs.CompactJsonFormatter, Blazing.Api"
}
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "Server=host.docker.internal,1200;Database=BlazingLogs;User Id=sa;Password=019Uf%HG0!{;TrustServerCertificate=True;",
"connectionString": "Server=192.168.0.10,1200;Database=BlazingLogs;User Id=sa;Password=019Uf%HG0!{;TrustServerCertificate=True;",
"tableName": "Logs",
"autoCreateSqlTable": true,
"restrictedToMinimumLevel": "Error",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
using Blazing.Application.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blazing.Application.Interfaces.Category
namespace Blazing.Application.Interface.Category
{
#region Interface Category App Service
public interface ICategoryAppService<T> where T : BaseEntityDto
Expand Down Expand Up @@ -50,7 +45,10 @@ public interface ICategoryAppService<T> where T : BaseEntityDto
/// </summary>
/// <param name="id">A boolean flag indicating whether to check for the existence of categoriesDto.</param>
/// <param name="nameExists">A boolean flag indicating whether to check for the existence of categoriesDto.</param>
Task<bool?> ExistsCategories(bool id, bool nameExists, IEnumerable<CategoryDto> categoryDto, CancellationToken cancellationToken);
/// <param name="categoryDto"></param>
/// <param name="cancellationToken"></param>
Task<bool?> ExistsCategories(bool id, bool nameExists, IEnumerable<CategoryDto?> categoryDto,
CancellationToken cancellationToken);
}
#endregion
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using Blazing.Application.Dto;
using Blazing.Domain.Entities;
using System.Xml.Linq;

namespace Blazing.Application.Interfaces.Product
namespace Blazing.Application.Interface.Product
{
#region Interface product App Service.
/// <summary>
Expand Down
Loading