# 9.2.4 Agregando usuarios y roles

Para agregar el usuario vamos a crear una función para que nos genere el salt.&#x20;

En nuestra carpeta **Core** agregamos una nueva clase llamada **Seguridad** y agregamos una función **GetSalt**, esta función nos regresa una cadena aleatoria.&#x20;

También agregamos la función  **GetHash** el cual nos devolverá el hash de la cadena de texto que enviamos como parámetro.

{% code title="Seguridad.cs" %}

```csharp
using System;
using System.Security.Cryptography;

namespace CaducaRest.Core
{
    public class Seguridad
    {
        public Seguridad()
        {
        }

        public string GetSalt()
        {
            byte[] bytes = new byte[128 / 8];
            using (var keyGenerator = RandomNumberGenerator.Create())
            {
                keyGenerator.GetBytes(bytes);
                return BitConverter.ToString(bytes).ToLower();
            }
        }
        
        public string GetHash(string text)
        { 
            using (var sha256 = SHA256.Create())
            {  
                var hashedBytes = sha256
                        .ComputeHash(Encoding.UTF8.GetBytes(text));
                return BitConverter
                     .ToString(hashedBytes).ToLower();
            }
        }
     }
}
```

{% endcode %}

En nuestra carpeta **DAO** creamos nuestra clase **UsuarioDAO**, en la función **agregarUsuario**, agregamos las funciones que creamos para guardar el salt y el password con un hash

{% code title="UsuarioDAO.cs" %}

```csharp
public class UsuarioDAO
{
    private readonly CaducaContext contexto;

    public CustomError customError;

    public UsuarioDAO(CaducaContext context)
    {
        this.contexto = context;
    }

    public async Task<bool> AgregarAsync(Usuario usuario)
    {
        contexto.Usuario.Add(usuario);
        Seguridad seguridad = new Seguridad();
        usuario.Adicional1 = seguridad.GetSalt();
        usuario.Password = seguridad.GetHash(usuario.Adicional1
                                                  + usuario.Password );
        await contexto.SaveChangesAsync();
        return true;
    }
}
```

{% endcode %}

En nuestro archivo **CaducaContext**, en la región de los inserts agregamos 3 usuarios uno por cada tipo de usuario.

{% hint style="warning" %}
Por seguridad tu primer usuario no debe ser el usuario administrador, ni llamarse admin, administrador, supervisor, superusuario, ni tampoco tener el nombre apellido del dueño o gerente, como por ejemplo chernandez ya que un hacker es lo primero que busca, intenta ver si el primer usuario es el administrador e intenta con esos nombres de usuarios.
{% endhint %}

{% code title="CaducaContext.cs" %}

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    #region Inserts
    string salt1 = seguridad.GetSalt();
    string salt2 = seguridad.GetSalt();
    string salt3 = seguridad.GetSalt();
    modelBuilder.Entity<Usuario>().HasData(
                new Usuario
                {
                    Id = 1,
                    Activo = true,
                    Clave = "Juan",
                    Email = "correo@gmail.com",
                    Nombre = "Juan Peréz",
                    Adicional1 = salt1,
                    Password = seguridad.GetHash(salt1 + "zUvyvsRSCMek58eR")
                },
                new Usuario
                {
                    Id = 2,
                    Activo = true,
                    Clave = "Maria",
                    Email = "correo@gmail.com",
                    Nombre = "Maria Lopez",
                    Adicional1 = salt2,
                    Password = seguridad.GetHash(salt2  + "8cYyY8paESGbzC5E")
                },
                new Usuario
                {
                    Id = 3,
                    Activo = true,
                    Clave = "Carlos",
                    Email = "correo@gmail.com",
                    Nombre = "Carlos Hernández",
                    Adicional1 = salt3,
                    Password = seguridad.GetHash(salt3  + "DtfhkmTRQ8mNzgRY")
                }
                );
```

{% endcode %}

Agregamos el rol a cada usuario

{% code title="CaducaContext.cs" %}

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    #region Inserts
    modelBuilder.Entity<UsuarioRol>().HasData(
                new UsuarioRol
                {
                    Id = 1,
                    RolId = 3,
                    UsuarioId = 1
                },
                new UsuarioRol
                {
                    Id = 2,
                    RolId = 2,
                    UsuarioId = 2
                },
                new UsuarioRol
                {
                    Id = 3,
                    RolId = 1,
                    UsuarioId = 3
                }
                );
```

{% endcode %}

Agregamos la migración **UsuariosRoles**

```
Add-Migration UsuariosRoles
```

De la migración que se creó, vemos los valores que se generaron para el salt, password y los sustituimos en nuestra clase caducaContext

```csharp
modelBuilder.Entity<Usuario>().HasData(
        new Usuario
            {
                Id = 1,
                Activo = true,
                Clave = "Juan",
                Email = "correo@gmail.com",
                Nombre = "Juan Peréz",
                Adicional1 = "2a3efe03a96840478bde71ae36a20f2e",
                Password = "9f9b901a43d795295661443f7f7098ee8e6c6c3694428717c54d5fd058220fed"
            },
        new Usuario
            {
                Id = 2,
                Activo = true,
                Clave = "Maria",
                Email = "correo@gmail.com",
                Nombre = "Maria Lopez",
                Adicional1 = "37b93bbd77b2d7a586cc7d5032f83808",
                Password = "6ad9ebcfe2bebed6655a4abb3e0409c83ad1e6db35098083476744cfe0d106b9"
            },
        new Usuario
            {
                Id = 3,
                Activo = true,
                Clave = "Carlos",
                Email = "correo@gmail.com",
                Nombre = "Carlos Hernández",
                Adicional1 = "5dd69f799e8ac1fd877460c4d461eb74",
                Password = "6c60e72d7ea36a7defc15f0b551cd739180d2254ddaf4c8833ece2ecf8b48c5a"
             }
         )
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://abi.gitbook.io/net-core/7.-seguridad/7.2-seguridad-basada-en-roles/7.6-agregando-usuarios-y-roles.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
