Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor/add enviroment variables file #31

Merged
merged 2 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,13 @@ fabric.properties
.history
.ionide

### ignore environment ###
.env
.env.local
.env.development
.env.test
.env.production

### VisualStudio ###

# User-specific files
Expand Down
13 changes: 13 additions & 0 deletions src/Web/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Database Connection String
DB_CONNECTION_STRING=Server=127.0.0.1;Port=5432;Database=your_database_name;User Id=your_db_user;Password=your_db_password;

# JWT Settings
JWT_ISSUER=http://your_issuer
JWT_AUDIENCE=http://your_audience
JWT_KEY=your_jwt_key

# Root User Settings
ROOTUSER_ROLE=Admin
ROOTUSER_USERNAME=your_username
ROOTUSER_EMAIL=your_email
ROOTUSER_PASSWORD=your_password
10 changes: 6 additions & 4 deletions src/Web/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Web.Startup;
using DotNetEnv;

var builder = WebApplication.CreateBuilder(args);
Env.Load();
var config = builder.Configuration;


Expand All @@ -9,11 +11,11 @@
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
builder.Services.AddInfrastructureServices(config);
builder.Services.ConfigureAppAuthenticationServices(config);
builder.Services.AddInfrastructureServices();
builder.Services.ConfigureAppAuthenticationServices();
builder.Services.AddApplicationServices();
builder.Services.AddSwaggerDocumentation();
builder.Services.AddCorsPolicy();
builder.Services.AddCorsPolicy(config);


var app = builder.Build();
Expand All @@ -23,6 +25,6 @@
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
await SeedData.Initialize(services, config);
await SeedData.Initialize(services);
}
app.Run();
11 changes: 5 additions & 6 deletions src/Web/Services/TokenService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ namespace Web.Services;

public class TokenService : ITokenService
{
private readonly IConfiguration _configuration;
private readonly SymmetricSecurityKey _symmetricSecurityKey;

public TokenService(IConfiguration configuration)
public TokenService()
{
_configuration = configuration;
var key = Environment.GetEnvironmentVariable("JWT_KEY")!;
_symmetricSecurityKey = new SymmetricSecurityKey(
System.Text.Encoding.UTF8.GetBytes(_configuration["JwtSettings:Key"])
System.Text.Encoding.UTF8.GetBytes(key)
);
}

Expand All @@ -37,8 +36,8 @@ public string GenerateToken(AppUser user, string role)
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddHours(8),
SigningCredentials = credentials,
Issuer = _configuration["JwtSettings:Issuer"],
Audience = _configuration["JwtSettings:Audience"]
Issuer = Environment.GetEnvironmentVariable("JWT_ISSUER"),
Audience = Environment.GetEnvironmentVariable("JWT_AUDIENCE")
};

var tokenHandler = new JwtSecurityTokenHandler();
Expand Down
16 changes: 7 additions & 9 deletions src/Web/Startup/SeedData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,20 @@ namespace Web.Startup;

public static class SeedData
{
public static async Task Initialize(IServiceProvider serviceProvider, IConfigurationManager config)
public static async Task Initialize(IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<AppUser>>();

var id = config["RootUser:Id"]!;
var roleName = config["RootUser:RoleName"]!;
var userName = config["RootUser:UserName"]!;
var email = config["RootUser:Email"];
var password = config["RootUser:Password"]!;

var rootUser = await userManager.FindByIdAsync(id);
var roleName = Environment.GetEnvironmentVariable("ROOTUSER_ROLE")!;
var userName = Environment.GetEnvironmentVariable("ROOTUSER_USERNAME")!;
var email = Environment.GetEnvironmentVariable("ROOTUSER_EMAIL")!;
var password = Environment.GetEnvironmentVariable("ROOTUSER_PASSWORD")!;

var rootUser = await userManager.FindByNameAsync(userName);
if (rootUser == null)
{
rootUser = new AppUser
{
Id = id,
UserName = userName,
Email = email,
EmailConfirmed = true
Expand Down
12 changes: 8 additions & 4 deletions src/Web/Startup/ServiceExtensions.Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ namespace Web.Startup
{
public static partial class ServiceExtensions
{
public static void ConfigureAppAuthenticationServices(this IServiceCollection services, IConfiguration config)
public static void ConfigureAppAuthenticationServices(this IServiceCollection services)
{
var issuer = Environment.GetEnvironmentVariable("JWT_ISSUER");
var audience = Environment.GetEnvironmentVariable("JWT_AUDIENCE");
var key = Environment.GetEnvironmentVariable("JWT_KEY")!;

services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
Expand All @@ -17,10 +21,10 @@ public static void ConfigureAppAuthenticationServices(this IServiceCollection se
{
x.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = config["JwtSettings:Issuer"],
ValidAudience = config["JwtSettings:Audience"],
ValidIssuer = issuer,
ValidAudience = audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(config["JwtSettings:Key"]!)),
Encoding.UTF8.GetBytes(key)),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
Expand Down
9 changes: 4 additions & 5 deletions src/Web/Startup/ServiceExtensions.Cors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ namespace Web.Startup
{
public static partial class ServiceExtensions
{
public static void AddCorsPolicy(this IServiceCollection services)
public static void AddCorsPolicy(this IServiceCollection services, IConfiguration config)
{
var origins = config.GetSection("CorsSettings:Origins").Get<string[]>()!;

services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins", corsPolicyBuilder =>
{
corsPolicyBuilder.WithOrigins(
"http://localhost:4200",
"http://external.abriment.com:30081"
)
corsPolicyBuilder.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
Expand Down
8 changes: 6 additions & 2 deletions src/Web/Startup/ServiceExtensions.Infra.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ namespace Web.Startup;

public static partial class ServiceExtensions
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration config)
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)
{
var connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING");

services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseNpgsql(config.GetConnectionString("DefaultConnection"));
options.UseNpgsql(connectionString);
});

services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

return services;
}
}
1 change: 1 addition & 0 deletions src/Web/Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.7" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7"/>
Expand Down
20 changes: 6 additions & 14 deletions src/Web/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1;Port=5432;Database=KakaSiah;User Id=postgres;Password=postgres;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JwtSettings": {
"Issuer": "http://localhost:5000",
"Audience": "http://localhost:5000",
"Key": "sjmcabnishcpasichquwh108hd29dh12wcf1hni1nci9vh9p920u1dhx08122hiokasnx89"
},
"RootUser": {
"Id": "d2228d10-5be9-40dd-9c20-6a19343a963a",
"RoleName": "Admin",
"UserName": "root",
"Email": "[email protected]",
"Password": "Root@123"
"CorsSettings": {
"Origins": [
"http://localhost:4200",
"http://external.abriment.com:30081",
"https://codestar.abriment.com"
]
}
}
Loading