Skip to content

Commit

Permalink
Seccion 07 Finalizada
Browse files Browse the repository at this point in the history
  • Loading branch information
debsdaniel committed Mar 13, 2019
1 parent eb1a5ba commit ef3ed78
Show file tree
Hide file tree
Showing 9 changed files with 335 additions and 13 deletions.
37 changes: 31 additions & 6 deletions Controllers/LoginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,34 @@
using System.Text;

using contactos.Models;
using contactos.Services;

namespace contactos.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class LoginController : Controller
{
private IConfiguration _config;
private IConfiguration _config;
private IUserService _userService;

public LoginController(IConfiguration config)
public LoginController(IConfiguration config, IUserService userService)
{
_config = config;
_userService = userService;
}

[HttpPost]
[AllowAnonymous]
public IActionResult Login([FromBody]Usuario login)
public IActionResult Login([FromBody]UserDto login)
{
IActionResult response = Unauthorized();
//Método responsable de Validar las credenciales del usuario y devolver el modelo Usuario
//Para demostración (en este punto) he usado datos de prueba sin persistencia de Datos
//Si no retorna un objeto nulo, se procede a generar el JWT.
//Usando el método GenerateJSONWebToken
var user = AuthenticateUser(login);
//var user = AuthenticateUser(login);
var user = _userService.Authenticate(login.username, login.password);

if (user != null)
{
Expand All @@ -41,16 +45,37 @@ public IActionResult Login([FromBody]Usuario login)

return response;
}

[Authorize]
[HttpPost("register")]
public IActionResult Register([FromBody] UserDto userDto)
{
User user = new User {} ;
user.username = userDto.username;
user.email = userDto.email;
user.fechacreado = userDto.FechaCreado;

try
{
_userService.Create(user, userDto.password);
return Ok();
}
catch(Exception ex)
{
return BadRequest(new {message = ex.Message});
}
}

private string GenerateJSONWebToken(Usuario userInfo)

private string GenerateJSONWebToken(User userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, userInfo.username),
new Claim(JwtRegisteredClaimNames.Email, userInfo.email),
new Claim("FechaCreado", userInfo.FechaCreado.ToString("yyyy-MM-dd")),
new Claim("FechaCreado", userInfo.fechacreado.ToString("yyyy-MM-dd")),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

Expand Down
64 changes: 64 additions & 0 deletions Migrations/20190313050111_UserAdd.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions Migrations/20190313050111_UserAdd.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace contactos.Migrations
{
public partial class UserAdd : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Usuario");

migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
username = table.Column<string>(maxLength: 20, nullable: false),
fechacreado = table.Column<DateTime>(nullable: false),
email = table.Column<string>(nullable: true),
PasswordHash = table.Column<byte[]>(nullable: true),
PasswordSalt = table.Column<byte[]>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.username);
});
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "User");

migrationBuilder.CreateTable(
name: "Usuario",
columns: table => new
{
username = table.Column<string>(maxLength: 20, nullable: false),
FechaCreado = table.Column<DateTime>(nullable: false),
email = table.Column<string>(nullable: true),
password = table.Column<string>(maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Usuario", x => x.username);
});
}
}
}
12 changes: 6 additions & 6 deletions Migrations/ContactosContextModelSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,23 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.ToTable("Contacto");
});

modelBuilder.Entity("contactos.Models.Usuario", b =>
modelBuilder.Entity("contactos.Models.User", b =>
{
b.Property<string>("username")
.ValueGeneratedOnAdd()
.HasMaxLength(20);

b.Property<DateTime>("FechaCreado");
b.Property<byte[]>("PasswordHash");

b.Property<byte[]>("PasswordSalt");

b.Property<string>("email");

b.Property<string>("password")
.IsRequired()
.HasMaxLength(100);
b.Property<DateTime>("fechacreado");

b.HasKey("username");

b.ToTable("Usuario");
b.ToTable("User");
});
#pragma warning restore 612, 618
}
Expand Down
2 changes: 1 addition & 1 deletion Models/ContactosContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ public ContactosContext(DbContextOptions<ContactosContext> options)

}
public DbSet<Contacto> Contacto {get; set;}
public DbSet<Usuario> Usuario {get; set;}
public DbSet<User> User {get; set;}
}
}
20 changes: 20 additions & 0 deletions Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.ComponentModel.DataAnnotations;

namespace contactos.Models
{
public class User
{
[Key]
[Required]
[Display(Name="Username")]
[StringLength(20, ErrorMessage = "El valor para {0} debe contener al menos {2} y máximo {1} caracteres de longitud.", MinimumLength = 6)]
public string username { get; set; }
public DateTime fechacreado { get; set; }
public string email { get; set; }

public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }

}
}
21 changes: 21 additions & 0 deletions Models/UserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.ComponentModel.DataAnnotations;

namespace contactos.Models
{
public class UserDto
{
[Key]
[Required]
[Display(Name="Username")]
[StringLength(20, ErrorMessage = "El valor para {0] debe contener al menos {2} y máximo {1} caracteres", MinimumLength=6)]
public string username {get; set;}

public string password {get; set;}

public string email {get; set;}

[DataType(DataType.Date)]
public DateTime FechaCreado {get; set;}
}
}
Loading

0 comments on commit ef3ed78

Please sign in to comment.