F1 - Autentcacion - Completa
This commit is contained in:
+108
@@ -0,0 +1,108 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using vita_asistente.Data;
|
||||
using vita_asistente.Models;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// 1. Configurar el DbContext con Pomelo MySQL
|
||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
|
||||
|
||||
// 2. Configurar Identity con ApplicationUser y ApplicationDbContext
|
||||
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
|
||||
{
|
||||
// Configuraciones opcionales de Identity (contraseñas, bloqueos, etc.)
|
||||
options.Password.RequireDigit = true;
|
||||
options.Password.RequiredLength = 6;
|
||||
options.Password.RequireNonAlphanumeric = false;
|
||||
options.Password.RequireUppercase = false;
|
||||
options.Password.RequireLowercase = false;
|
||||
})
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
builder.Services.ConfigureApplicationCookie(options =>
|
||||
{
|
||||
options.LoginPath = "/Account/Login";
|
||||
options.LogoutPath = "/Account/Logout";
|
||||
options.AccessDeniedPath = "/Account/AccessDenied";
|
||||
});
|
||||
|
||||
// 3. Agregar autenticación (ya incluida con AddIdentity, pero aseguramos)
|
||||
builder.Services.AddAuthentication();
|
||||
|
||||
// El resto de tus servicios...
|
||||
builder.Services.AddControllersWithViews(); // o AddRazorPages según tu proyecto
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
//seeds
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
try
|
||||
{
|
||||
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
|
||||
|
||||
// Crear roles si no existen
|
||||
string[] roles = { "Admin", "Usuario" };
|
||||
foreach (var role in roles)
|
||||
{
|
||||
if (!await roleManager.RoleExistsAsync(role))
|
||||
{
|
||||
await roleManager.CreateAsync(new IdentityRole(role));
|
||||
}
|
||||
}
|
||||
|
||||
// Crear un usuario admin si no existe
|
||||
var adminUser = await userManager.FindByEmailAsync("admin@example.com");
|
||||
if (adminUser == null)
|
||||
{
|
||||
adminUser = new ApplicationUser
|
||||
{
|
||||
UserName = "admin@example.com",
|
||||
Email = "admin@example.com",
|
||||
Nombre = "Admin",
|
||||
Apellido = "Sistema",
|
||||
Documento = "00000000",
|
||||
Direccion = "Calle Falsa 123",
|
||||
};
|
||||
var result = await userManager.CreateAsync(adminUser, "Admin123!");
|
||||
if (result.Succeeded)
|
||||
{
|
||||
await userManager.AddToRoleAsync(adminUser, "Admin");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var logger = services.GetRequiredService<ILogger<Program>>();
|
||||
logger.LogError(ex, "Error al crear roles o usuario admin.");
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Home/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseStaticFiles();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllerRoute(
|
||||
name: "default",
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
|
||||
app.Run();
|
||||
Reference in New Issue
Block a user