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

Implementação login #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
64 changes: 55 additions & 9 deletions src/login/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,78 @@
using Microsoft.AspNetCore.Mvc;
using projeto_adotapet.Models;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace projeto_adotapet.Controllers
{
public class HomeController : Controller
public class LoginController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly AppDbContext _context;

public HomeController(ILogger<HomeController> logger)
public LoginController(AppDbContext context)
{
_logger = logger;
_context = context;
}

// Exibir p�gina de login
public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
// Processar o login
[HttpPost]
public async Task<IActionResult> Index(string nome, string senha)
{
var usuario = await _context.Usuarios
.FirstOrDefaultAsync(u => u.Nome == nome);

if (usuario != null && usuario.VerificarSenha(senha))
{
// Login bem-sucedido
HttpContext.Session.SetString("UserName", usuario.Nome); // Salvando nome na sess�o
return RedirectToAction("Index", "Home"); // Redireciona para a p�gina inicial ap�s login
}

// Caso falhe
ModelState.AddModelError("", "Nome de usu�rio ou senha inv�lidos.");
return View();
}

// Exibir p�gina de registro
public IActionResult Register()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
// Processar o registro de um novo usu�rio
[HttpPost]
public async Task<IActionResult> Register(Usuario usuario, string ConfirmSenha)
{
if (ModelState.IsValid)
{
// Verificar se as senhas coincidem
if (usuario.Senha != ConfirmSenha)
{
ModelState.AddModelError("", "As senhas n�o coincidem.");
return View(usuario);
}

// Criptografar a senha antes de salvar no banco
usuario.SetSenha(usuario.Senha);
_context.Usuarios.Add(usuario);
await _context.SaveChangesAsync();
return RedirectToAction("Index"); // Redireciona para a p�gina de login ap�s o registro
}
return View(usuario);
}

// Logout
public IActionResult Logout()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
HttpContext.Session.Remove("UserName"); // Remover o nome de usu�rio da sess�o
return RedirectToAction("Index", "Login"); // Redireciona para a p�gina de login
}
}
}
3 changes: 1 addition & 2 deletions src/login/Models/AppDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

public DbSet<Veiculo> Veiculos { get; set; }

public DbSet<Usuario> Usuarios { get; set; }
}
}
43 changes: 43 additions & 0 deletions src/login/Models/Usuario.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Importando o namespace do BCrypt.Net
using BCrypt.Net;

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace projeto_adotapet.Models
{
[Table("Usuarios")]
public class Usuario
{
[Key]
public int Id { get; set; }

[Required(ErrorMessage = "Obrigatório informar o nome")]
public string Nome { get; set; }

[Required(ErrorMessage = "Obrigatório informar a senha")]
[DataType(DataType.Password)]
public string Senha { get; set; }

[Required(ErrorMessage = "Obrigatório informar o perfil")]
public Perfil Perfil { get; set; }

// Método para criar hash da senha
public void SetSenha(string senha)
{
this.Senha = BCrypt.Net.BCrypt.HashPassword(senha); // Usando BCrypt para gerar o hash da senha
}

// Método para verificar a senha fornecida
public bool VerificarSenha(string senha)
{
return BCrypt.Net.BCrypt.Verify(senha, this.Senha); // Verificando a senha com o hash
}
}

public enum Perfil
{
Admin,
User
}
}
43 changes: 36 additions & 7 deletions src/login/Program.cs
Original file line number Diff line number Diff line change
@@ -1,34 +1,63 @@
using projeto_adotapet.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Adicionando os servi�os ao container
builder.Services.AddControllersWithViews();

builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

// Configura��o do banco de dados (SQL Server)
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Configura��o de Autentica��o por Cookie
builder.Services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", options =>
{
options.LoginPath = "/Login/Index"; // P�gina de login
options.LogoutPath = "/Login/Logout"; // P�gina de logout
options.ExpireTimeSpan = TimeSpan.FromMinutes(60); // Tempo de expira��o do cookie
options.SlidingExpiration = true; // Expira��o deslizante do cookie
});

// Configura��o de Sess�es
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // Tempo de expira��o da sess�o
options.Cookie.HttpOnly = true; // Seguran�a adicional para o cookie de sess�o
options.Cookie.IsEssential = true; // O cookie � essencial para a aplica��o funcionar
});

var app = builder.Build();

// Configure the HTTP request pipeline.
// Configura��o do pipeline de requisi��es HTTP
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.UseHsts(); // HSTS (HTTP Strict Transport Security)
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();
// Ordem dos middlewares
app.UseSession(); // Coloque UseSession antes de UseAuthentication
app.UseAuthentication(); // Autentica��o
app.UseAuthorization(); // Autoriza��o

// Configura��o das rotas
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
pattern: "{controller=Login}/{action=Index}/{id?}"); // Alterado para LoginController

app.Run();
8 changes: 0 additions & 8 deletions src/login/Views/Home/Index.cshtml

This file was deleted.

32 changes: 32 additions & 0 deletions src/login/Views/Login/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
@{
ViewData["Title"] = "Login";
}

<h2>Login</h2>

<!-- Exibir erros de validação, se houver -->
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
<ul>
@foreach (var error in ViewData.ModelState.Values.SelectMany(v => v.Errors))
{
<li>@error.ErrorMessage</li>
}
</ul>
</div>
}

<form method="post">
<div class="form-group">
<label for="Nome">Nome de Usuário:</label>
<input type="text" class="form-control" id="Nome" name="nome" required />
</div>
<div class="form-group">
<label for="Senha">Senha:</label>
<input type="password" class="form-control" id="Senha" name="senha" required />
</div>
<button type="submit" class="btn btn-primary">Entrar</button>
</form>

<p><a href="@Url.Action("Register", "Login")">Realizar Cadastro</a></p>