Esempio n. 1
0
        public async Task <ActionResult> Put(int id, [FromBody] Useraquito model)
        {
            var entidad = model;

            entidad.Id = id;
            _context.Entry(entidad).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
Esempio n. 2
0
        public async Task <(string, IEnumerable <string>)> GenerateJwtToken(Useraquito user)
        {
            JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIndentity = new ClaimsIdentity(
                new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())     // for refresh token
            }
                );

            IList <string> userRoles = await _userManager.GetRolesAsync(user);

            foreach (string userRole in userRoles)
            {
                claimsIndentity.AddClaim(new Claim(ClaimTypes.Role, userRole));
            }

            byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = claimsIndentity,
                Expires            = DateTime.UtcNow.AddDays(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            SecurityToken token = jwtTokenHandler.CreateToken(tokenDescriptor);

            string jwtToken = jwtTokenHandler.WriteToken(token);


            return(jwtToken, userRoles);
        }
Esempio n. 3
0
        public async Task <IActionResult> Register([FromBody] UserRequest model)
        {
            BaseResponse res = new BaseResponse();

            if (!ModelState.IsValid)
            {
                res.Message = "Payload no valido";

                return(BadRequest(res));
            }

            // chequear que el email exista
            Useraquito existingUser = await _userManager.FindByEmailAsync(model.Email);

            if (existingUser != null)
            {
                res.Message = "Email ya existe";
                return(BadRequest(res));
            }

            // Chequear si existe el role enviado
            bool existingRole = await _roleManager.RoleExistsAsync(model.Role);

            if (!existingRole)
            {
                res.Message = $"Role '{model.Role}' no existe, ponga un rol valido";
                return(BadRequest(res));
            }

            // Crear Usuario
            var user = _mapper.Map <Useraquito>(model);

            IdentityResult isUserCreated = await _userManager.CreateAsync(user, model.Password);

            if (!isUserCreated.Succeeded)
            {
                res.Message = isUserCreated.Errors.Select(x => x.Description).FirstOrDefault();

                return(new JsonResult(res)
                {
                    StatusCode = 500
                });
            }


            // Agregar role
            IdentityResult isAddedRole = await _userManager.AddToRoleAsync(user, model.Role);

            if (!isAddedRole.Succeeded)
            {
                res.Message = isAddedRole.Errors.Select(x => x.Description).FirstOrDefault();

                return(new JsonResult(res)
                {
                    StatusCode = 500
                });
            }

            (string token, IEnumerable <string> roles) = await _tokenService.GenerateJwtToken(user);

            res.Message = "Usuario creado correctamente";
            res.Ok      = true;
            res.Data    = new {
                Token     = token,
                Roles     = roles,
                UserName  = user.UserName,
                FirstName = user.Firstname,
                LastName  = user.Lastname,
                Phone     = user.Phone,
                Id        = user.Id
            };

            return(Ok(res));
        }