Skip to content

Commit

Permalink
feat : Codecleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
RondineleG committed Sep 17, 2023
1 parent 513a533 commit 00b8b0d
Show file tree
Hide file tree
Showing 19 changed files with 477 additions and 522 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
using Browl.Service.AuthSecurity.API.Data;
using Browl.Service.AuthSecurity.Domain.Entities;

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace Browl.Service.AuthSecurity.API.Configuration;
namespace Browl.Service.AuthSecurity.API.Configuration;

public static class ApiConfig
{
public static IServiceCollection AddApiConfiguration(this IServiceCollection services, IWebHostEnvironment hostEnvironment, IConfiguration configuration)
{
services.AddControllers();
services.AddEndpointsApiExplorer();
_ = services.AddControllers();
_ = services.AddEndpointsApiExplorer();

IConfigurationBuilder builder = new ConfigurationBuilder()
var builder = new ConfigurationBuilder()
.SetBasePath(hostEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();

if (hostEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Program>();
_ = builder.AddUserSecrets<Program>();
}

return services;
Expand All @@ -39,16 +33,16 @@ public static IApplicationBuilder UseApiConfiguration(this IApplicationBuilder a
// });
//}

app.UseHttpsRedirection();
var unused5 = app.UseHttpsRedirection();

app.UseRouting();
var unused4 = app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
var unused3 = app.UseAuthentication();
var unused2 = app.UseAuthorization();

app.UseEndpoints(endpoints =>
var unused1 = app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
var unused = endpoints.MapControllers();
});

return app;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
using Browl.Service.AuthSecurity.API.Data;
using System.Text;

using Browl.Service.AuthSecurity.API.Data;
using Browl.Service.AuthSecurity.API.Entities;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

using System.Text;

namespace Browl.Service.AuthSecurity.API.Configuration;

public static class IdentityConfig
{
public static IServiceCollection AddIdentityConfiguration(this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<BrowlAuthSecurityDbContext>(options =>
var unused3 = services.AddDbContext<BrowlAuthSecurityDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<BrowlAuthSecurityDbContext>()
.AddDefaultTokenProviders();

var unused2 = services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<BrowlAuthSecurityDbContext>()
.AddDefaultTokenProviders();

// JWT

var appSettingsSection = configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var unused1 = services.Configure<AppSettings>(appSettingsSection);

var appSettings = appSettingsSection.Get<AppSettings>();
byte[] key = Encoding.ASCII.GetBytes(appSettings.Secret);
var key = Encoding.ASCII.GetBytes(appSettings.Secret);

Microsoft.AspNetCore.Authentication.AuthenticationBuilder unused = services.AddAuthentication(options =>
var unused = services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
Expand All @@ -55,8 +55,8 @@ public static IServiceCollection AddIdentityConfiguration(this IServiceCollectio

public static IApplicationBuilder UseIdentityConfiguration(this IApplicationBuilder app)
{
app.UseAuthentication();
app.UseAuthorization();
_ = app.UseAuthentication();
_ = app.UseAuthorization();

return app;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@ namespace Browl.Service.AuthSecurity.API.Configuration;

public static class SwaggerConfig
{
public static IServiceCollection AddSwaggerConfiguration(this IServiceCollection services)
{
IServiceCollection unused = services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo()
{
Title = "Browl Service AuthSecurity API",
Description = "This API guarantees the security and proper authentication of users in the application.",
Contact = new OpenApiContact() { Name = "Rondinele Guimarães", Email = "[email protected]" },
License = new OpenApiLicense() { Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT") }
});
public static IServiceCollection AddSwaggerConfiguration(this IServiceCollection services)
{
var unused = services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo()
{
Title = "Browl Service AuthSecurity API",
Description = "This API guarantees the security and proper authentication of users in the application.",
Contact = new OpenApiContact() { Name = "Rondinele Guimarães", Email = "[email protected]" },
License = new OpenApiLicense() { Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT") }
});
});
});

return services;
}
return services;
}

public static IApplicationBuilder UseSwaggerConfiguration(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
var unused1 = app.UseSwagger();
var unused = app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
using Browl.Service.AuthSecurity.API.Controllers.Base;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

using Browl.Service.AuthSecurity.API.Controllers.Base;
using Browl.Service.AuthSecurity.API.Entities;
using Browl.Service.AuthSecurity.Domain.Entities;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Browl.Service.AuthSecurity.API.Controllers;

/// <summary>
Expand Down Expand Up @@ -81,7 +80,7 @@ public async Task<ActionResult> Register(UserRegister userRegister)
return CustomResponse(await GenerateJWT(userRegister.Email));
}

foreach (IdentityError error in result.Errors)
foreach (var error in result.Errors)
{
AddErrorProcessing(error.Description);
}
Expand Down Expand Up @@ -109,7 +108,7 @@ public async Task<ActionResult> Login(UserLogin usuarioLogin)
return CustomResponse(ModelState);
}

Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(usuarioLogin.Email, usuarioLogin.Password,
var result = await _signInManager.PasswordSignInAsync(usuarioLogin.Email, usuarioLogin.Password,
false, true);

if (result.Succeeded)
Expand Down Expand Up @@ -150,13 +149,13 @@ private async Task<UserResponse> GenerateJWT(string email)
/// <returns>The claims identity for the user.</returns>
private async Task<ClaimsIdentity> GetClaimsUser(ICollection<Claim> claims, IdentityUser user)
{
IList<string> userRoles = await _userManager.GetRolesAsync(user);
var userRoles = await _userManager.GetRolesAsync(user);
claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString()));
claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64));
foreach (string userRole in userRoles)
foreach (var userRole in userRoles)
{
claims.Add(new Claim("role", userRole));
}
Expand Down Expand Up @@ -185,8 +184,8 @@ private async Task<ClaimsIdentity> GetClaimsUser(ICollection<Claim> claims, Iden
private string EncodeToken(ClaimsIdentity identityClaims)
{
JwtSecurityTokenHandler tokenHandler = new();
byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);
SecurityToken token = tokenHandler.CreateToken(new SecurityTokenDescriptor
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
Issuer = _appSettings.Issuer,
Audience = _appSettings.ValidOn,
Expand Down Expand Up @@ -255,8 +254,5 @@ private UserResponse GetResponseToken(string encodedToken, IdentityUser user, IE
///
/// The returned long can be used as a Unix timestamp.
/// </remarks>
private static long ToUnixEpochDate(DateTime date)
{
return DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
private static long ToUnixEpochDate(DateTime date) => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
Original file line number Diff line number Diff line change
@@ -1,72 +1,65 @@
using Microsoft.AspNetCore.Mvc;

namespace Browl.Service.AuthSecurity.API.Controllers.Base
namespace Browl.Service.AuthSecurity.API.Controllers.Base;

/// <summary>
/// Abstract base controller class that provides common functionality for API controllers.
/// </summary>
/// <remarks>
/// This abstract class defines:
/// - Errors: An IList property to hold a list of error strings.
/// - CustomResponse(): A protected method that returns an ActionResult with custom error handling.
/// - AddErrorProcessing(): A protected method to add an error string to the Errors collection.
/// - ClearErrorsProcessing(): A protected method to clear the Errors collection.
///
/// Controllers that inherit from this base class can utilize these common members and methods for consistent error handling and responses.
/// </remarks>
[ApiController]
public abstract class MainController : Controller
{
// Collection to store error messages
protected IList<string> Errors = new List<string>();

/// <summary>
/// Abstract base controller class that provides common functionality for API controllers.
/// Custom response method to handle API responses
/// </summary>
/// <remarks>
/// This abstract class defines:
/// - Errors: An IList property to hold a list of error strings.
/// - CustomResponse(): A protected method that returns an ActionResult with custom error handling.
/// - AddErrorProcessing(): A protected method to add an error string to the Errors collection.
/// - ClearErrorsProcessing(): A protected method to clear the Errors collection.
///
/// Controllers that inherit from this base class can utilize these common members and methods for consistent error handling and responses.
/// </remarks>
[ApiController]
public abstract class MainController : Controller
/// <param name="result">Optional result object</param>
/// <returns>Action result</returns>
protected ActionResult CustomResponse(object? result = null)
{
// Collection to store error messages
protected IList<string> Errors = new List<string>();

/// <summary>
/// Custom response method to handle API responses
/// </summary>
/// <param name="result">Optional result object</param>
/// <returns>Action result</returns>
protected ActionResult CustomResponse(object? result = null)
// Check if the model state is valid and there are no errors
if (ModelState.IsValid && Errors.Count == 0)
{
// Check if the model state is valid and there are no errors
if (ModelState.IsValid && Errors.Count == 0)
{
return Ok(result);
}

var errorDictionary = new Dictionary<string, string[]>();

// Add model state errors to the dictionary
if (ModelState.ErrorCount > 0)
{
var modelErrors = ModelState.Values.SelectMany(v => v.Errors);
errorDictionary.Add("Messages", modelErrors.Select(e => e.ErrorMessage).ToArray());
}

// Add custom errors to the dictionary
if (Errors.Count > 0)
{
errorDictionary.Add("Messages", Errors.ToArray());
}

// Return a bad request response with the validation problem details
return BadRequest(new ValidationProblemDetails(errorDictionary));
return Ok(result);
}

/// <summary>
/// Add an error message to the collection
/// </summary>
/// <param name="error">Error message</param>
protected void AddErrorProcessing(string error)
var errorDictionary = new Dictionary<string, string[]>();

// Add model state errors to the dictionary
if (ModelState.ErrorCount > 0)
{
Errors.Add(error);
var modelErrors = ModelState.Values.SelectMany(v => v.Errors);
errorDictionary.Add("Messages", modelErrors.Select(e => e.ErrorMessage).ToArray());
}

/// <summary>
/// Clear all error messages from the collection
/// </summary>
protected void ClearErrorsProcessing()
// Add custom errors to the dictionary
if (Errors.Count > 0)
{
Errors.Clear();
errorDictionary.Add("Messages", Errors.ToArray());
}

// Return a bad request response with the validation problem details
return BadRequest(new ValidationProblemDetails(errorDictionary));
}

/// <summary>
/// Add an error message to the collection
/// </summary>
/// <param name="error">Error message</param>
protected void AddErrorProcessing(string error) => Errors.Add(error);

/// <summary>
/// Clear all error messages from the collection
/// </summary>
protected void ClearErrorsProcessing() => Errors.Clear();
}
Loading

0 comments on commit 00b8b0d

Please sign in to comment.