Exemplo n.º 1
0
        public async Task <IdentityResult> Handle(CrearUsuarioComando notification, CancellationToken cancellationToken)
        {
            var entry = new UsuarioAplicacion
            {
                Nombre    = notification.Nombre,
                Apellidos = notification.Apellidos,
                Email     = notification.Email,
                UserName  = notification.Email
            };

            return(await _userManager.CreateAsync(entry, notification.Password));
        }
Exemplo n.º 2
0
        public JsonResult GenerarToken(LoginViewModel login)
        {
            if (login == null)
            {
                throw new ArgumentNullException(nameof(login));
            }

            UsuarioAplicacion user = new UsuarioAplicacion
            {
                UserName = login.NombreUsuario
            };


            SymmetricSecurityKey claveSeguridad = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(
                    _config["JwtOptions:ClaveSecreta"]));

            SigningCredentials credenciales = new SigningCredentials(claveSeguridad, SecurityAlgorithms.HmacSha256);
            List <Claim>       listClaims   = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("name", ""),
                new Claim("id", ""),
                new Claim("cualquiercosavalida", "ejemploheaderparavalidar")
            };

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: listClaims,
                expires: DateTime.Now.AddHours(2),
                signingCredentials: credenciales);

            string json_token = new JwtSecurityTokenHandler().WriteToken(token);

            return(new JsonResult(new {
                token = json_token,
                expire_in = TimeSpan.FromHours(2).TotalSeconds,
                nickname = login.NombreUsuario
            }));
        }
Exemplo n.º 3
0
        private async Task GenerateToken(UsuarioAplicacion usuario, IdentidadAcceso identidadAcceso)
        {
            var secretKey        = _configuration.GetValue <string>("SecretKey");
            var tiempoExpiracion = _configuration.GetValue <int>("TiempoExpiracion");
            var key = Encoding.ASCII.GetBytes(secretKey);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, usuario.Id),
                new Claim(ClaimTypes.Email, usuario.Email),
                new Claim(ClaimTypes.Name, usuario.Nombre),
                new Claim(ClaimTypes.Surname, usuario.Apellidos)
            };

            var roles = await _context.Roles
                        .Where(x => x.UsuarioRoles.Any(y => y.UserId == usuario.Id))
                        .ToListAsync();

            foreach (var role in roles)
            {
                claims.Add(
                    new Claim(ClaimTypes.Role, role.Name)
                    );
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddMinutes(tiempoExpiracion),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature
                    )
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var createdToken = tokenHandler.CreateToken(tokenDescriptor);

            identidadAcceso.Token = tokenHandler.WriteToken(createdToken);
        }
        public async Task <IActionResult> EliminarUsuarioApp(UsuarioViewModel usuario)
        {
            var user = new UsuarioAplicacion {
                UserName = usuario.Usuario, Email = usuario.Usuario
            };
            var result = await _userManager.DeleteAsync(user);

            if (result.Succeeded)
            {
                return(Ok(new JsonResult(new
                {
                    success = string.Format(
                        CultureInfo.CurrentCulture,
                        "usuario eliminado con exito")
                })));
            }

            return(BadRequest(new JsonResult(new
            {
                error = string.Format(
                    CultureInfo.CurrentCulture,
                    "No se pudo eliminar el usuario.")
            })));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new UsuarioAplicacion
                {
                    UserName  = Input.UserName,
                    Email     = Input.Email,
                    Nombre    = Input.Nombre,
                    Apellidos = Input.Apellidos,
                    Direccion = Input.Direccion,
                    Ciudad    = Input.Ciudad,
                    Pais      = Input.Pais,
                };



                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");


                    if (!await _roleManager.RoleExistsAsync(DS.Role_Admin))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(DS.Role_Admin));
                    }

                    if (!await _roleManager.RoleExistsAsync(DS.Role_Cliente))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(DS.Role_Cliente));
                    }

                    if (!await _roleManager.RoleExistsAsync(DS.Role_Inventario))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(DS.Role_Inventario));
                    }

                    if (!await _roleManager.RoleExistsAsync(DS.Role_Ventas))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(DS.Role_Ventas));
                    }

                    await _userManager.AddToRoleAsync(user, DS.Role_Admin);

                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    //var callbackUrl = Url.Page(
                    //    "/Account/ConfirmEmail",
                    //    pageHandler: null,
                    //    values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                    //    protocol: Request.Scheme);

                    //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }