-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
168 lines (145 loc) · 6.54 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
using System.Security.Claims;
using System.Text;
using backend.Authentication;
using backend.Authentication.RoleAccess;
using backend.Models;
using backend.Repositories;
using backend.Repositories.Interfaces;
using backend.Services;
using backend.Services.Interfaces;
using backend.Utils;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace backend;
public static class Program
{
public static T GetFromConfig<T>(this WebApplicationBuilder builder, string configSection)
{
return builder.Configuration.GetSection(configSection).Get<T>()
?? throw new Exception($"No se pudo encontrar el valor {configSection} en la configuracion");
}
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Only allow things within this namespace to log to file
builder.Logging.AddFilter<TextLoggerProvider>((category, _) => category?.StartsWith("backend") ?? false);
builder.Logging.AddProvider(new TextLoggerProvider("../log.txt"));
// Add services to the container.
builder.Services.AddAuthorization(options =>
{
foreach (Access access in Enum.GetValues<Access>())
{
options.AddPolicy(access.ToString(), policy =>
{
policy.Requirements.Add(new AccessRequirement(access));
});
}
});
// Right now it doesn't hold state, so it should be recycled.
builder.Services.AddSingleton<IAuthorizationHandler, AccessHandler>();
string jwtIssuer = builder.GetFromConfig<string>("Jwt:Issuer");
string jwtKey = builder.GetFromConfig<string>("Jwt:Key");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
// Who makes
ValidIssuer = jwtIssuer,
// Who receves
ValidAudience = jwtIssuer, // This is so comical
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
};
});
string rootDirectory = Path.Combine("..", "res");
string usersJsonFile = Path.Combine(rootDirectory,
builder.GetFromConfig<string>("JsonFile:Users"));
string clientsJsonFile = Path.Combine(rootDirectory,
builder.GetFromConfig<string>("JsonFile:Clients"));
string productStatusJsonFile = Path.Combine(rootDirectory,
builder.GetFromConfig<string>("JsonFile:ProductStatuses")
);
JsonClientRepository clientRepo = new(clientsJsonFile, 20);
builder.Services
.AddSingleton<Dictionary<string, IRoleAccess>>(_ => new()
{
{AgenteServiciosRoleAccess.Instance.RoleName, AgenteServiciosRoleAccess.Instance},
{GerenteRoleAccess.Instance.RoleName, GerenteRoleAccess.Instance},
}).AddSingleton<IRoleAccessFactory, DefaultRoleAccessFactory>()
.AddSingleton<IUserRepository, JsonUserRepository>(_ => new(usersJsonFile))
.AddScoped<IUserService, DefaultUserService>()
// Theses are going to break so hard when trying to access concurrently to the same file.
.AddSingleton<IClientRepository, JsonClientRepository>(_ => clientRepo)
.AddScoped<IClientService, DefaultClientService>()
.AddSingleton<IProductNameCheck, JsonClientRepository>(_ => clientRepo)
.AddSingleton<IProductRepository, JsonClientRepository>(_ => clientRepo)
.AddSingleton<INameProduct, DefaultProductService>()
.AddSingleton<IProductFactory, ProductoFactory>()
.AddSingleton<IProductStatusRepository, JsonProductStatusRepository>(_ => new(
productStatusJsonFile,
new FilterByRoleProductStatus()
))
.AddScoped<IProductService, DefaultProductService>()
.AddSingleton<ISeedProductStatusRepository, JsonProductStatusRepository>(_ => new(
productStatusJsonFile,
new FilterByRoleProductStatus()
))
.AddScoped<IProductStatusService, DefaultProductService>();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// From https://www.codeindotnet.com/jwt-bearer-token-authorization-in-swagger-api/
builder.Services.AddSwaggerGen(swagger =>
{
swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
});
swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
var app = builder.Build();
app.Services.GetService<ISeedProductStatusRepository>()?.SeedFile(productStatusJsonFile);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors(options =>
{
// Allow frontend address api calls
options.WithOrigins("http://localhost:5000").AllowAnyMethod().AllowAnyHeader();
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}