-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
418 lines (388 loc) · 12.5 KB
/
Program.cs
File metadata and controls
418 lines (388 loc) · 12.5 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
using System.Text;
using ApiEcommerce.Constants;
using ApiEcommerce.Data;
using ApiEcommerce.Models;
using ApiEcommerce.Repository;
using ApiEcommerce.Repository.IRepository;
using Asp.Versioning;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var dbConnectionString = builder.Configuration.GetConnectionString("ConexionSql");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(dbConnectionString)
.UseSeeding((context, _) =>
{
var appContext = (ApplicationDbContext)context;
DataSeeder.SeedData(appContext);
})
);
builder.Services.AddResponseCaching(options =>
{
options.MaximumBodySize = 1024 * 1024;
options.UseCaseSensitivePaths = true;
}
);
builder.Services.AddScoped<ICategoryRepository,CategoryRepository>();
builder.Services.AddScoped<IProductRepository,ProductRepository>();
builder.Services.AddScoped<IUserRepository,UserRepository>();
// Registrar configuración de Mapster
ApiEcommerce.Mapping.MapsterConfig.RegisterMappings();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var secretKey = builder.Configuration.GetValue<string>("ApiSettings:SecretKey");
if (string.IsNullOrEmpty(secretKey))
{
throw new InvalidOperationException("SecretKey no esta configurada");
}
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}
).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
ValidateIssuer = false,
ValidateAudience = false,
};
});
builder.Services.AddControllers(option =>
{
option.CacheProfiles.Add(CacheProfiles.Default10, CacheProfiles.Profile10);
option.CacheProfiles.Add(CacheProfiles.Default20, CacheProfiles.Profile20);
}
);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(
options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Nuestra API utiliza la Autenticación JWT usando el esquema Bearer. \n\r\n\r" +
"Ingresa la palabra a continuación el token generado en login.\n\r\n\r" +
"Ejemplo: \"12345abcdef\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
options.SwaggerDoc("v1",new OpenApiInfo
{
Version = "v1",
Title = "API Ecommerce",
Description = "API para gestionar productos y usuarios",
TermsOfService = new Uri("https://bgm.com/terms"),
Contact = new OpenApiContact
{
Name = "BreinerGM",
Url = new Uri("https://bgm.com.co")
},
License = new OpenApiLicense
{
Name = "License",
Url = new Uri("https://bgm.com/licenses")
}
});
options.SwaggerDoc("v2",new OpenApiInfo
{
Version = "v2",
Title = "API Ecommerce V2",
Description = "API para gestionar productos y usuarios",
TermsOfService = new Uri("https://bgm.com/terms"),
Contact = new OpenApiContact
{
Name = "BreinerGM",
Url = new Uri("https://bgm.com.co")
},
License = new OpenApiLicense
{
Name = "License",
Url = new Uri("https://bgm.com/licenses")
}
});
}
);
var apiVersioningBuilder = builder.Services.AddApiVersioning(option =>
{
option.AssumeDefaultVersionWhenUnspecified = true;
option.DefaultApiVersion = new ApiVersion(1,0);
option.ReportApiVersions = true;
//option.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"));
});
apiVersioningBuilder.AddApiExplorer(option =>
{
option.GroupNameFormat = "'v'VVV"; // v1,v2,v3
option.SubstituteApiVersionInUrl = true;
});
builder.Services.AddCors(options =>
{
options.AddPolicy(PolicyNames.AllowSpecificOrigin,
builder =>
{
builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}
);
}
);
var app = builder.Build();
// Ejecutar seeding/migraciones al arrancar
using (var scope = app.Services.CreateScope())
{
var appContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Aplicar migraciones pendientes
appContext.Database.Migrate();
// Seeding de Roles
if (!appContext.Roles.Any())
{
appContext.Roles.AddRange(
new IdentityRole { Id = "1", Name = "Admin", NormalizedName = "ADMIN" },
new IdentityRole { Id = "2", Name = "User", NormalizedName = "USER" }
);
}
// Seeding de Categorías
if (!appContext.Categories.Any())
{
appContext.Categories.AddRange(
new Category { Name = "Ropa y accesorios", CreationDate = DateTime.Now },
new Category { Name = "Electrónicos", CreationDate = DateTime.Now },
new Category { Name = "Deportes", CreationDate = DateTime.Now },
new Category { Name = "Hogar", CreationDate = DateTime.Now },
new Category { Name = "Libros", CreationDate = DateTime.Now }
);
}
// Seeding de Usuario Administrador
if (!appContext.ApplicationUsers.Any())
{
var hasher = new PasswordHasher<ApplicationUser>();
var adminUser = new ApplicationUser
{
Id = "admin-001",
UserName = "[email protected]",
NormalizedUserName = "[email protected]",
Email = "[email protected]",
NormalizedEmail = "[email protected]",
EmailConfirmed = true,
Name = "Administrador"
};
adminUser.PasswordHash = hasher.HashPassword(adminUser, "Admin123!");
var regularUser = new ApplicationUser
{
Id = "user-001",
UserName = "[email protected]",
NormalizedUserName = "[email protected]",
Email = "[email protected]",
NormalizedEmail = "[email protected]",
EmailConfirmed = true,
Name = "Usuario Regular"
};
regularUser.PasswordHash = hasher.HashPassword(regularUser, "User123!");
appContext.ApplicationUsers.AddRange(adminUser, regularUser);
}
// Seeding de UserRoles
if (!appContext.UserRoles.Any())
{
appContext.UserRoles.AddRange(
new IdentityUserRole<string> { UserId = "admin-001", RoleId = "1" }, // Admin
new IdentityUserRole<string> { UserId = "user-001", RoleId = "2" } // User
);
}
// Seeding de Productos
if (!appContext.Products.Any())
{
appContext.Products.AddRange(
new Product
{
Name = "Camiseta Básica",
Description = "Camiseta de algodón 100%",
Price = 25.99m,
SKU = "PROD-001-CAM-M",
Stock = 50,
CategoryId = 1,
Category = appContext.Categories.Find(1)!,
ImgUrl = "https://via.placeholder.com/300x300/FF0000/FFFFFF?text=Camiseta",
CreationDate = DateTime.Now
},
new Product
{
Name = "Smartphone Galaxy",
Description = "Teléfono inteligente con 128GB",
Price = 599.99m,
SKU = "PROD-002-PHO-BLK",
Stock = 25,
CategoryId = 2,
Category = appContext.Categories.Find(2)!,
ImgUrl = "https://via.placeholder.com/300x300/0000FF/FFFFFF?text=Smartphone",
CreationDate = DateTime.Now
},
new Product
{
Name = "Pelota de Fútbol",
Description = "Pelota oficial FIFA",
Price = 45.00m,
SKU = "PROD-003-BAL-WHT",
Stock = 30,
CategoryId = 3,
Category = appContext.Categories.Find(3)!,
ImgUrl = "https://via.placeholder.com/300x300/00FF00/FFFFFF?text=Pelota",
CreationDate = DateTime.Now
},
new Product
{
Name = "Lámpara de Mesa",
Description = "Lámpara LED regulable",
Price = 89.99m,
SKU = "PROD-004-LAM-WHT",
Stock = 15,
CategoryId = 4,
Category = appContext.Categories.Find(4)!,
ImgUrl = "https://via.placeholder.com/300x300/FFFF00/000000?text=Lampara",
CreationDate = DateTime.Now
},
new Product
{
Name = "El Quijote",
Description = "Novela clásica de Cervantes",
Price = 19.99m,
SKU = "PROD-005-LIB-ESP",
Stock = 100,
CategoryId = 5,
Category = appContext.Categories.Find(5)!,
ImgUrl = "https://via.placeholder.com/300x300/800080/FFFFFF?text=Libro",
CreationDate = DateTime.Now
},
new Product
{
Name = "Jeans Clásicos",
Description = "Pantalones vaqueros azules",
Price = 79.99m,
SKU = "PROD-006-PAN-BLU",
Stock = 40,
CategoryId = 1,
Category = appContext.Categories.Find(1)!,
ImgUrl = "https://via.placeholder.com/300x300/4169E1/FFFFFF?text=Jeans",
CreationDate = DateTime.Now
},
new Product
{
Name = "Tablet Pro",
Description = "Tablet 10.5 pulgadas con stylus incluido",
Price = 459.99m,
SKU = "PROD-007-TAB-SIL",
Stock = 20,
CategoryId = 2,
Category = appContext.Categories.Find(2)!,
ImgUrl = "https://via.placeholder.com/300x300/C0C0C0/000000?text=Tablet",
CreationDate = DateTime.Now
},
new Product
{
Name = "Zapatillas Running",
Description = "Zapatillas deportivas para correr",
Price = 129.99m,
SKU = "PROD-008-ZAP-BLK",
Stock = 35,
CategoryId = 3,
Category = appContext.Categories.Find(3)!,
ImgUrl = "https://via.placeholder.com/300x300/000000/FFFFFF?text=Zapatillas",
CreationDate = DateTime.Now
},
new Product
{
Name = "Cafetera Express",
Description = "Cafetera automática con molinillo integrado",
Price = 299.99m,
SKU = "PROD-009-CAF-BLK",
Stock = 12,
CategoryId = 4,
Category = appContext.Categories.Find(4)!,
ImgUrl = "https://via.placeholder.com/300x300/2F4F4F/FFFFFF?text=Cafetera",
CreationDate = DateTime.Now
},
new Product
{
Name = "Programación en C#",
Description = "Guía completa de programación en C# y .NET",
Price = 49.99m,
SKU = "PROD-010-LIB-ESP",
Stock = 80,
CategoryId = 5,
Category = appContext.Categories.Find(5)!,
ImgUrl = "https://via.placeholder.com/300x300/008B8B/FFFFFF?text=C%23+Book",
CreationDate = DateTime.Now
},
new Product
{
Name = "Chaqueta Deportiva",
Description = "Chaqueta impermeable para actividades al aire libre",
Price = 149.99m,
SKU = "PROD-011-CHA-NAV",
Stock = 28,
CategoryId = 1,
Category = appContext.Categories.Find(1)!,
ImgUrl = "https://via.placeholder.com/300x300/000080/FFFFFF?text=Chaqueta",
CreationDate = DateTime.Now
},
new Product
{
Name = "Auriculares Bluetooth",
Description = "Auriculares inalámbricos con cancelación de ruido",
Price = 189.99m,
SKU = "PROD-012-AUR-BLK",
Stock = 45,
CategoryId = 2,
Category = appContext.Categories.Find(2)!,
ImgUrl = "https://via.placeholder.com/300x300/1C1C1C/FFFFFF?text=Auriculares",
CreationDate = DateTime.Now
}
);
}
appContext.SaveChanges();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
options.SwaggerEndpoint("/swagger/v2/swagger.json", "v2");
});
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseCors(PolicyNames.AllowSpecificOrigin);
app.UseResponseCaching();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();