├── README.md ├── src ├── Way2Commerce.Domain │ ├── Entities │ │ ├── Shared │ │ │ └── Entity.cs │ │ ├── Categoria.cs │ │ └── Produto.cs │ ├── Interfaces │ │ ├── Services │ │ │ ├── IProdutoService.cs │ │ │ └── Shared │ │ │ │ └── IServiceBase.cs │ │ └── Repositories │ │ │ ├── IProdutoRepository.cs │ │ │ ├── ICategoriaRepository.cs │ │ │ └── Shared │ │ │ └── IRepositoryBase.cs │ ├── Way2Commerce.Domain.csproj │ └── Services │ │ ├── ProdutoService.cs │ │ └── Shared │ │ └── ServiceBase.cs ├── Way2Commerce.Identity │ ├── Constants │ │ ├── Roles.cs │ │ ├── Policies.cs │ │ └── ClaimTypes.cs │ ├── PolicyRequirements │ │ ├── HorarioComercialRequirement.cs │ │ └── HorarioComercialHandler.cs │ ├── Data │ │ └── IdentityDataContext.cs │ ├── Configurations │ │ └── JwtOptions.cs │ ├── Way2Commerce.Identity.csproj │ ├── Services │ │ └── IdentityService.cs │ └── Migrations │ │ ├── 20220220191221_Initial.cs │ │ ├── IdentityDataContextModelSnapshot.cs │ │ └── 20220220191221_Initial.Designer.cs ├── Way2Commerce.Api │ ├── appsettings.json │ ├── Controllers │ │ ├── Shared │ │ │ ├── ApiControllerBase.cs │ │ │ ├── ApiCollectionResponse.cs │ │ │ └── CustomProblemDetails.cs │ │ └── v1 │ │ │ ├── CategoriaController.cs │ │ │ ├── UsuarioController.cs │ │ │ └── ProdutoController.cs │ ├── appsettings.Development.json │ ├── Extensions │ │ ├── ApiVersioningSetup.cs │ │ ├── ProblemDetailsSetup.cs │ │ ├── SwaggerSetup.cs │ │ └── AuthenticationSetup.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Attributes │ │ └── ClaimsAuthorizeAttribute.cs │ ├── Way2Commerce.Api.csproj │ └── IoC │ │ └── NativeInjectorConfig.cs ├── Way2Commerce.Application │ ├── Way2Commerce.Application.csproj │ ├── DTOs │ │ ├── Request │ │ │ ├── UsuarioLoginRequest.cs │ │ │ ├── UsuarioCadastroRequest.cs │ │ │ ├── InsercaoProdutoRequest.cs │ │ │ └── AtualizacaoProdutoRequest.cs │ │ └── Response │ │ │ ├── UsuarioCadastroResponse.cs │ │ │ ├── CategoriaResponse.cs │ │ │ ├── UsuarioLoginResponse.cs │ │ │ └── ProdutoResponse.cs │ └── Interfaces │ │ └── Services │ │ └── IIdentityService.cs └── Way2Commerce.Data │ ├── Repositories │ ├── CategoriaRepository.cs │ ├── ProdutoRepository.cs │ └── Shared │ │ └── RepositoryBase.cs │ ├── Way2Commerce.Data.csproj │ ├── Mappings │ ├── CategoriaMap.cs │ └── ProdutoMap.cs │ ├── Context │ └── DataContext.cs │ └── Migrations │ ├── 20211224171716_Initial.cs │ ├── DataContextModelSnapshot.cs │ └── 20211224171716_Initial.Designer.cs ├── test ├── Way2Commerce.Domain.Tests │ ├── Way2Commerce.Domain.Tests.csproj │ └── Services │ │ └── ProdutoServiceTests.cs └── Way2Commerce.Data.Tests │ ├── Way2Commerce.Data.Tests.csproj │ ├── Repositories │ ├── CategoriaRepositoryTests.cs │ └── ProdutoRepositoryTests.cs │ └── Database │ └── DBInMemory.cs ├── .github └── workflows │ └── main_way2commerce.yml ├── Way2Commerce.sln └── .gitignore /README.md: -------------------------------------------------------------------------------- 1 | # Way2Commerce 2 | Projeto idealizado para o Way2 Dev Bootcamp 3 | -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Entities/Shared/Entity.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Domain.Entities.Shared; 2 | 3 | public abstract class Entity 4 | { 5 | public int Id { get; protected set; } 6 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Constants/Roles.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Identity 2 | { 3 | public class Roles 4 | { 5 | public const string Admin = nameof(Admin); 6 | } 7 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Constants/Policies.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Identity 2 | { 3 | public class Policies 4 | { 5 | public const string HorarioComercial = nameof(HorarioComercial); 6 | } 7 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Constants/ClaimTypes.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Identity 2 | { 3 | public class ClaimTypes 4 | { 5 | public const string Categoria = nameof(Categoria); 6 | public const string Produto = nameof(Produto); 7 | } 8 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Interfaces/Services/IProdutoService.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | using Way2Commerce.Domain.Interfaces.Services.Shared; 3 | 4 | namespace Way2Commerce.Domain.Interfaces.Services; 5 | 6 | public interface IProdutoService : IServiceBase { } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Way2Commerce.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Interfaces/Repositories/IProdutoRepository.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | using Way2Commerce.Domain.Interfaces.Repositories.Shared; 3 | 4 | namespace Way2Commerce.Domain.Interfaces.Repositories; 5 | 6 | public interface IProdutoRepository : IRepositoryBase { } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Interfaces/Repositories/ICategoriaRepository.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | using Way2Commerce.Domain.Interfaces.Repositories.Shared; 3 | 4 | namespace Way2Commerce.Domain.Interfaces.Repositories; 5 | 6 | public interface ICategoriaRepository : IRepositoryBase { } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/PolicyRequirements/HorarioComercialRequirement.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace Way2Commerce.Identity.PolicyRequirements 4 | { 5 | public class HorarioComercialRequirement : IAuthorizationRequirement 6 | { 7 | public HorarioComercialRequirement() { } 8 | } 9 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Data/IdentityDataContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace Way2Commerce.Identity.Data 5 | { 6 | public class IdentityDataContext : IdentityDbContext 7 | { 8 | public IdentityDataContext(DbContextOptions options) : base(options) { } 9 | } 10 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Entities/Categoria.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities.Shared; 2 | 3 | namespace Way2Commerce.Domain.Entities; 4 | 5 | public class Categoria : Entity 6 | { 7 | public string Nome { get; set; } 8 | 9 | public ICollection Produtos { get; private set; } 10 | 11 | public Categoria(int id, string nome) 12 | { 13 | Id = id; 14 | Nome = nome; 15 | } 16 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/Way2Commerce.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Configurations/JwtOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.Tokens; 2 | 3 | namespace Way2Commerce.Identity.Configurations; 4 | 5 | public class JwtOptions 6 | { 7 | public string Issuer { get; set; } 8 | public string Audience { get; set; } 9 | public SigningCredentials SigningCredentials { get; set; } 10 | public int AccessTokenExpiration { get; set; } 11 | public int RefreshTokenExpiration { get; set; } 12 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Repositories/CategoriaRepository.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Data.Context; 2 | using Way2Commerce.Data.Repositories.Shared; 3 | using Way2Commerce.Domain.Entities; 4 | using Way2Commerce.Domain.Interfaces.Repositories; 5 | 6 | namespace Way2Commerce.Data.Repositories; 7 | 8 | public class CategoriaRepository : RepositoryBase, ICategoriaRepository 9 | { 10 | public CategoriaRepository(DataContext dataContext) : base(dataContext) { } 11 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Services/ProdutoService.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | using Way2Commerce.Domain.Interfaces.Repositories; 3 | using Way2Commerce.Domain.Interfaces.Services; 4 | using Way2Commerce.Domain.Services.Shared; 5 | 6 | namespace Way2Commerce.Domain.Services; 7 | 8 | public class ProdutoService : ServiceBase, IProdutoService 9 | { 10 | public ProdutoService(IProdutoRepository produtoRepository) : base(produtoRepository) { } 11 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Request/UsuarioLoginRequest.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Way2Commerce.Application.DTOs.Request; 4 | 5 | public class UsuarioLoginRequest 6 | { 7 | [Required(ErrorMessage = "O campo {0} é obrigatório")] 8 | [EmailAddress(ErrorMessage = "O campo {0} é inválido")] 9 | public string Email { get; set; } 10 | 11 | [Required(ErrorMessage = "O campo {0} é obrigatório")] 12 | public string Senha { get; set; } 13 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/Interfaces/Services/IIdentityService.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Application.DTOs.Request; 2 | using Way2Commerce.Application.DTOs.Response; 3 | 4 | namespace Way2Commerce.Application.Interfaces.Services; 5 | 6 | public interface IIdentityService 7 | { 8 | Task CadastrarUsuario(UsuarioCadastroRequest usuarioCadastro); 9 | Task Login(UsuarioLoginRequest usuarioLogin); 10 | Task LoginSemSenha(string usuarioId); 11 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Way2Commerce.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Interfaces/Services/Shared/IServiceBase.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities.Shared; 2 | 3 | namespace Way2Commerce.Domain.Interfaces.Services.Shared; 4 | 5 | public interface IServiceBase : IDisposable where TEntity : Entity 6 | { 7 | Task> ObterTodosAsync(); 8 | Task ObterPorIdAsync(int id); 9 | Task AdicionarAsync(TEntity objeto); 10 | Task AtualizarAsync(TEntity objeto); 11 | Task RemoverAsync(TEntity objeto); 12 | Task RemoverPorIdAsync(int id); 13 | } 14 | -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Interfaces/Repositories/Shared/IRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities.Shared; 2 | 3 | namespace Way2Commerce.Domain.Interfaces.Repositories.Shared; 4 | 5 | public interface IRepositoryBase : IDisposable where TEntity : Entity 6 | { 7 | Task> ObterTodosAsync(); 8 | Task ObterPorIdAsync(int id); 9 | Task AdicionarAsync(TEntity objeto); 10 | Task AtualizarAsync(TEntity objeto); 11 | Task RemoverAsync(TEntity objeto); 12 | Task RemoverPorIdAsync(int id); 13 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/Shared/ApiControllerBase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace Way2Commerce.Api.Controllers.Shared; 4 | 5 | // O ideal aqui seria termos um controller base para cada versão e setar o atributo ApiVersion. Ex: v1ControllerBase, v2ControllerBase, etc 6 | // Isso só não é possível ainda pois a biblioteca de versionamento não suporta isso. 7 | // Essa feature está em progresso e mapeada para vesão 3: https://github.com/dotnet/aspnet-api-versioning/issues/230 8 | [ApiController] 9 | [Route("api/v{version:apiVersion}")] 10 | public class ApiControllerBase : ControllerBase { } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Response/UsuarioCadastroResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Application.DTOs.Response 2 | { 3 | public class UsuarioCadastroResponse 4 | { 5 | public bool Sucesso { get; private set; } 6 | public List Erros { get; private set; } 7 | 8 | public UsuarioCadastroResponse() => 9 | Erros = new List(); 10 | 11 | public UsuarioCadastroResponse(bool sucesso = true) : this() => 12 | Sucesso = sucesso; 13 | 14 | public void AdicionarErros(IEnumerable erros) => 15 | Erros.AddRange(erros); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "Way2CommerceConnection": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=Way2Commerce;Integrated Security=True" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft.AspNetCore": "Warning" 9 | } 10 | }, 11 | "JwtOptions": { 12 | "Issuer": "http://localhost", 13 | "Audience": "Audience", 14 | "SecurityKey": "A494384E-8732-434C-AC6A-1D0E3396B981-514D0116-1251-4373-8682-C212A11D3FB0", 15 | "AccessTokenExpiration": 3600, 16 | "RefreshTokenExpiration": 10800 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Response/CategoriaResponse.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | 3 | namespace Way2Commerce.Application.DTOs.Response; 4 | 5 | public class CategoriaResponse 6 | { 7 | public int Id { get; set; } 8 | public string Nome { get; set; } 9 | 10 | public CategoriaResponse(int id, string nome) 11 | { 12 | Id = id; 13 | Nome = nome; 14 | } 15 | 16 | public static CategoriaResponse ConverterParaResponse(Categoria categoria) 17 | { 18 | return new CategoriaResponse 19 | ( 20 | categoria.Id, 21 | categoria.Nome 22 | ); 23 | } 24 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/PolicyRequirements/HorarioComercialHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace Way2Commerce.Identity.PolicyRequirements 4 | { 5 | public class HorarioComercialHandler : AuthorizationHandler 6 | { 7 | protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HorarioComercialRequirement requirement) 8 | { 9 | var horarioAtual = TimeOnly.FromDateTime(DateTime.Now); 10 | if (horarioAtual.Hour >= 8 && horarioAtual.Hour <= 18) 11 | context.Succeed(requirement); 12 | 13 | return Task.CompletedTask; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/Shared/ApiCollectionResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Way2Commerce.Api.Controllers.Shared 2 | { 3 | public class ApiCollectionResponse 4 | { 5 | public int Count { get; private set; } 6 | public IEnumerable Data { get; private set; } 7 | 8 | public ApiCollectionResponse(IEnumerable data) 9 | { 10 | Count = data.Count(); 11 | Data = data; 12 | } 13 | } 14 | 15 | public static class ApiCollectionResponseExtensions 16 | { 17 | public static ApiCollectionResponse ToApiCollectionResponse(this IEnumerable data) => 18 | new ApiCollectionResponse(data); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Extensions/ApiVersioningSetup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace Way2Commerce.Api.Extensions; 4 | 5 | public static class ApiVersioningSetup 6 | { 7 | public static void AddVersioning(this IServiceCollection services) 8 | { 9 | services.AddApiVersioning(options => 10 | { 11 | options.DefaultApiVersion = new ApiVersion(1, 0); 12 | options.AssumeDefaultVersionWhenUnspecified = true; 13 | options.ReportApiVersions = true; 14 | }); 15 | services.AddVersionedApiExplorer(options => 16 | { 17 | options.GroupNameFormat = "'v'VVV"; 18 | options.SubstituteApiVersionInUrl = true; 19 | }); 20 | } 21 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Request/UsuarioCadastroRequest.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Way2Commerce.Application.DTOs.Request; 4 | 5 | public class UsuarioCadastroRequest 6 | { 7 | [Required(ErrorMessage = "O campo {0} é obrigatório")] 8 | [EmailAddress(ErrorMessage = "O campo {0} é inválido")] 9 | public string Email { get; set; } 10 | 11 | [Required(ErrorMessage = "O campo {0} é obrigatório")] 12 | [StringLength(50, ErrorMessage = "O campo {0} deve ter entre {2} e {1} caracteres", MinimumLength = 6)] 13 | public string Senha { get; set; } 14 | 15 | [Compare(nameof(Senha), ErrorMessage = "As senhas devem ser iguais")] 16 | public string SenhaConfirmacao { get; set; } 17 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Way2Commerce.Identity.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Mappings/CategoriaMap.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using Way2Commerce.Domain.Entities; 4 | 5 | namespace Way2Commerce.Data.Mappings; 6 | 7 | public class CategoriaMap : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.ToTable("Categoria"); 12 | 13 | builder.Property(p => p.Id) 14 | .ValueGeneratedNever(); 15 | 16 | builder.Property(p => p.Nome) 17 | .HasMaxLength(100) 18 | .IsUnicode(false); 19 | 20 | builder.HasData(new[] 21 | { 22 | new Categoria(1, "Eletrodomésticos"), 23 | new Categoria(2, "Informática"), 24 | new Categoria(3, "Vestuário"), 25 | new Categoria(4, "Livros") 26 | }); 27 | } 28 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Context/DataContext.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.EntityFrameworkCore; 3 | using Way2Commerce.Domain.Entities; 4 | 5 | namespace Way2Commerce.Data.Context; 6 | 7 | public class DataContext : DbContext 8 | { 9 | public DataContext(DbContextOptions options) : base(options) { } 10 | 11 | protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) 12 | { 13 | configurationBuilder 14 | .Properties() 15 | .AreUnicode(false) 16 | .HaveMaxLength(500); 17 | } 18 | 19 | protected override void OnModelCreating(ModelBuilder modelBuilder) 20 | { 21 | modelBuilder 22 | .ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); 23 | } 24 | 25 | public DbSet Produtos { get; set; } 26 | public DbSet Categorias { get; set; } 27 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Api.Extensions; 2 | using Way2Commerce.Api.IoC; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | builder.Services.AddCors(); 7 | builder.Services.AddApiProblemDetails(); 8 | builder.Services.AddControllers(); 9 | builder.Services.AddRouting(options => options.LowercaseUrls = true); 10 | builder.Services.AddVersioning(); 11 | builder.Services.AddSwagger(); 12 | builder.Services.AddAuthentication(builder.Configuration); 13 | builder.Services.AddAuthorizationPolicies(); 14 | builder.Services.RegisterServices(builder.Configuration); 15 | 16 | var app = builder.Build(); 17 | 18 | app.UseSwaggerUI(); 19 | app.UseHttpsRedirection(); 20 | app.UseAuthentication(); 21 | app.UseAuthorization(); 22 | app.UseCors(builder => builder 23 | .SetIsOriginAllowed(orign => true) 24 | .AllowAnyMethod() 25 | .AllowAnyHeader() 26 | .AllowCredentials()); 27 | app.MapControllers(); 28 | 29 | app.Run(); -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Mappings/ProdutoMap.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using Way2Commerce.Domain.Entities; 4 | 5 | namespace Way2Commerce.Data.Mappings; 6 | 7 | public class ProdutoMap : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.ToTable("Produto"); 12 | 13 | builder.Property(p => p.Codigo) 14 | .HasMaxLength(6) 15 | .IsUnicode(false); 16 | 17 | builder.Property(p => p.Nome) 18 | .HasMaxLength(100) 19 | .IsUnicode(false); 20 | 21 | builder.Property(p => p.Preco) 22 | .HasPrecision(18, 2); 23 | 24 | builder.HasOne(p => p.Categoria) 25 | .WithMany(p => p.Produtos) 26 | .HasForeignKey(p => p.IdCategoria) 27 | .OnDelete(DeleteBehavior.NoAction); 28 | } 29 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:21174", 8 | "sslPort": 44336 9 | } 10 | }, 11 | "profiles": { 12 | "Way2Commerce.Api": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "", 17 | "applicationUrl": "https://localhost:7271;http://localhost:5029", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Repositories/ProdutoRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Way2Commerce.Data.Context; 3 | using Way2Commerce.Data.Repositories.Shared; 4 | using Way2Commerce.Domain.Entities; 5 | using Way2Commerce.Domain.Interfaces.Repositories; 6 | 7 | namespace Way2Commerce.Data.Repositories; 8 | 9 | public class ProdutoRepository : RepositoryBase, IProdutoRepository 10 | { 11 | public ProdutoRepository(DataContext dataContext) : base(dataContext) { } 12 | 13 | public async override Task> ObterTodosAsync() 14 | { 15 | return await Context.Produtos 16 | .Include(p => p.Categoria) 17 | .AsNoTracking() 18 | .ToListAsync(); 19 | } 20 | 21 | public async override Task ObterPorIdAsync(int id) 22 | { 23 | return await Context.Produtos 24 | .Include(p => p.Categoria) 25 | .FirstOrDefaultAsync(p => p.Id.Equals(id)); 26 | } 27 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Request/InsercaoProdutoRequest.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | 3 | namespace Way2Commerce.Application.DTOs.Request; 4 | 5 | public class InsercaoProdutoRequest 6 | { 7 | public string Codigo { get; set; } 8 | public int IdCategoria { get; set; } 9 | public string Nome { get; set; } 10 | public string Descricao { get; set; } 11 | public decimal Preco { get; set; } 12 | 13 | public InsercaoProdutoRequest(string codigo, int idCategoria, string nome, string descricao, decimal preco) 14 | { 15 | Codigo = codigo; 16 | IdCategoria = idCategoria; 17 | Nome = nome; 18 | Descricao = descricao; 19 | Preco = preco; 20 | } 21 | 22 | public static Produto ConverterParaEntidade(InsercaoProdutoRequest produtoRequest) 23 | { 24 | return new Produto 25 | ( 26 | produtoRequest.Codigo, 27 | produtoRequest.IdCategoria, 28 | produtoRequest.Nome, 29 | produtoRequest.Descricao, 30 | produtoRequest.Preco 31 | ); 32 | } 33 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Entities/Produto.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities.Shared; 2 | 3 | namespace Way2Commerce.Domain.Entities; 4 | 5 | public class Produto : Entity 6 | { 7 | public string Codigo { get; private set; } 8 | public int IdCategoria { get; private set; } 9 | public string Nome { get; private set; } 10 | public string Descricao { get; private set; } 11 | public decimal Preco { get; set; } 12 | public DateTime DataCadastro { get; private set; } 13 | 14 | public Categoria Categoria { get; private set; } 15 | 16 | public Produto(int id, string codigo, int idCategoria, string nome, string descricao, decimal preco) 17 | { 18 | Id = id; 19 | Codigo = codigo; 20 | IdCategoria = idCategoria; 21 | Nome = nome; 22 | Descricao = descricao; 23 | Preco = preco; 24 | DataCadastro = DateTime.Now; 25 | } 26 | 27 | public Produto(string codigo, int idCategoria, string nome, string descricao, decimal preco) 28 | : this(default, codigo, idCategoria, nome, descricao, preco) { } 29 | 30 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Response/UsuarioLoginResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace Way2Commerce.Application.DTOs.Response 4 | { 5 | public class UsuarioLoginResponse 6 | { 7 | public bool Sucesso => Erros.Count == 0; 8 | 9 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 10 | public string AccessToken { get; private set; } 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 12 | public string RefreshToken { get; private set; } 13 | 14 | public List Erros { get; private set; } 15 | 16 | public UsuarioLoginResponse() => 17 | Erros = new List(); 18 | 19 | public UsuarioLoginResponse(bool sucesso, string accessToken, string refreshToken) : this() 20 | { 21 | AccessToken = accessToken; 22 | RefreshToken = refreshToken; 23 | } 24 | 25 | public void AdicionarErro(string erro) => 26 | Erros.Add(erro); 27 | 28 | public void AdicionarErros(IEnumerable erros) => 29 | Erros.AddRange(erros); 30 | } 31 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Request/AtualizacaoProdutoRequest.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | 3 | namespace Way2Commerce.Application.DTOs.Request; 4 | 5 | public class AtualizacaoProdutoRequest 6 | { 7 | public int Id { get; set; } 8 | public string Codigo { get; set; } 9 | public int IdCategoria { get; set; } 10 | public string Nome { get; set; } 11 | public string Descricao { get; set; } 12 | public decimal Preco { get; set; } 13 | 14 | public AtualizacaoProdutoRequest(string codigo, int idCategoria, string nome, string descricao, decimal preco) 15 | { 16 | Codigo = codigo; 17 | IdCategoria = idCategoria; 18 | Nome = nome; 19 | Descricao = descricao; 20 | Preco = preco; 21 | } 22 | 23 | public static Produto ConverterParaEntidade(AtualizacaoProdutoRequest produtoRequest) 24 | { 25 | return new Produto 26 | ( 27 | produtoRequest.Id, 28 | produtoRequest.Codigo, 29 | produtoRequest.IdCategoria, 30 | produtoRequest.Nome, 31 | produtoRequest.Descricao, 32 | produtoRequest.Preco 33 | ); 34 | } 35 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Attributes/ClaimsAuthorizeAttribute.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | 5 | namespace Way2Commerce.Api.Attributes 6 | { 7 | public class ClaimsAuthorizeAttribute : TypeFilterAttribute 8 | { 9 | public ClaimsAuthorizeAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter)) => 10 | Arguments = new object[] { new Claim(claimType, claimValue) }; 11 | } 12 | 13 | public class ClaimRequirementFilter : IAuthorizationFilter 14 | { 15 | readonly Claim _claim; 16 | 17 | public ClaimRequirementFilter(Claim claim) => 18 | _claim = claim; 19 | 20 | public void OnAuthorization(AuthorizationFilterContext context) 21 | { 22 | var user = context.HttpContext.User as ClaimsPrincipal; 23 | 24 | if (user == null || !user.Identity.IsAuthenticated) 25 | { 26 | context.Result = new UnauthorizedResult(); 27 | return; 28 | } 29 | 30 | if (!user.HasClaim(_claim.Type, _claim.Value)) 31 | context.Result = new ForbidResult(); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /test/Way2Commerce.Domain.Tests/Way2Commerce.Domain.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /test/Way2Commerce.Data.Tests/Way2Commerce.Data.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/Way2Commerce.Application/DTOs/Response/ProdutoResponse.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities; 2 | 3 | namespace Way2Commerce.Application.DTOs.Response; 4 | 5 | public class ProdutoResponse 6 | { 7 | public int Id { get; set; } 8 | public string Codigo { get; set; } 9 | public string Nome { get; set; } 10 | public string Descricao { get; set; } 11 | public decimal Preco { get; set; } 12 | public DateTime DataCadastro { get; set; } 13 | public CategoriaResponse Categoria { get; set; } 14 | 15 | public ProdutoResponse(int id, string codigo, string nome, string descricao, decimal preco, DateTime dataCadastro, CategoriaResponse categoria) 16 | { 17 | Id = id; 18 | Codigo = codigo; 19 | Nome = nome; 20 | Descricao = descricao; 21 | Preco = preco; 22 | DataCadastro = dataCadastro; 23 | Categoria = categoria; 24 | } 25 | 26 | public static ProdutoResponse ConverterParaResponse(Produto produto) 27 | { 28 | return new ProdutoResponse 29 | ( 30 | produto.Id, 31 | produto.Codigo, 32 | produto.Nome, 33 | produto.Descricao, 34 | produto.Preco, 35 | produto.DataCadastro, 36 | new CategoriaResponse(produto.Categoria.Id, produto.Categoria.Nome) 37 | ); 38 | } 39 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Way2Commerce.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | true 8 | $(NoWarn);1591 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/Way2Commerce.Domain/Services/Shared/ServiceBase.cs: -------------------------------------------------------------------------------- 1 | using Way2Commerce.Domain.Entities.Shared; 2 | using Way2Commerce.Domain.Interfaces.Repositories.Shared; 3 | using Way2Commerce.Domain.Interfaces.Services.Shared; 4 | 5 | namespace Way2Commerce.Domain.Services.Shared; 6 | 7 | public abstract class ServiceBase : IServiceBase where TEntity : Entity 8 | { 9 | private readonly IRepositoryBase _repositoryBase; 10 | 11 | public ServiceBase(IRepositoryBase repositoryBase) => 12 | _repositoryBase = repositoryBase; 13 | 14 | public virtual async Task> ObterTodosAsync() => 15 | await _repositoryBase.ObterTodosAsync(); 16 | 17 | public virtual async Task ObterPorIdAsync(int id) => 18 | await _repositoryBase.ObterPorIdAsync(id); 19 | 20 | public virtual async Task AdicionarAsync(TEntity objeto) => 21 | await _repositoryBase.AdicionarAsync(objeto); 22 | 23 | public virtual async Task AtualizarAsync(TEntity objeto) => 24 | await _repositoryBase.AtualizarAsync(objeto); 25 | 26 | public virtual async Task RemoverAsync(TEntity objeto) => 27 | await _repositoryBase.RemoverAsync(objeto); 28 | 29 | public virtual async Task RemoverPorIdAsync(int id) => 30 | await _repositoryBase.RemoverPorIdAsync(id); 31 | 32 | public void Dispose() => 33 | _repositoryBase.Dispose(); 34 | } -------------------------------------------------------------------------------- /test/Way2Commerce.Data.Tests/Repositories/CategoriaRepositoryTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using FluentAssertions; 5 | using Way2Commerce.Data.Context; 6 | using Way2Commerce.Data.Repositories; 7 | using Way2Commerce.Data.Tests.Database; 8 | using Way2Commerce.Domain.Entities; 9 | using Xunit; 10 | 11 | namespace Way2Commerce.Data.Tests.Repositories 12 | { 13 | public class CategoriaRepositoryTests 14 | { 15 | private readonly DataContext _dataContext; 16 | private readonly DBInMemory _dbInMemory; 17 | private readonly CategoriaRepository _categoriaRepository; 18 | 19 | public CategoriaRepositoryTests() 20 | { 21 | _dbInMemory = new DBInMemory(); 22 | _dataContext = _dbInMemory.GetContext(); 23 | 24 | _categoriaRepository = new CategoriaRepository(_dataContext); 25 | } 26 | 27 | [Fact] 28 | public async Task ObterTodosAsync_Deve_Retornar_Todos_Os_Registros() 29 | { 30 | var categorias = await _categoriaRepository.ObterTodosAsync(); 31 | categorias.Should().HaveCount(4); 32 | } 33 | 34 | [Fact] 35 | public async Task ObterPorIdAsync_Deve_Retornar_Registro_Com_O_Id_Especificado() 36 | { 37 | var id = 2; 38 | var categoria = await _categoriaRepository.ObterPorIdAsync(id); 39 | categoria.Id.Should().Be(id); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/Shared/CustomProblemDetails.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace Way2Commerce.Api.Controllers.Shared 5 | { 6 | public class CustomProblemDetails : ProblemDetails 7 | { 8 | public List Errors { get; private set; } 9 | 10 | public CustomProblemDetails(HttpStatusCode status, string? detail = null, IEnumerable? errors = null) : this() 11 | { 12 | Title = status switch 13 | { 14 | HttpStatusCode.BadRequest => "One or more validation errors occurred.", 15 | HttpStatusCode.InternalServerError => "Internal server error.", 16 | _ => "An error has occurred." 17 | }; 18 | 19 | Status = (int)status; 20 | Detail = detail; 21 | 22 | if (errors is not null) 23 | { 24 | if (errors.Count() == 1) 25 | Detail = errors.First(); 26 | else if (errors.Count() > 1) 27 | Detail = "Multiple problems have occurred."; 28 | 29 | Errors.AddRange(errors); 30 | } 31 | } 32 | 33 | public CustomProblemDetails(HttpStatusCode status, HttpRequest request, string? detail = null, IEnumerable? errors = null) : this(status, detail, errors) => 34 | Instance = request.Path; 35 | 36 | private CustomProblemDetails() => 37 | Errors = new List(); 38 | } 39 | } -------------------------------------------------------------------------------- /test/Way2Commerce.Data.Tests/Database/DBInMemory.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Microsoft.Data.Sqlite; 3 | using Microsoft.EntityFrameworkCore; 4 | using Way2Commerce.Data.Context; 5 | using Way2Commerce.Domain.Entities; 6 | 7 | namespace Way2Commerce.Data.Tests.Database 8 | { 9 | public class DBInMemory 10 | { 11 | private readonly DataContext _dataContext; 12 | private readonly SqliteConnection _connection; 13 | 14 | public DBInMemory() 15 | { 16 | _connection = new SqliteConnection("DataSource=:memory:"); 17 | _connection.Open(); 18 | 19 | var options = new DbContextOptionsBuilder() 20 | .UseSqlite(_connection) 21 | .EnableSensitiveDataLogging() 22 | .Options; 23 | 24 | _dataContext = new DataContext(options); 25 | InsertFakeData(); 26 | } 27 | 28 | public DataContext GetContext() => _dataContext; 29 | 30 | public void Cleanup() => 31 | _connection.Close(); 32 | 33 | private void InsertFakeData() 34 | { 35 | if (_dataContext.Database.EnsureCreated()) 36 | { 37 | var idsProdutos = new[] { 1, 2, 3, 4 }; 38 | 39 | idsProdutos.ToList().ForEach(id => 40 | { 41 | _dataContext.Produtos.Add( 42 | new Produto(id, $"00000{id}", 1, $"Produto{id}", $"Descrição{id}", 10* id) 43 | ); 44 | }); 45 | 46 | _dataContext.SaveChanges(); 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/IoC/NativeInjectorConfig.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.EntityFrameworkCore; 3 | using Way2Commerce.Application.Interfaces.Services; 4 | using Way2Commerce.Data.Context; 5 | using Way2Commerce.Data.Repositories; 6 | using Way2Commerce.Domain.Interfaces.Repositories; 7 | using Way2Commerce.Domain.Interfaces.Services; 8 | using Way2Commerce.Domain.Services; 9 | using Way2Commerce.Identity.Data; 10 | using Way2Commerce.Identity.Services; 11 | 12 | namespace Way2Commerce.Api.IoC 13 | { 14 | public static class NativeInjectorConfig 15 | { 16 | public static void RegisterServices(this IServiceCollection services, IConfiguration configuration) 17 | { 18 | services.AddDbContext(options => 19 | options.UseSqlServer(configuration.GetConnectionString("Way2CommerceConnection")) 20 | ); 21 | 22 | services.AddDbContext(options => 23 | options.UseSqlServer(configuration.GetConnectionString("Way2CommerceConnection")) 24 | ); 25 | 26 | services.AddDefaultIdentity() 27 | .AddRoles() 28 | .AddEntityFrameworkStores() 29 | .AddDefaultTokenProviders(); 30 | 31 | services.AddScoped(); 32 | services.AddScoped(); 33 | services.AddScoped(); 34 | services.AddScoped(); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Repositories/Shared/RepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Way2Commerce.Data.Context; 3 | using Way2Commerce.Domain.Entities.Shared; 4 | using Way2Commerce.Domain.Interfaces.Repositories.Shared; 5 | 6 | namespace Way2Commerce.Data.Repositories.Shared; 7 | 8 | public abstract class RepositoryBase : IRepositoryBase where TEntity : Entity 9 | { 10 | protected readonly DataContext Context; 11 | 12 | public RepositoryBase(DataContext dataContext) => 13 | Context = dataContext; 14 | 15 | public virtual async Task> ObterTodosAsync() => 16 | await Context.Set() 17 | .AsNoTracking() 18 | .ToListAsync(); 19 | 20 | public virtual async Task ObterPorIdAsync(int id) => 21 | await Context.Set().FindAsync(id); 22 | 23 | public virtual async Task AdicionarAsync(TEntity objeto) 24 | { 25 | Context.Add(objeto); 26 | await Context.SaveChangesAsync(); 27 | return objeto.Id; 28 | } 29 | 30 | public virtual async Task AtualizarAsync(TEntity objeto) 31 | { 32 | Context.Entry(objeto).State = EntityState.Modified; 33 | await Context.SaveChangesAsync(); 34 | } 35 | 36 | public virtual async Task RemoverAsync(TEntity objeto) 37 | { 38 | Context.Set().Remove(objeto); 39 | await Context.SaveChangesAsync(); 40 | } 41 | 42 | public virtual async Task RemoverPorIdAsync(int id) 43 | { 44 | var objeto = await ObterPorIdAsync(id); 45 | if (objeto == null) 46 | throw new Exception("O registro não existe na base de dados."); 47 | await RemoverAsync(objeto); 48 | } 49 | 50 | public void Dispose() => 51 | Context.Dispose(); 52 | } -------------------------------------------------------------------------------- /.github/workflows/main_way2commerce.yml: -------------------------------------------------------------------------------- 1 | # Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy 2 | # More GitHub Actions for Azure: https://github.com/Azure/actions 3 | 4 | name: Build and deploy ASP.Net Core app to Azure Web App - way2commerce 5 | 6 | on: 7 | push: 8 | branches: 9 | - main 10 | workflow_dispatch: 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - name: Set up .NET Core 20 | uses: actions/setup-dotnet@v1 21 | with: 22 | dotnet-version: '6.0.x' 23 | include-prerelease: true 24 | 25 | - name: Build with dotnet 26 | run: dotnet build src/Way2Commerce.Api --configuration Release 27 | 28 | - name: dotnet publish 29 | run: dotnet publish src/Way2Commerce.Api -c Release -o ${{env.DOTNET_ROOT}}/myapp 30 | 31 | - name: Upload artifact for deployment job 32 | uses: actions/upload-artifact@v2 33 | with: 34 | name: .net-app 35 | path: ${{env.DOTNET_ROOT}}/myapp 36 | 37 | deploy: 38 | runs-on: ubuntu-latest 39 | needs: build 40 | environment: 41 | name: 'Production' 42 | url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} 43 | 44 | steps: 45 | - name: Download artifact from build job 46 | uses: actions/download-artifact@v2 47 | with: 48 | name: .net-app 49 | 50 | - name: Deploy to Azure Web App 51 | id: deploy-to-webapp 52 | uses: azure/webapps-deploy@v2 53 | with: 54 | app-name: 'way2commerce' 55 | slot-name: 'Production' 56 | publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_DA1F4E046B9147EFB1AF3649E3FEE141 }} 57 | package: . 58 | -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Extensions/ProblemDetailsSetup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Diagnostics; 2 | using System.Text.Json; 3 | 4 | namespace Way2Commerce.Api.Extensions; 5 | public static class ProblemDetailsSetup 6 | { 7 | private static Dictionary _mapping = new Dictionary 8 | { 9 | { typeof(UnauthorizedAccessException), StatusCodes.Status401Unauthorized }, 10 | { typeof(JsonException), StatusCodes.Status400BadRequest }, 11 | { typeof(ArgumentException), StatusCodes.Status400BadRequest }, 12 | { typeof(ArgumentNullException), StatusCodes.Status400BadRequest }, 13 | { typeof(NotImplementedException), StatusCodes.Status501NotImplemented }, 14 | { typeof(HttpRequestException), StatusCodes.Status503ServiceUnavailable }, 15 | { typeof(Exception), StatusCodes.Status500InternalServerError }, 16 | }; 17 | 18 | public static void AddApiProblemDetails(this IServiceCollection services) 19 | { 20 | services.AddProblemDetails(options => 21 | { 22 | options.CustomizeProblemDetails = (context) => context.MapExceptionToStatusCode(); 23 | }); 24 | } 25 | 26 | public static void MapExceptionToStatusCode(this ProblemDetailsContext context) 27 | { 28 | var env = context.HttpContext.RequestServices.GetRequiredService(); 29 | var exception = context.HttpContext.Features.Get()?.Error; 30 | 31 | if (exception is not null) 32 | { 33 | var statusCode = _mapping.GetValueOrDefault(exception.GetType(), context.HttpContext.Response.StatusCode); 34 | context.HttpContext.Response.StatusCode = statusCode; 35 | context.ProblemDetails.Status = statusCode; 36 | context.ProblemDetails.Detail = env.IsDevelopment() || env.IsStaging() ? context.ProblemDetails.Detail : null; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/v1/CategoriaController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Way2Commerce.Api.Controllers.Shared; 4 | using Way2Commerce.Application.DTOs.Response; 5 | using Way2Commerce.Domain.Interfaces.Repositories; 6 | 7 | namespace Way2Commerce.Api.Controllers.v1; 8 | 9 | [Authorize] 10 | [ApiVersion("1.0")] 11 | public class CategoriaController : ApiControllerBase 12 | { 13 | private ICategoriaRepository _categoriaRepository; 14 | 15 | public CategoriaController(ICategoriaRepository categoriaRepository) => 16 | _categoriaRepository = categoriaRepository; 17 | 18 | /// 19 | /// Obtém todas as categorias. 20 | /// 21 | /// 22 | /// 23 | /// 24 | /// Retorna todas as categorias cadastradas 25 | /// Retorna erros caso ocorram 26 | [ProducesResponseType(typeof(ApiCollectionResponse), StatusCodes.Status200OK)] 27 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 28 | [Route("categorias")] 29 | [HttpGet] 30 | public async Task>> ObterTodas() 31 | { 32 | var categorias = await _categoriaRepository.ObterTodosAsync(); 33 | var categoriasResponse = categorias.Select(categoria => CategoriaResponse.ConverterParaResponse(categoria)); 34 | return Ok(categoriasResponse.ToApiCollectionResponse()); 35 | } 36 | 37 | 38 | /// 39 | /// Obtém categoria por Id. 40 | /// 41 | /// 42 | /// 43 | /// Id da categoria 44 | /// 45 | /// Retorna os dados da categoria 46 | /// Retorno caso a categoria não seja encontrada 47 | /// Retorna erros caso ocorram 48 | [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] 49 | [ProducesResponseType(StatusCodes.Status404NotFound)] 50 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 51 | [HttpGet("categorias/{id}")] 52 | public async Task> ObterPorId(int id) 53 | { 54 | var categoria = await _categoriaRepository.ObterPorIdAsync(id); 55 | if (categoria is null) 56 | return NotFound(); 57 | 58 | var categoriaResponse = CategoriaResponse.ConverterParaResponse(categoria); 59 | return Ok(categoriaResponse); 60 | } 61 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Extensions/SwaggerSetup.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 3 | using Microsoft.OpenApi.Models; 4 | using Swashbuckle.AspNetCore.SwaggerUI; 5 | 6 | namespace Way2Commerce.Api.Extensions; 7 | 8 | public static class SwaggerSetup 9 | { 10 | public static void AddSwagger(this IServiceCollection services) 11 | { 12 | services.AddEndpointsApiExplorer(); 13 | services.AddSwaggerGen(options => 14 | { 15 | var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; 16 | var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); 17 | options.IncludeXmlComments(xmlPath); 18 | 19 | options.SwaggerDoc("v1", new OpenApiInfo 20 | { 21 | Title = "Way2Commerce.Api", 22 | Version = "v1" 23 | }); 24 | 25 | options.SwaggerDoc("v2", new OpenApiInfo 26 | { 27 | Title = "Way2Commerce.Api", 28 | Version = "v2" 29 | }); 30 | 31 | options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 32 | { 33 | Description = @"JWT Authorization header using the Bearer scheme. 34 | Enter 'Bearer' [space] and then your token in the text input below. 35 | Example: 'Bearer 12345abcdef'", 36 | Name = "Authorization", 37 | In = ParameterLocation.Header, 38 | Type = SecuritySchemeType.ApiKey, 39 | Scheme = "Bearer" 40 | }); 41 | 42 | options.AddSecurityRequirement(new OpenApiSecurityRequirement() 43 | { 44 | { 45 | new OpenApiSecurityScheme 46 | { 47 | Reference = new OpenApiReference 48 | { 49 | Type = ReferenceType.SecurityScheme, 50 | Id = "Bearer" 51 | }, 52 | Scheme = "oauth2", 53 | Name = "Bearer", 54 | In = ParameterLocation.Header, 55 | 56 | }, 57 | new List() 58 | } 59 | }); 60 | }); 61 | } 62 | 63 | public static void UseSwaggerUI(this WebApplication app) 64 | { 65 | app.UseSwagger(); 66 | app.UseSwaggerUI(options => 67 | { 68 | var apiVersionProvider = app.Services.GetService(); 69 | if (apiVersionProvider == null) 70 | throw new ArgumentException("API Versioning not registered."); 71 | 72 | foreach (var description in apiVersionProvider.ApiVersionDescriptions) 73 | { 74 | options.SwaggerEndpoint( 75 | $"/swagger/{description.GroupName}/swagger.json", 76 | description.GroupName); 77 | } 78 | options.RoutePrefix = string.Empty; 79 | 80 | options.DocExpansion(DocExpansion.List); 81 | }); 82 | } 83 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Migrations/20211224171716_Initial.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace Way2Commerce.Data.Migrations 7 | { 8 | public partial class Initial : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "Categoria", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "int", nullable: false), 17 | Nome = table.Column(type: "varchar(100)", unicode: false, maxLength: 100, nullable: false) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_Categoria", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "Produto", 26 | columns: table => new 27 | { 28 | Id = table.Column(type: "int", nullable: false) 29 | .Annotation("SqlServer:Identity", "1, 1"), 30 | Codigo = table.Column(type: "varchar(6)", unicode: false, maxLength: 6, nullable: false), 31 | IdCategoria = table.Column(type: "int", nullable: false), 32 | Nome = table.Column(type: "varchar(100)", unicode: false, maxLength: 100, nullable: false), 33 | Descricao = table.Column(type: "varchar(500)", unicode: false, maxLength: 500, nullable: false), 34 | Preco = table.Column(type: "decimal(18,2)", precision: 18, scale: 2, nullable: false), 35 | DataCadastro = table.Column(type: "datetime2", nullable: false) 36 | }, 37 | constraints: table => 38 | { 39 | table.PrimaryKey("PK_Produto", x => x.Id); 40 | table.ForeignKey( 41 | name: "FK_Produto_Categoria_IdCategoria", 42 | column: x => x.IdCategoria, 43 | principalTable: "Categoria", 44 | principalColumn: "Id"); 45 | }); 46 | 47 | migrationBuilder.InsertData( 48 | table: "Categoria", 49 | columns: new[] { "Id", "Nome" }, 50 | values: new object[,] 51 | { 52 | { 1, "Eletrodomésticos" }, 53 | { 2, "Informática" }, 54 | { 3, "Vestuário" }, 55 | { 4, "Livros" } 56 | }); 57 | 58 | migrationBuilder.CreateIndex( 59 | name: "IX_Produto_IdCategoria", 60 | table: "Produto", 61 | column: "IdCategoria"); 62 | } 63 | 64 | protected override void Down(MigrationBuilder migrationBuilder) 65 | { 66 | migrationBuilder.DropTable( 67 | name: "Produto"); 68 | 69 | migrationBuilder.DropTable( 70 | name: "Categoria"); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /test/Way2Commerce.Domain.Tests/Services/ProdutoServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using FluentAssertions; 4 | using NSubstitute; 5 | using Way2Commerce.Domain.Entities; 6 | using Way2Commerce.Domain.Interfaces.Repositories; 7 | using Way2Commerce.Domain.Services; 8 | using Xunit; 9 | 10 | namespace Way2Commerce.Domain.Tests.Services 11 | { 12 | public class ProdutoServiceTests 13 | { 14 | private readonly ProdutoService _produtoService; 15 | private readonly IProdutoRepository _produtoRepository; 16 | private readonly Produto _produto; 17 | 18 | public ProdutoServiceTests() 19 | { 20 | _produto = new Produto("000001", 1, "Produto1", "Descrição1", 59.90m); 21 | _produtoRepository = Substitute.For(); 22 | 23 | _produtoService = new ProdutoService(_produtoRepository); 24 | } 25 | 26 | [Fact] 27 | public async Task ObterTodosAsync_Deve_Retornar_Todos_Os_Registros() 28 | { 29 | _produtoRepository.ObterTodosAsync() 30 | .Returns(new List { 31 | _produto, 32 | _produto, 33 | _produto 34 | }); 35 | 36 | var produtos = await _produtoService.ObterTodosAsync(); 37 | produtos.Should().HaveCount(3); 38 | } 39 | 40 | [Fact] 41 | public async Task ObterPorIdAsync_Deve_Retornar_Registro_Com_O_Id_Especificado() 42 | { 43 | var id = 1; 44 | _produtoRepository.ObterPorIdAsync(id) 45 | .Returns(_produto); 46 | 47 | var produto = await _produtoService.ObterPorIdAsync(id); 48 | produto.Id.Should().Be(_produto.Id); 49 | } 50 | 51 | [Fact] 52 | public async Task AdicionarAsync_Deve_Adicionar_Produto_E_Retornar_Id() 53 | { 54 | var id = 1; 55 | _produtoRepository.AdicionarAsync(_produto) 56 | .Returns(id); 57 | 58 | var idNovoRegistro = await _produtoService.AdicionarAsync(_produto); 59 | idNovoRegistro.Should().Be(id); 60 | } 61 | 62 | [Fact] 63 | public async Task AtualizarAsync_Deve_Atualizar_Produto() 64 | { 65 | _produtoRepository.AtualizarAsync(_produto) 66 | .Returns(Task.CompletedTask); 67 | 68 | await _produtoService.AtualizarAsync(_produto); 69 | await _produtoRepository.Received().AtualizarAsync(_produto); 70 | } 71 | 72 | [Fact] 73 | public async Task RemoverAsync_Deve_Remover_Produto() 74 | { 75 | _produtoRepository.RemoverAsync(_produto) 76 | .Returns(Task.CompletedTask); 77 | 78 | await _produtoService.RemoverAsync(_produto); 79 | await _produtoRepository.Received().RemoverAsync(_produto); 80 | } 81 | 82 | [Fact] 83 | public async Task RemoverPorIdAsync_Deve_Remover_Produto() 84 | { 85 | var id = 1; 86 | _produtoRepository.RemoverPorIdAsync(id) 87 | .Returns(Task.CompletedTask); 88 | 89 | await _produtoService.RemoverPorIdAsync(id); 90 | await _produtoRepository.Received().RemoverPorIdAsync(id); 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Extensions/AuthenticationSetup.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Identity; 5 | using Microsoft.IdentityModel.Tokens; 6 | using Way2Commerce.Identity; 7 | using Way2Commerce.Identity.Configurations; 8 | using Way2Commerce.Identity.PolicyRequirements; 9 | 10 | namespace Way2Commerce.Api.Extensions 11 | { 12 | public static class AuthenticationSetup 13 | { 14 | public static void AddAuthentication(this IServiceCollection services, IConfiguration configuration) 15 | { 16 | var jwtAppSettingOptions = configuration.GetSection(nameof(JwtOptions)); 17 | var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration.GetSection("JwtOptions:SecurityKey").Value)); 18 | 19 | services.Configure(options => 20 | { 21 | options.Issuer = jwtAppSettingOptions[nameof(JwtOptions.Issuer)]; 22 | options.Audience = jwtAppSettingOptions[nameof(JwtOptions.Audience)]; 23 | options.SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512); 24 | options.AccessTokenExpiration = int.Parse(jwtAppSettingOptions[nameof(JwtOptions.AccessTokenExpiration)] ?? "0"); 25 | options.RefreshTokenExpiration = int.Parse(jwtAppSettingOptions[nameof(JwtOptions.RefreshTokenExpiration)] ?? "0"); 26 | }); 27 | 28 | services.Configure(options => 29 | { 30 | options.Password.RequireDigit = true; 31 | options.Password.RequireLowercase = true; 32 | options.Password.RequireNonAlphanumeric = true; 33 | options.Password.RequireUppercase = true; 34 | options.Password.RequiredLength = 6; 35 | }); 36 | 37 | var tokenValidationParameters = new TokenValidationParameters 38 | { 39 | ValidateIssuer = true, 40 | ValidIssuer = configuration.GetSection("JwtOptions:Issuer").Value, 41 | 42 | ValidateAudience = true, 43 | ValidAudience = configuration.GetSection("JwtOptions:Audience").Value, 44 | 45 | ValidateIssuerSigningKey = true, 46 | IssuerSigningKey = securityKey, 47 | 48 | RequireExpirationTime = true, 49 | ValidateLifetime = true, 50 | 51 | ClockSkew = TimeSpan.Zero 52 | }; 53 | 54 | services.AddAuthentication(options => 55 | { 56 | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 57 | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 58 | }).AddJwtBearer(options => 59 | { 60 | options.TokenValidationParameters = tokenValidationParameters; 61 | }); 62 | } 63 | 64 | public static void AddAuthorizationPolicies(this IServiceCollection services) 65 | { 66 | services.AddSingleton(); 67 | services.AddAuthorization(options => 68 | { 69 | options.AddPolicy(Policies.HorarioComercial, policy => 70 | policy.Requirements.Add(new HorarioComercialRequirement())); 71 | }); 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /test/Way2Commerce.Data.Tests/Repositories/ProdutoRepositoryTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using FluentAssertions; 5 | using Way2Commerce.Data.Context; 6 | using Way2Commerce.Data.Repositories; 7 | using Way2Commerce.Data.Tests.Database; 8 | using Way2Commerce.Domain.Entities; 9 | using Xunit; 10 | 11 | namespace Way2Commerce.Data.Tests.Repositories 12 | { 13 | public class ProdutoRepositoryTests 14 | { 15 | private readonly DataContext _dataContext; 16 | private readonly DBInMemory _dbInMemory; 17 | private readonly ProdutoRepository _produtoRepository; 18 | 19 | public ProdutoRepositoryTests() 20 | { 21 | _dbInMemory = new DBInMemory(); 22 | _dataContext = _dbInMemory.GetContext(); 23 | 24 | _produtoRepository = new ProdutoRepository(_dataContext); 25 | } 26 | 27 | [Fact] 28 | public async Task ObterTodosAsync_Deve_Retornar_Todos_Os_Registros() 29 | { 30 | var produtos = await _produtoRepository.ObterTodosAsync(); 31 | produtos.Should().HaveCount(4); 32 | produtos.FirstOrDefault().Categoria.Should().NotBeNull(); 33 | } 34 | 35 | [Fact] 36 | public async Task ObterPorIdAsync_Deve_Retornar_Registro_Com_O_Id_Especificado() 37 | { 38 | var id = 2; 39 | var produto = await _produtoRepository.ObterPorIdAsync(id); 40 | produto.Id.Should().Be(id); 41 | produto.Categoria.Should().NotBeNull(); 42 | } 43 | 44 | [Fact] 45 | public async Task AdicionarAsync_Deve_Adicionar_Produto_E_Retornar_Id() 46 | { 47 | var produto = new Produto("000005", 4, "Produto5", "Descrição5", 50.00m); 48 | var id = await _produtoRepository.AdicionarAsync(produto); 49 | id.Should().Be(produto.Id); 50 | } 51 | 52 | [Fact] 53 | public async Task AtualizarAsync_Deve_Atualizar_Produto() 54 | { 55 | var novoPreco = 109.99m; 56 | 57 | var produto = await _produtoRepository.ObterPorIdAsync(1); 58 | produto.Preco = novoPreco; 59 | await _produtoRepository.AtualizarAsync(produto); 60 | 61 | produto = await _produtoRepository.ObterPorIdAsync(1); 62 | produto.Preco.Should().Be(novoPreco); 63 | } 64 | 65 | [Fact] 66 | public async Task RemoverAsync_Deve_Remover_Produto() 67 | { 68 | var id = 3; 69 | var produto = await _produtoRepository.ObterPorIdAsync(id); 70 | await _produtoRepository.RemoverAsync(produto); 71 | 72 | var produtoExcluido = await _produtoRepository.ObterPorIdAsync(id); 73 | produtoExcluido.Should().BeNull(); 74 | } 75 | 76 | [Fact] 77 | public async Task RemoverPorIdAsync_Deve_Remover_Produto() 78 | { 79 | var id = 3; 80 | await _produtoRepository.RemoverPorIdAsync(id); 81 | 82 | var produtoExcluido = await _produtoRepository.ObterPorIdAsync(id); 83 | produtoExcluido.Should().BeNull(); 84 | } 85 | 86 | [Fact] 87 | public async Task RemoverPorIdAsync_Deve_Lancar_Excecao_Para_Registro_Inexistente() 88 | { 89 | var id = 100; 90 | await FluentActions.Invoking(async () => await _produtoRepository.RemoverPorIdAsync(id)) 91 | .Should().ThrowAsync("O registro não existe na base de dados."); 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Migrations/DataContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Way2Commerce.Data.Context; 8 | 9 | #nullable disable 10 | 11 | namespace Way2Commerce.Data.Migrations 12 | { 13 | [DbContext(typeof(DataContext))] 14 | partial class DataContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.1") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Categoria", b => 26 | { 27 | b.Property("Id") 28 | .HasColumnType("int"); 29 | 30 | b.Property("Nome") 31 | .IsRequired() 32 | .HasMaxLength(100) 33 | .IsUnicode(false) 34 | .HasColumnType("varchar(100)"); 35 | 36 | b.HasKey("Id"); 37 | 38 | b.ToTable("Categoria", (string)null); 39 | 40 | b.HasData( 41 | new 42 | { 43 | Id = 1, 44 | Nome = "Eletrodomésticos" 45 | }, 46 | new 47 | { 48 | Id = 2, 49 | Nome = "Informática" 50 | }, 51 | new 52 | { 53 | Id = 3, 54 | Nome = "Vestuário" 55 | }, 56 | new 57 | { 58 | Id = 4, 59 | Nome = "Livros" 60 | }); 61 | }); 62 | 63 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Produto", b => 64 | { 65 | b.Property("Id") 66 | .ValueGeneratedOnAdd() 67 | .HasColumnType("int"); 68 | 69 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 70 | 71 | b.Property("Codigo") 72 | .IsRequired() 73 | .HasMaxLength(6) 74 | .IsUnicode(false) 75 | .HasColumnType("varchar(6)"); 76 | 77 | b.Property("DataCadastro") 78 | .HasColumnType("datetime2"); 79 | 80 | b.Property("Descricao") 81 | .IsRequired() 82 | .HasMaxLength(500) 83 | .IsUnicode(false) 84 | .HasColumnType("varchar(500)"); 85 | 86 | b.Property("IdCategoria") 87 | .HasColumnType("int"); 88 | 89 | b.Property("Nome") 90 | .IsRequired() 91 | .HasMaxLength(100) 92 | .IsUnicode(false) 93 | .HasColumnType("varchar(100)"); 94 | 95 | b.Property("Preco") 96 | .HasPrecision(18, 2) 97 | .HasColumnType("decimal(18,2)"); 98 | 99 | b.HasKey("Id"); 100 | 101 | b.HasIndex("IdCategoria"); 102 | 103 | b.ToTable("Produto", (string)null); 104 | }); 105 | 106 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Produto", b => 107 | { 108 | b.HasOne("Way2Commerce.Domain.Entities.Categoria", "Categoria") 109 | .WithMany("Produtos") 110 | .HasForeignKey("IdCategoria") 111 | .OnDelete(DeleteBehavior.NoAction) 112 | .IsRequired(); 113 | 114 | b.Navigation("Categoria"); 115 | }); 116 | 117 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Categoria", b => 118 | { 119 | b.Navigation("Produtos"); 120 | }); 121 | #pragma warning restore 612, 618 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/v1/UsuarioController.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Security.Claims; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Way2Commerce.Api.Controllers.Shared; 6 | using Way2Commerce.Application.DTOs.Request; 7 | using Way2Commerce.Application.DTOs.Response; 8 | using Way2Commerce.Application.Interfaces.Services; 9 | 10 | namespace Way2Commerce.Api.Controllers.v1; 11 | 12 | [ApiVersion("1.0")] 13 | public class UsuarioController : ApiControllerBase 14 | { 15 | private IIdentityService _identityService; 16 | 17 | public UsuarioController(IIdentityService identityService) => 18 | _identityService = identityService; 19 | 20 | /// 21 | /// Cadastro de usuário. 22 | /// 23 | /// 24 | /// 25 | /// Dados de cadastro do usuário 26 | /// 27 | /// Usuário criado com sucesso 28 | /// Retorna erros de validação 29 | /// Retorna erros caso ocorram 30 | [ProducesResponseType(typeof(UsuarioCadastroResponse), StatusCodes.Status200OK)] 31 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 32 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 33 | [HttpPost("usuario/cadastro")] 34 | public async Task Cadastrar(UsuarioCadastroRequest usuarioCadastro) 35 | { 36 | if (!ModelState.IsValid) 37 | return BadRequest(); 38 | 39 | var resultado = await _identityService.CadastrarUsuario(usuarioCadastro); 40 | if (resultado.Sucesso) 41 | return Ok(resultado); 42 | else if (resultado.Erros.Count > 0) 43 | { 44 | var problemDetails = new CustomProblemDetails(HttpStatusCode.BadRequest, Request, errors: resultado.Erros); 45 | return BadRequest(problemDetails); 46 | } 47 | 48 | return StatusCode(StatusCodes.Status500InternalServerError); 49 | } 50 | 51 | /// 52 | /// Login do usuário via usuário/senha. 53 | /// 54 | /// 55 | /// 56 | /// Dados de login do usuário 57 | /// 58 | /// Login realizado com sucesso 59 | /// Retorna erros de validação 60 | /// Erro caso usuário não esteja autorizado 61 | /// Retorna erros caso ocorram 62 | [ProducesResponseType(typeof(UsuarioCadastroResponse), StatusCodes.Status200OK)] 63 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 64 | [ProducesResponseType(StatusCodes.Status401Unauthorized)] 65 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 66 | [HttpPost("usuario/login")] 67 | public async Task> Login(UsuarioLoginRequest usuarioLogin) 68 | { 69 | if (!ModelState.IsValid) 70 | return BadRequest(); 71 | 72 | var resultado = await _identityService.Login(usuarioLogin); 73 | if (resultado.Sucesso) 74 | return Ok(resultado); 75 | 76 | return Unauthorized(); 77 | } 78 | 79 | /// 80 | /// Login do usuário via refresh token. 81 | /// 82 | /// 83 | /// 84 | /// 85 | /// Login realizado com sucesso 86 | /// Retorna erros de validação 87 | /// Erro caso usuário não esteja autorizado 88 | /// Retorna erros caso ocorram 89 | [ProducesResponseType(typeof(UsuarioCadastroResponse), StatusCodes.Status200OK)] 90 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 91 | [ProducesResponseType(StatusCodes.Status401Unauthorized)] 92 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 93 | [Authorize] 94 | [HttpPost("usuario/refresh-login")] 95 | public async Task> RefreshLogin() 96 | { 97 | var identity = HttpContext.User.Identity as ClaimsIdentity; 98 | var usuarioId = identity?.FindFirst(ClaimTypes.NameIdentifier)?.Value; 99 | if (usuarioId == null) 100 | return BadRequest(); 101 | 102 | var resultado = await _identityService.LoginSemSenha(usuarioId); 103 | if (resultado.Sucesso) 104 | return Ok(resultado); 105 | 106 | return Unauthorized(); 107 | } 108 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Data/Migrations/20211224171716_Initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using Way2Commerce.Data.Context; 9 | 10 | #nullable disable 11 | 12 | namespace Way2Commerce.Data.Migrations 13 | { 14 | [DbContext(typeof(DataContext))] 15 | [Migration("20211224171716_Initial")] 16 | partial class Initial 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.1") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Categoria", b => 28 | { 29 | b.Property("Id") 30 | .HasColumnType("int"); 31 | 32 | b.Property("Nome") 33 | .IsRequired() 34 | .HasMaxLength(100) 35 | .IsUnicode(false) 36 | .HasColumnType("varchar(100)"); 37 | 38 | b.HasKey("Id"); 39 | 40 | b.ToTable("Categoria", (string)null); 41 | 42 | b.HasData( 43 | new 44 | { 45 | Id = 1, 46 | Nome = "Eletrodomésticos" 47 | }, 48 | new 49 | { 50 | Id = 2, 51 | Nome = "Informática" 52 | }, 53 | new 54 | { 55 | Id = 3, 56 | Nome = "Vestuário" 57 | }, 58 | new 59 | { 60 | Id = 4, 61 | Nome = "Livros" 62 | }); 63 | }); 64 | 65 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Produto", b => 66 | { 67 | b.Property("Id") 68 | .ValueGeneratedOnAdd() 69 | .HasColumnType("int"); 70 | 71 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 72 | 73 | b.Property("Codigo") 74 | .IsRequired() 75 | .HasMaxLength(6) 76 | .IsUnicode(false) 77 | .HasColumnType("varchar(6)"); 78 | 79 | b.Property("DataCadastro") 80 | .HasColumnType("datetime2"); 81 | 82 | b.Property("Descricao") 83 | .IsRequired() 84 | .HasMaxLength(500) 85 | .IsUnicode(false) 86 | .HasColumnType("varchar(500)"); 87 | 88 | b.Property("IdCategoria") 89 | .HasColumnType("int"); 90 | 91 | b.Property("Nome") 92 | .IsRequired() 93 | .HasMaxLength(100) 94 | .IsUnicode(false) 95 | .HasColumnType("varchar(100)"); 96 | 97 | b.Property("Preco") 98 | .HasPrecision(18, 2) 99 | .HasColumnType("decimal(18,2)"); 100 | 101 | b.HasKey("Id"); 102 | 103 | b.HasIndex("IdCategoria"); 104 | 105 | b.ToTable("Produto", (string)null); 106 | }); 107 | 108 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Produto", b => 109 | { 110 | b.HasOne("Way2Commerce.Domain.Entities.Categoria", "Categoria") 111 | .WithMany("Produtos") 112 | .HasForeignKey("IdCategoria") 113 | .OnDelete(DeleteBehavior.NoAction) 114 | .IsRequired(); 115 | 116 | b.Navigation("Categoria"); 117 | }); 118 | 119 | modelBuilder.Entity("Way2Commerce.Domain.Entities.Categoria", b => 120 | { 121 | b.Navigation("Produtos"); 122 | }); 123 | #pragma warning restore 612, 618 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /Way2Commerce.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30114.105 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5B194365-E498-4DE5-BD41-485B20D488C8}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0753C455-1E69-49BF-B290-89B68381A996}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Way2Commerce.Domain", "src\Way2Commerce.Domain\Way2Commerce.Domain.csproj", "{549B657C-7F5E-401A-B053-3CE46DB47A1E}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Way2Commerce.Data", "src\Way2Commerce.Data\Way2Commerce.Data.csproj", "{AF403D63-BE8C-40CD-A76C-EE978448E51C}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Way2Commerce.Api", "src\Way2Commerce.Api\Way2Commerce.Api.csproj", "{DACC224F-3880-4E66-BA51-2060E2DEB99D}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Way2Commerce.Domain.Tests", "test\Way2Commerce.Domain.Tests\Way2Commerce.Domain.Tests.csproj", "{8CDDA110-7134-4ADF-A103-BB53A02BFC33}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Way2Commerce.Data.Tests", "test\Way2Commerce.Data.Tests\Way2Commerce.Data.Tests.csproj", "{0A857674-B93B-4524-9799-3529E30C0B59}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Way2Commerce.Identity", "src\Way2Commerce.Identity\Way2Commerce.Identity.csproj", "{40428569-3C78-4B2F-9FD8-B12E1E9B1C38}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Way2Commerce.Application", "src\Way2Commerce.Application\Way2Commerce.Application.csproj", "{4BE132DA-2561-415D-A1B9-7B3E72794DAB}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {549B657C-7F5E-401A-B053-3CE46DB47A1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {549B657C-7F5E-401A-B053-3CE46DB47A1E}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {549B657C-7F5E-401A-B053-3CE46DB47A1E}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {549B657C-7F5E-401A-B053-3CE46DB47A1E}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {AF403D63-BE8C-40CD-A76C-EE978448E51C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {AF403D63-BE8C-40CD-A76C-EE978448E51C}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {AF403D63-BE8C-40CD-A76C-EE978448E51C}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {AF403D63-BE8C-40CD-A76C-EE978448E51C}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {DACC224F-3880-4E66-BA51-2060E2DEB99D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {DACC224F-3880-4E66-BA51-2060E2DEB99D}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {DACC224F-3880-4E66-BA51-2060E2DEB99D}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {DACC224F-3880-4E66-BA51-2060E2DEB99D}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {8CDDA110-7134-4ADF-A103-BB53A02BFC33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {8CDDA110-7134-4ADF-A103-BB53A02BFC33}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {8CDDA110-7134-4ADF-A103-BB53A02BFC33}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {8CDDA110-7134-4ADF-A103-BB53A02BFC33}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {0A857674-B93B-4524-9799-3529E30C0B59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {0A857674-B93B-4524-9799-3529E30C0B59}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {0A857674-B93B-4524-9799-3529E30C0B59}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {0A857674-B93B-4524-9799-3529E30C0B59}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {40428569-3C78-4B2F-9FD8-B12E1E9B1C38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {40428569-3C78-4B2F-9FD8-B12E1E9B1C38}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {40428569-3C78-4B2F-9FD8-B12E1E9B1C38}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {40428569-3C78-4B2F-9FD8-B12E1E9B1C38}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {4BE132DA-2561-415D-A1B9-7B3E72794DAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {4BE132DA-2561-415D-A1B9-7B3E72794DAB}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {4BE132DA-2561-415D-A1B9-7B3E72794DAB}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {4BE132DA-2561-415D-A1B9-7B3E72794DAB}.Release|Any CPU.Build.0 = Release|Any CPU 58 | EndGlobalSection 59 | GlobalSection(SolutionProperties) = preSolution 60 | HideSolutionNode = FALSE 61 | EndGlobalSection 62 | GlobalSection(NestedProjects) = preSolution 63 | {549B657C-7F5E-401A-B053-3CE46DB47A1E} = {5B194365-E498-4DE5-BD41-485B20D488C8} 64 | {AF403D63-BE8C-40CD-A76C-EE978448E51C} = {5B194365-E498-4DE5-BD41-485B20D488C8} 65 | {DACC224F-3880-4E66-BA51-2060E2DEB99D} = {5B194365-E498-4DE5-BD41-485B20D488C8} 66 | {8CDDA110-7134-4ADF-A103-BB53A02BFC33} = {0753C455-1E69-49BF-B290-89B68381A996} 67 | {0A857674-B93B-4524-9799-3529E30C0B59} = {0753C455-1E69-49BF-B290-89B68381A996} 68 | {40428569-3C78-4B2F-9FD8-B12E1E9B1C38} = {5B194365-E498-4DE5-BD41-485B20D488C8} 69 | {4BE132DA-2561-415D-A1B9-7B3E72794DAB} = {5B194365-E498-4DE5-BD41-485B20D488C8} 70 | EndGlobalSection 71 | GlobalSection(ExtensibilityGlobals) = postSolution 72 | SolutionGuid = {E684C85C-08EA-4CF9-9C52-8AEC8D930EF3} 73 | EndGlobalSection 74 | EndGlobal 75 | -------------------------------------------------------------------------------- /src/Way2Commerce.Api/Controllers/v1/ProdutoController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Way2Commerce.Api.Attributes; 4 | using Way2Commerce.Api.Controllers.Shared; 5 | using Way2Commerce.Application.DTOs.Request; 6 | using Way2Commerce.Application.DTOs.Response; 7 | using Way2Commerce.Domain.Interfaces.Services; 8 | using Way2Commerce.Identity; 9 | 10 | namespace Way2Commerce.Api.Controllers.v1; 11 | 12 | [Authorize(Roles = Roles.Admin)] 13 | [ApiVersion("1.0")] 14 | public class ProdutoController : ApiControllerBase 15 | { 16 | private IProdutoService _produtoService; 17 | 18 | public ProdutoController(IProdutoService produtoService) => 19 | _produtoService = produtoService; 20 | 21 | /// 22 | /// Obtém todos os produtos. 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// Retorna todos os produtos cadastrados 28 | /// Retorna erros caso ocorram 29 | [ProducesResponseType(typeof(ApiCollectionResponse), StatusCodes.Status200OK)] 30 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 31 | [ClaimsAuthorize(ClaimTypes.Produto, "Ler")] 32 | [Route("produtos")] 33 | [HttpGet] 34 | public async Task>> ObterTodos() 35 | { 36 | var produtos = await _produtoService.ObterTodosAsync(); 37 | var produtosResponse = produtos.Select(produto => ProdutoResponse.ConverterParaResponse(produto)); 38 | return Ok(produtosResponse.ToApiCollectionResponse()); 39 | } 40 | 41 | /// 42 | /// Obtém produto por Id. 43 | /// 44 | /// 45 | /// 46 | /// Id do produto 47 | /// 48 | /// Retorna os dados do produto 49 | /// Retorno caso o produto não seja encontrado 50 | /// Retorna erros caso ocorram 51 | [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] 52 | [ProducesResponseType(StatusCodes.Status404NotFound)] 53 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 54 | [ClaimsAuthorize(ClaimTypes.Produto, "Ler")] 55 | [HttpGet("produtos/{id}")] 56 | public async Task> ObterPorId(int id) 57 | { 58 | var produto = await _produtoService.ObterPorIdAsync(id); 59 | if (produto is null) 60 | return NotFound(); 61 | 62 | var produtoResponse = ProdutoResponse.ConverterParaResponse(produto); 63 | return Ok(produtoResponse); 64 | } 65 | 66 | /// 67 | /// Insere um produto. 68 | /// 69 | /// 70 | /// 71 | /// Dados do produto 72 | /// 73 | /// Retorna o Id do produto criado 74 | /// Retorna erros de validação 75 | /// Retorna erros caso ocorram 76 | [ProducesResponseType(typeof(int), StatusCodes.Status201Created)] 77 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 78 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 79 | [ClaimsAuthorizeAttribute(ClaimTypes.Produto, "Inserir")] 80 | [HttpPost("produtos")] 81 | public async Task> Inserir(InsercaoProdutoRequest produtoRequest) 82 | { 83 | var produto = InsercaoProdutoRequest.ConverterParaEntidade(produtoRequest); 84 | var id = (int)await _produtoService.AdicionarAsync(produto); 85 | return CreatedAtAction(nameof(ObterPorId), new { id = id }, id); 86 | } 87 | 88 | /// 89 | /// Atualiza um produto. 90 | /// 91 | /// 92 | /// 93 | /// Dados do produto 94 | /// 95 | /// Sucesso ao atualizar produto 96 | /// Retorna erros de validação 97 | /// Retorna erros caso ocorram 98 | [ProducesResponseType(StatusCodes.Status200OK)] 99 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 100 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 101 | [ClaimsAuthorizeAttribute(ClaimTypes.Produto, "Atualizar")] 102 | [HttpPut("produtos")] 103 | public async Task Atualizar(AtualizacaoProdutoRequest produtoRequest) 104 | { 105 | var produto = AtualizacaoProdutoRequest.ConverterParaEntidade(produtoRequest); 106 | await _produtoService.AtualizarAsync(produto); 107 | return Ok(); 108 | } 109 | 110 | /// 111 | /// Exclui um produto. 112 | /// 113 | /// 114 | /// 115 | /// Id do produto 116 | /// 117 | /// Sucesso ao excluir produto 118 | /// Retorna erros de validação 119 | /// Retorna erros caso ocorram 120 | [ProducesResponseType(StatusCodes.Status200OK)] 121 | [ProducesResponseType(StatusCodes.Status400BadRequest)] 122 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)] 123 | [Authorize(Policy = Policies.HorarioComercial)] 124 | [ClaimsAuthorizeAttribute(ClaimTypes.Produto, "Excluir")] 125 | [HttpDelete("produtos/{id}")] 126 | public async Task Excluir(int id) 127 | { 128 | await _produtoService.RemoverPorIdAsync(id); 129 | return Ok(); 130 | } 131 | } -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Services/IdentityService.cs: -------------------------------------------------------------------------------- 1 | using System.IdentityModel.Tokens.Jwt; 2 | using System.Security.Claims; 3 | using Microsoft.AspNetCore.Identity; 4 | using Microsoft.Extensions.Options; 5 | using Way2Commerce.Application.DTOs.Request; 6 | using Way2Commerce.Application.DTOs.Response; 7 | using Way2Commerce.Application.Interfaces.Services; 8 | using Way2Commerce.Identity.Configurations; 9 | 10 | namespace Way2Commerce.Identity.Services 11 | { 12 | public class IdentityService : IIdentityService 13 | { 14 | private readonly SignInManager _signInManager; 15 | private readonly UserManager _userManager; 16 | private readonly JwtOptions _jwtOptions; 17 | 18 | public IdentityService(SignInManager signInManager, 19 | UserManager userManager, 20 | IOptions jwtOptions) 21 | { 22 | _signInManager = signInManager; 23 | _userManager = userManager; 24 | _jwtOptions = jwtOptions.Value; 25 | } 26 | 27 | public async Task CadastrarUsuario(UsuarioCadastroRequest usuarioCadastro) 28 | { 29 | var identityUser = new IdentityUser 30 | { 31 | UserName = usuarioCadastro.Email, 32 | Email = usuarioCadastro.Email, 33 | EmailConfirmed = true 34 | }; 35 | 36 | var result = await _userManager.CreateAsync(identityUser, usuarioCadastro.Senha); 37 | if (result.Succeeded) 38 | await _userManager.SetLockoutEnabledAsync(identityUser, false); 39 | 40 | var usuarioCadastroResponse = new UsuarioCadastroResponse(result.Succeeded); 41 | if (!result.Succeeded && result.Errors.Count() > 0) 42 | usuarioCadastroResponse.AdicionarErros(result.Errors.Select(r => r.Description)); 43 | 44 | return usuarioCadastroResponse; 45 | } 46 | 47 | public async Task Login(UsuarioLoginRequest usuarioLogin) 48 | { 49 | var result = await _signInManager.PasswordSignInAsync(usuarioLogin.Email, usuarioLogin.Senha, false, true); 50 | if (result.Succeeded) 51 | return await GerarCredenciais(usuarioLogin.Email); 52 | 53 | var usuarioLoginResponse = new UsuarioLoginResponse(); 54 | if (!result.Succeeded) 55 | { 56 | if (result.IsLockedOut) 57 | usuarioLoginResponse.AdicionarErro("Essa conta está bloqueada"); 58 | else if (result.IsNotAllowed) 59 | usuarioLoginResponse.AdicionarErro("Essa conta não tem permissão para fazer login"); 60 | else if (result.RequiresTwoFactor) 61 | usuarioLoginResponse.AdicionarErro("É necessário confirmar o login no seu segundo fator de autenticação"); 62 | else 63 | usuarioLoginResponse.AdicionarErro("Usuário ou senha estão incorretos"); 64 | } 65 | 66 | return usuarioLoginResponse; 67 | } 68 | 69 | public async Task LoginSemSenha(string usuarioId) 70 | { 71 | var usuarioLoginResponse = new UsuarioLoginResponse(); 72 | var usuario = await _userManager.FindByIdAsync(usuarioId); 73 | 74 | if (await _userManager.IsLockedOutAsync(usuario)) 75 | usuarioLoginResponse.AdicionarErro("Essa conta está bloqueada"); 76 | else if (!await _userManager.IsEmailConfirmedAsync(usuario)) 77 | usuarioLoginResponse.AdicionarErro("Essa conta precisa confirmar seu e-mail antes de realizar o login"); 78 | 79 | if (usuarioLoginResponse.Sucesso) 80 | return await GerarCredenciais(usuario.Email); 81 | 82 | return usuarioLoginResponse; 83 | } 84 | 85 | private async Task GerarCredenciais(string email) 86 | { 87 | var user = await _userManager.FindByEmailAsync(email); 88 | var accessTokenClaims = await ObterClaims(user, adicionarClaimsUsuario: true); 89 | var refreshTokenClaims = await ObterClaims(user, adicionarClaimsUsuario: false); 90 | 91 | var dataExpiracaoAccessToken = DateTime.Now.AddSeconds(_jwtOptions.AccessTokenExpiration); 92 | var dataExpiracaoRefreshToken = DateTime.Now.AddSeconds(_jwtOptions.RefreshTokenExpiration); 93 | 94 | var accessToken = GerarToken(accessTokenClaims, dataExpiracaoAccessToken); 95 | var refreshToken = GerarToken(refreshTokenClaims, dataExpiracaoRefreshToken); 96 | 97 | return new UsuarioLoginResponse 98 | ( 99 | sucesso: true, 100 | accessToken: accessToken, 101 | refreshToken: refreshToken 102 | ); 103 | } 104 | 105 | private string GerarToken(IEnumerable claims, DateTime dataExpiracao) 106 | { 107 | var jwt = new JwtSecurityToken( 108 | issuer: _jwtOptions.Issuer, 109 | audience: _jwtOptions.Audience, 110 | claims: claims, 111 | notBefore: DateTime.Now, 112 | expires: dataExpiracao, 113 | signingCredentials: _jwtOptions.SigningCredentials); 114 | 115 | return new JwtSecurityTokenHandler().WriteToken(jwt); 116 | } 117 | 118 | private async Task> ObterClaims(IdentityUser user, bool adicionarClaimsUsuario) 119 | { 120 | var claims = new List(); 121 | 122 | claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id)); 123 | claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email)); 124 | claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); 125 | claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, DateTime.Now.ToString())); 126 | claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString())); 127 | 128 | if (adicionarClaimsUsuario) 129 | { 130 | var userClaims = await _userManager.GetClaimsAsync(user); 131 | var roles = await _userManager.GetRolesAsync(user); 132 | 133 | claims.AddRange(userClaims); 134 | 135 | foreach (var role in roles) 136 | claims.Add(new Claim("role", role)); 137 | } 138 | 139 | return claims; 140 | } 141 | } 142 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | .vscode/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # StyleCop 66 | StyleCopReport.xml 67 | 68 | # Files built by Visual Studio 69 | *_i.c 70 | *_p.c 71 | *_h.h 72 | *.ilk 73 | *.meta 74 | *.obj 75 | *.iobj 76 | *.pch 77 | *.pdb 78 | *.ipdb 79 | *.pgc 80 | *.pgd 81 | *.rsp 82 | *.sbr 83 | *.tlb 84 | *.tli 85 | *.tlh 86 | *.tmp 87 | *.tmp_proj 88 | *_wpftmp.csproj 89 | *.log 90 | *.vspscc 91 | *.vssscc 92 | .builds 93 | *.pidb 94 | *.svclog 95 | *.scc 96 | 97 | # Chutzpah Test files 98 | _Chutzpah* 99 | 100 | # Visual C++ cache files 101 | ipch/ 102 | *.aps 103 | *.ncb 104 | *.opendb 105 | *.opensdf 106 | *.sdf 107 | *.cachefile 108 | *.VC.db 109 | *.VC.VC.opendb 110 | 111 | # Visual Studio profiler 112 | *.psess 113 | *.vsp 114 | *.vspx 115 | *.sap 116 | 117 | # Visual Studio Trace Files 118 | *.e2e 119 | 120 | # TFS 2012 Local Workspace 121 | $tf/ 122 | 123 | # Guidance Automation Toolkit 124 | *.gpState 125 | 126 | # ReSharper is a .NET coding add-in 127 | _ReSharper*/ 128 | *.[Rr]e[Ss]harper 129 | *.DotSettings.user 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # NuGet Symbol Packages 189 | *.snupkg 190 | # The packages folder can be ignored because of Package Restore 191 | **/[Pp]ackages/* 192 | # except build/, which is used as an MSBuild target. 193 | !**/[Pp]ackages/build/ 194 | # Uncomment if necessary however generally it will be regenerated when needed 195 | #!**/[Pp]ackages/repositories.config 196 | # NuGet v3's project.json files produces more ignorable files 197 | *.nuget.props 198 | *.nuget.targets 199 | 200 | # Microsoft Azure Build Output 201 | csx/ 202 | *.build.csdef 203 | 204 | # Microsoft Azure Emulator 205 | ecf/ 206 | rcf/ 207 | 208 | # Windows Store app package directories and files 209 | AppPackages/ 210 | BundleArtifacts/ 211 | Package.StoreAssociation.xml 212 | _pkginfo.txt 213 | *.appx 214 | *.appxbundle 215 | *.appxupload 216 | 217 | # Visual Studio cache files 218 | # files ending in .cache can be ignored 219 | *.[Cc]ache 220 | # but keep track of directories ending in .cache 221 | !?*.[Cc]ache/ 222 | 223 | # Others 224 | ClientBin/ 225 | ~$* 226 | *~ 227 | *.dbmdl 228 | *.dbproj.schemaview 229 | *.jfm 230 | *.pfx 231 | *.publishsettings 232 | orleans.codegen.cs 233 | 234 | # Including strong name files can present a security risk 235 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 236 | #*.snk 237 | 238 | # Since there are multiple workflows, uncomment next line to ignore bower_components 239 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 240 | #bower_components/ 241 | 242 | # RIA/Silverlight projects 243 | Generated_Code/ 244 | 245 | # Backup & report files from converting an old project file 246 | # to a newer Visual Studio version. Backup files are not needed, 247 | # because we have git ;-) 248 | _UpgradeReport_Files/ 249 | Backup*/ 250 | UpgradeLog*.XML 251 | UpgradeLog*.htm 252 | ServiceFabricBackup/ 253 | *.rptproj.bak 254 | 255 | # SQL Server files 256 | *.mdf 257 | *.ldf 258 | *.ndf 259 | 260 | # Business Intelligence projects 261 | *.rdl.data 262 | *.bim.layout 263 | *.bim_*.settings 264 | *.rptproj.rsuser 265 | *- [Bb]ackup.rdl 266 | *- [Bb]ackup ([0-9]).rdl 267 | *- [Bb]ackup ([0-9][0-9]).rdl 268 | 269 | # Microsoft Fakes 270 | FakesAssemblies/ 271 | 272 | # GhostDoc plugin setting file 273 | *.GhostDoc.xml 274 | 275 | # Node.js Tools for Visual Studio 276 | .ntvs_analysis.dat 277 | node_modules/ 278 | 279 | # Visual Studio 6 build log 280 | *.plg 281 | 282 | # Visual Studio 6 workspace options file 283 | *.opt 284 | 285 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 286 | *.vbw 287 | 288 | # Visual Studio LightSwitch build output 289 | **/*.HTMLClient/GeneratedArtifacts 290 | **/*.DesktopClient/GeneratedArtifacts 291 | **/*.DesktopClient/ModelManifest.xml 292 | **/*.Server/GeneratedArtifacts 293 | **/*.Server/ModelManifest.xml 294 | _Pvt_Extensions 295 | 296 | # Paket dependency manager 297 | .paket/paket.exe 298 | paket-files/ 299 | 300 | # FAKE - F# Make 301 | .fake/ 302 | 303 | # CodeRush personal settings 304 | .cr/personal 305 | 306 | # Python Tools for Visual Studio (PTVS) 307 | __pycache__/ 308 | *.pyc 309 | 310 | # Cake - Uncomment if you are using it 311 | # tools/** 312 | # !tools/packages.config 313 | 314 | # Tabs Studio 315 | *.tss 316 | 317 | # Telerik's JustMock configuration file 318 | *.jmconfig 319 | 320 | # BizTalk build output 321 | *.btp.cs 322 | *.btm.cs 323 | *.odx.cs 324 | *.xsd.cs 325 | 326 | # OpenCover UI analysis results 327 | OpenCover/ 328 | 329 | # Azure Stream Analytics local run output 330 | ASALocalRun/ 331 | 332 | # MSBuild Binary and Structured Log 333 | *.binlog 334 | 335 | # NVidia Nsight GPU debugger configuration file 336 | *.nvuser 337 | 338 | # MFractors (Xamarin productivity tool) working folder 339 | .mfractor/ 340 | 341 | # Local History for Visual Studio 342 | .localhistory/ 343 | 344 | # BeatPulse healthcheck temp database 345 | healthchecksdb 346 | 347 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 348 | MigrationBackup/ 349 | 350 | # Ionide (cross platform F# VS Code tools) working folder 351 | .ionide/ 352 | -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Migrations/20220220191221_Initial.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace Way2Commerce.Identity.Migrations 7 | { 8 | public partial class Initial : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "AspNetRoles", 14 | columns: table => new 15 | { 16 | Id = table.Column(type: "nvarchar(450)", nullable: false), 17 | Name = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 18 | NormalizedName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 19 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true) 20 | }, 21 | constraints: table => 22 | { 23 | table.PrimaryKey("PK_AspNetRoles", x => x.Id); 24 | }); 25 | 26 | migrationBuilder.CreateTable( 27 | name: "AspNetUsers", 28 | columns: table => new 29 | { 30 | Id = table.Column(type: "nvarchar(450)", nullable: false), 31 | UserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 32 | NormalizedUserName = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 33 | Email = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 34 | NormalizedEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), 35 | EmailConfirmed = table.Column(type: "bit", nullable: false), 36 | PasswordHash = table.Column(type: "nvarchar(max)", nullable: true), 37 | SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true), 38 | ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true), 39 | PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true), 40 | PhoneNumberConfirmed = table.Column(type: "bit", nullable: false), 41 | TwoFactorEnabled = table.Column(type: "bit", nullable: false), 42 | LockoutEnd = table.Column(type: "datetimeoffset", nullable: true), 43 | LockoutEnabled = table.Column(type: "bit", nullable: false), 44 | AccessFailedCount = table.Column(type: "int", nullable: false) 45 | }, 46 | constraints: table => 47 | { 48 | table.PrimaryKey("PK_AspNetUsers", x => x.Id); 49 | }); 50 | 51 | migrationBuilder.CreateTable( 52 | name: "AspNetRoleClaims", 53 | columns: table => new 54 | { 55 | Id = table.Column(type: "int", nullable: false) 56 | .Annotation("SqlServer:Identity", "1, 1"), 57 | RoleId = table.Column(type: "nvarchar(450)", nullable: false), 58 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 59 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 60 | }, 61 | constraints: table => 62 | { 63 | table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); 64 | table.ForeignKey( 65 | name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", 66 | column: x => x.RoleId, 67 | principalTable: "AspNetRoles", 68 | principalColumn: "Id", 69 | onDelete: ReferentialAction.Cascade); 70 | }); 71 | 72 | migrationBuilder.CreateTable( 73 | name: "AspNetUserClaims", 74 | columns: table => new 75 | { 76 | Id = table.Column(type: "int", nullable: false) 77 | .Annotation("SqlServer:Identity", "1, 1"), 78 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 79 | ClaimType = table.Column(type: "nvarchar(max)", nullable: true), 80 | ClaimValue = table.Column(type: "nvarchar(max)", nullable: true) 81 | }, 82 | constraints: table => 83 | { 84 | table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); 85 | table.ForeignKey( 86 | name: "FK_AspNetUserClaims_AspNetUsers_UserId", 87 | column: x => x.UserId, 88 | principalTable: "AspNetUsers", 89 | principalColumn: "Id", 90 | onDelete: ReferentialAction.Cascade); 91 | }); 92 | 93 | migrationBuilder.CreateTable( 94 | name: "AspNetUserLogins", 95 | columns: table => new 96 | { 97 | LoginProvider = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), 98 | ProviderKey = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), 99 | ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true), 100 | UserId = table.Column(type: "nvarchar(450)", nullable: false) 101 | }, 102 | constraints: table => 103 | { 104 | table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); 105 | table.ForeignKey( 106 | name: "FK_AspNetUserLogins_AspNetUsers_UserId", 107 | column: x => x.UserId, 108 | principalTable: "AspNetUsers", 109 | principalColumn: "Id", 110 | onDelete: ReferentialAction.Cascade); 111 | }); 112 | 113 | migrationBuilder.CreateTable( 114 | name: "AspNetUserRoles", 115 | columns: table => new 116 | { 117 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 118 | RoleId = table.Column(type: "nvarchar(450)", nullable: false) 119 | }, 120 | constraints: table => 121 | { 122 | table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); 123 | table.ForeignKey( 124 | name: "FK_AspNetUserRoles_AspNetRoles_RoleId", 125 | column: x => x.RoleId, 126 | principalTable: "AspNetRoles", 127 | principalColumn: "Id", 128 | onDelete: ReferentialAction.Cascade); 129 | table.ForeignKey( 130 | name: "FK_AspNetUserRoles_AspNetUsers_UserId", 131 | column: x => x.UserId, 132 | principalTable: "AspNetUsers", 133 | principalColumn: "Id", 134 | onDelete: ReferentialAction.Cascade); 135 | }); 136 | 137 | migrationBuilder.CreateTable( 138 | name: "AspNetUserTokens", 139 | columns: table => new 140 | { 141 | UserId = table.Column(type: "nvarchar(450)", nullable: false), 142 | LoginProvider = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), 143 | Name = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), 144 | Value = table.Column(type: "nvarchar(max)", nullable: true) 145 | }, 146 | constraints: table => 147 | { 148 | table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); 149 | table.ForeignKey( 150 | name: "FK_AspNetUserTokens_AspNetUsers_UserId", 151 | column: x => x.UserId, 152 | principalTable: "AspNetUsers", 153 | principalColumn: "Id", 154 | onDelete: ReferentialAction.Cascade); 155 | }); 156 | 157 | migrationBuilder.CreateIndex( 158 | name: "IX_AspNetRoleClaims_RoleId", 159 | table: "AspNetRoleClaims", 160 | column: "RoleId"); 161 | 162 | migrationBuilder.CreateIndex( 163 | name: "RoleNameIndex", 164 | table: "AspNetRoles", 165 | column: "NormalizedName", 166 | unique: true, 167 | filter: "[NormalizedName] IS NOT NULL"); 168 | 169 | migrationBuilder.CreateIndex( 170 | name: "IX_AspNetUserClaims_UserId", 171 | table: "AspNetUserClaims", 172 | column: "UserId"); 173 | 174 | migrationBuilder.CreateIndex( 175 | name: "IX_AspNetUserLogins_UserId", 176 | table: "AspNetUserLogins", 177 | column: "UserId"); 178 | 179 | migrationBuilder.CreateIndex( 180 | name: "IX_AspNetUserRoles_RoleId", 181 | table: "AspNetUserRoles", 182 | column: "RoleId"); 183 | 184 | migrationBuilder.CreateIndex( 185 | name: "EmailIndex", 186 | table: "AspNetUsers", 187 | column: "NormalizedEmail"); 188 | 189 | migrationBuilder.CreateIndex( 190 | name: "UserNameIndex", 191 | table: "AspNetUsers", 192 | column: "NormalizedUserName", 193 | unique: true, 194 | filter: "[NormalizedUserName] IS NOT NULL"); 195 | } 196 | 197 | protected override void Down(MigrationBuilder migrationBuilder) 198 | { 199 | migrationBuilder.DropTable( 200 | name: "AspNetRoleClaims"); 201 | 202 | migrationBuilder.DropTable( 203 | name: "AspNetUserClaims"); 204 | 205 | migrationBuilder.DropTable( 206 | name: "AspNetUserLogins"); 207 | 208 | migrationBuilder.DropTable( 209 | name: "AspNetUserRoles"); 210 | 211 | migrationBuilder.DropTable( 212 | name: "AspNetUserTokens"); 213 | 214 | migrationBuilder.DropTable( 215 | name: "AspNetRoles"); 216 | 217 | migrationBuilder.DropTable( 218 | name: "AspNetUsers"); 219 | } 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Migrations/IdentityDataContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Way2Commerce.Identity.Data; 8 | 9 | #nullable disable 10 | 11 | namespace Way2Commerce.Identity.Migrations 12 | { 13 | [DbContext(typeof(IdentityDataContext))] 14 | partial class IdentityDataContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.2") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 26 | { 27 | b.Property("Id") 28 | .HasColumnType("nvarchar(450)"); 29 | 30 | b.Property("ConcurrencyStamp") 31 | .IsConcurrencyToken() 32 | .HasColumnType("nvarchar(max)"); 33 | 34 | b.Property("Name") 35 | .HasMaxLength(256) 36 | .HasColumnType("nvarchar(256)"); 37 | 38 | b.Property("NormalizedName") 39 | .HasMaxLength(256) 40 | .HasColumnType("nvarchar(256)"); 41 | 42 | b.HasKey("Id"); 43 | 44 | b.HasIndex("NormalizedName") 45 | .IsUnique() 46 | .HasDatabaseName("RoleNameIndex") 47 | .HasFilter("[NormalizedName] IS NOT NULL"); 48 | 49 | b.ToTable("AspNetRoles", (string)null); 50 | }); 51 | 52 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 53 | { 54 | b.Property("Id") 55 | .ValueGeneratedOnAdd() 56 | .HasColumnType("int"); 57 | 58 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 59 | 60 | b.Property("ClaimType") 61 | .HasColumnType("nvarchar(max)"); 62 | 63 | b.Property("ClaimValue") 64 | .HasColumnType("nvarchar(max)"); 65 | 66 | b.Property("RoleId") 67 | .IsRequired() 68 | .HasColumnType("nvarchar(450)"); 69 | 70 | b.HasKey("Id"); 71 | 72 | b.HasIndex("RoleId"); 73 | 74 | b.ToTable("AspNetRoleClaims", (string)null); 75 | }); 76 | 77 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 78 | { 79 | b.Property("Id") 80 | .HasColumnType("nvarchar(450)"); 81 | 82 | b.Property("AccessFailedCount") 83 | .HasColumnType("int"); 84 | 85 | b.Property("ConcurrencyStamp") 86 | .IsConcurrencyToken() 87 | .HasColumnType("nvarchar(max)"); 88 | 89 | b.Property("Email") 90 | .HasMaxLength(256) 91 | .HasColumnType("nvarchar(256)"); 92 | 93 | b.Property("EmailConfirmed") 94 | .HasColumnType("bit"); 95 | 96 | b.Property("LockoutEnabled") 97 | .HasColumnType("bit"); 98 | 99 | b.Property("LockoutEnd") 100 | .HasColumnType("datetimeoffset"); 101 | 102 | b.Property("NormalizedEmail") 103 | .HasMaxLength(256) 104 | .HasColumnType("nvarchar(256)"); 105 | 106 | b.Property("NormalizedUserName") 107 | .HasMaxLength(256) 108 | .HasColumnType("nvarchar(256)"); 109 | 110 | b.Property("PasswordHash") 111 | .HasColumnType("nvarchar(max)"); 112 | 113 | b.Property("PhoneNumber") 114 | .HasColumnType("nvarchar(max)"); 115 | 116 | b.Property("PhoneNumberConfirmed") 117 | .HasColumnType("bit"); 118 | 119 | b.Property("SecurityStamp") 120 | .HasColumnType("nvarchar(max)"); 121 | 122 | b.Property("TwoFactorEnabled") 123 | .HasColumnType("bit"); 124 | 125 | b.Property("UserName") 126 | .HasMaxLength(256) 127 | .HasColumnType("nvarchar(256)"); 128 | 129 | b.HasKey("Id"); 130 | 131 | b.HasIndex("NormalizedEmail") 132 | .HasDatabaseName("EmailIndex"); 133 | 134 | b.HasIndex("NormalizedUserName") 135 | .IsUnique() 136 | .HasDatabaseName("UserNameIndex") 137 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 138 | 139 | b.ToTable("AspNetUsers", (string)null); 140 | }); 141 | 142 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 143 | { 144 | b.Property("Id") 145 | .ValueGeneratedOnAdd() 146 | .HasColumnType("int"); 147 | 148 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 149 | 150 | b.Property("ClaimType") 151 | .HasColumnType("nvarchar(max)"); 152 | 153 | b.Property("ClaimValue") 154 | .HasColumnType("nvarchar(max)"); 155 | 156 | b.Property("UserId") 157 | .IsRequired() 158 | .HasColumnType("nvarchar(450)"); 159 | 160 | b.HasKey("Id"); 161 | 162 | b.HasIndex("UserId"); 163 | 164 | b.ToTable("AspNetUserClaims", (string)null); 165 | }); 166 | 167 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 168 | { 169 | b.Property("LoginProvider") 170 | .HasMaxLength(128) 171 | .HasColumnType("nvarchar(128)"); 172 | 173 | b.Property("ProviderKey") 174 | .HasMaxLength(128) 175 | .HasColumnType("nvarchar(128)"); 176 | 177 | b.Property("ProviderDisplayName") 178 | .HasColumnType("nvarchar(max)"); 179 | 180 | b.Property("UserId") 181 | .IsRequired() 182 | .HasColumnType("nvarchar(450)"); 183 | 184 | b.HasKey("LoginProvider", "ProviderKey"); 185 | 186 | b.HasIndex("UserId"); 187 | 188 | b.ToTable("AspNetUserLogins", (string)null); 189 | }); 190 | 191 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 192 | { 193 | b.Property("UserId") 194 | .HasColumnType("nvarchar(450)"); 195 | 196 | b.Property("RoleId") 197 | .HasColumnType("nvarchar(450)"); 198 | 199 | b.HasKey("UserId", "RoleId"); 200 | 201 | b.HasIndex("RoleId"); 202 | 203 | b.ToTable("AspNetUserRoles", (string)null); 204 | }); 205 | 206 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 207 | { 208 | b.Property("UserId") 209 | .HasColumnType("nvarchar(450)"); 210 | 211 | b.Property("LoginProvider") 212 | .HasMaxLength(128) 213 | .HasColumnType("nvarchar(128)"); 214 | 215 | b.Property("Name") 216 | .HasMaxLength(128) 217 | .HasColumnType("nvarchar(128)"); 218 | 219 | b.Property("Value") 220 | .HasColumnType("nvarchar(max)"); 221 | 222 | b.HasKey("UserId", "LoginProvider", "Name"); 223 | 224 | b.ToTable("AspNetUserTokens", (string)null); 225 | }); 226 | 227 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 228 | { 229 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 230 | .WithMany() 231 | .HasForeignKey("RoleId") 232 | .OnDelete(DeleteBehavior.Cascade) 233 | .IsRequired(); 234 | }); 235 | 236 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 237 | { 238 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 239 | .WithMany() 240 | .HasForeignKey("UserId") 241 | .OnDelete(DeleteBehavior.Cascade) 242 | .IsRequired(); 243 | }); 244 | 245 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 246 | { 247 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 248 | .WithMany() 249 | .HasForeignKey("UserId") 250 | .OnDelete(DeleteBehavior.Cascade) 251 | .IsRequired(); 252 | }); 253 | 254 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 255 | { 256 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 257 | .WithMany() 258 | .HasForeignKey("RoleId") 259 | .OnDelete(DeleteBehavior.Cascade) 260 | .IsRequired(); 261 | 262 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 263 | .WithMany() 264 | .HasForeignKey("UserId") 265 | .OnDelete(DeleteBehavior.Cascade) 266 | .IsRequired(); 267 | }); 268 | 269 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 270 | { 271 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 272 | .WithMany() 273 | .HasForeignKey("UserId") 274 | .OnDelete(DeleteBehavior.Cascade) 275 | .IsRequired(); 276 | }); 277 | #pragma warning restore 612, 618 278 | } 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /src/Way2Commerce.Identity/Migrations/20220220191221_Initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using Way2Commerce.Identity.Data; 9 | 10 | #nullable disable 11 | 12 | namespace Way2Commerce.Identity.Migrations 13 | { 14 | [DbContext(typeof(IdentityDataContext))] 15 | [Migration("20220220191221_Initial")] 16 | partial class Initial 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.2") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => 28 | { 29 | b.Property("Id") 30 | .HasColumnType("nvarchar(450)"); 31 | 32 | b.Property("ConcurrencyStamp") 33 | .IsConcurrencyToken() 34 | .HasColumnType("nvarchar(max)"); 35 | 36 | b.Property("Name") 37 | .HasMaxLength(256) 38 | .HasColumnType("nvarchar(256)"); 39 | 40 | b.Property("NormalizedName") 41 | .HasMaxLength(256) 42 | .HasColumnType("nvarchar(256)"); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.HasIndex("NormalizedName") 47 | .IsUnique() 48 | .HasDatabaseName("RoleNameIndex") 49 | .HasFilter("[NormalizedName] IS NOT NULL"); 50 | 51 | b.ToTable("AspNetRoles", (string)null); 52 | }); 53 | 54 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 55 | { 56 | b.Property("Id") 57 | .ValueGeneratedOnAdd() 58 | .HasColumnType("int"); 59 | 60 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 61 | 62 | b.Property("ClaimType") 63 | .HasColumnType("nvarchar(max)"); 64 | 65 | b.Property("ClaimValue") 66 | .HasColumnType("nvarchar(max)"); 67 | 68 | b.Property("RoleId") 69 | .IsRequired() 70 | .HasColumnType("nvarchar(450)"); 71 | 72 | b.HasKey("Id"); 73 | 74 | b.HasIndex("RoleId"); 75 | 76 | b.ToTable("AspNetRoleClaims", (string)null); 77 | }); 78 | 79 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => 80 | { 81 | b.Property("Id") 82 | .HasColumnType("nvarchar(450)"); 83 | 84 | b.Property("AccessFailedCount") 85 | .HasColumnType("int"); 86 | 87 | b.Property("ConcurrencyStamp") 88 | .IsConcurrencyToken() 89 | .HasColumnType("nvarchar(max)"); 90 | 91 | b.Property("Email") 92 | .HasMaxLength(256) 93 | .HasColumnType("nvarchar(256)"); 94 | 95 | b.Property("EmailConfirmed") 96 | .HasColumnType("bit"); 97 | 98 | b.Property("LockoutEnabled") 99 | .HasColumnType("bit"); 100 | 101 | b.Property("LockoutEnd") 102 | .HasColumnType("datetimeoffset"); 103 | 104 | b.Property("NormalizedEmail") 105 | .HasMaxLength(256) 106 | .HasColumnType("nvarchar(256)"); 107 | 108 | b.Property("NormalizedUserName") 109 | .HasMaxLength(256) 110 | .HasColumnType("nvarchar(256)"); 111 | 112 | b.Property("PasswordHash") 113 | .HasColumnType("nvarchar(max)"); 114 | 115 | b.Property("PhoneNumber") 116 | .HasColumnType("nvarchar(max)"); 117 | 118 | b.Property("PhoneNumberConfirmed") 119 | .HasColumnType("bit"); 120 | 121 | b.Property("SecurityStamp") 122 | .HasColumnType("nvarchar(max)"); 123 | 124 | b.Property("TwoFactorEnabled") 125 | .HasColumnType("bit"); 126 | 127 | b.Property("UserName") 128 | .HasMaxLength(256) 129 | .HasColumnType("nvarchar(256)"); 130 | 131 | b.HasKey("Id"); 132 | 133 | b.HasIndex("NormalizedEmail") 134 | .HasDatabaseName("EmailIndex"); 135 | 136 | b.HasIndex("NormalizedUserName") 137 | .IsUnique() 138 | .HasDatabaseName("UserNameIndex") 139 | .HasFilter("[NormalizedUserName] IS NOT NULL"); 140 | 141 | b.ToTable("AspNetUsers", (string)null); 142 | }); 143 | 144 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 145 | { 146 | b.Property("Id") 147 | .ValueGeneratedOnAdd() 148 | .HasColumnType("int"); 149 | 150 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); 151 | 152 | b.Property("ClaimType") 153 | .HasColumnType("nvarchar(max)"); 154 | 155 | b.Property("ClaimValue") 156 | .HasColumnType("nvarchar(max)"); 157 | 158 | b.Property("UserId") 159 | .IsRequired() 160 | .HasColumnType("nvarchar(450)"); 161 | 162 | b.HasKey("Id"); 163 | 164 | b.HasIndex("UserId"); 165 | 166 | b.ToTable("AspNetUserClaims", (string)null); 167 | }); 168 | 169 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 170 | { 171 | b.Property("LoginProvider") 172 | .HasMaxLength(128) 173 | .HasColumnType("nvarchar(128)"); 174 | 175 | b.Property("ProviderKey") 176 | .HasMaxLength(128) 177 | .HasColumnType("nvarchar(128)"); 178 | 179 | b.Property("ProviderDisplayName") 180 | .HasColumnType("nvarchar(max)"); 181 | 182 | b.Property("UserId") 183 | .IsRequired() 184 | .HasColumnType("nvarchar(450)"); 185 | 186 | b.HasKey("LoginProvider", "ProviderKey"); 187 | 188 | b.HasIndex("UserId"); 189 | 190 | b.ToTable("AspNetUserLogins", (string)null); 191 | }); 192 | 193 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 194 | { 195 | b.Property("UserId") 196 | .HasColumnType("nvarchar(450)"); 197 | 198 | b.Property("RoleId") 199 | .HasColumnType("nvarchar(450)"); 200 | 201 | b.HasKey("UserId", "RoleId"); 202 | 203 | b.HasIndex("RoleId"); 204 | 205 | b.ToTable("AspNetUserRoles", (string)null); 206 | }); 207 | 208 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 209 | { 210 | b.Property("UserId") 211 | .HasColumnType("nvarchar(450)"); 212 | 213 | b.Property("LoginProvider") 214 | .HasMaxLength(128) 215 | .HasColumnType("nvarchar(128)"); 216 | 217 | b.Property("Name") 218 | .HasMaxLength(128) 219 | .HasColumnType("nvarchar(128)"); 220 | 221 | b.Property("Value") 222 | .HasColumnType("nvarchar(max)"); 223 | 224 | b.HasKey("UserId", "LoginProvider", "Name"); 225 | 226 | b.ToTable("AspNetUserTokens", (string)null); 227 | }); 228 | 229 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => 230 | { 231 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 232 | .WithMany() 233 | .HasForeignKey("RoleId") 234 | .OnDelete(DeleteBehavior.Cascade) 235 | .IsRequired(); 236 | }); 237 | 238 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => 239 | { 240 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 241 | .WithMany() 242 | .HasForeignKey("UserId") 243 | .OnDelete(DeleteBehavior.Cascade) 244 | .IsRequired(); 245 | }); 246 | 247 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => 248 | { 249 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 250 | .WithMany() 251 | .HasForeignKey("UserId") 252 | .OnDelete(DeleteBehavior.Cascade) 253 | .IsRequired(); 254 | }); 255 | 256 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => 257 | { 258 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) 259 | .WithMany() 260 | .HasForeignKey("RoleId") 261 | .OnDelete(DeleteBehavior.Cascade) 262 | .IsRequired(); 263 | 264 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 265 | .WithMany() 266 | .HasForeignKey("UserId") 267 | .OnDelete(DeleteBehavior.Cascade) 268 | .IsRequired(); 269 | }); 270 | 271 | modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => 272 | { 273 | b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) 274 | .WithMany() 275 | .HasForeignKey("UserId") 276 | .OnDelete(DeleteBehavior.Cascade) 277 | .IsRequired(); 278 | }); 279 | #pragma warning restore 612, 618 280 | } 281 | } 282 | } 283 | --------------------------------------------------------------------------------