Example #1
0
        public async Task <IActionResult> Create([FromBody] AccountRegisterLogin model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(modelError => modelError.ErrorMessage).ToList()));
            }

            var user = new AppUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                _logger.LogWarning($"Error in Creating Account: {result.Errors.Select(x => x.Description).ToList()}");
                return(BadRequest(result.Errors.Select(x => x.Description).ToList()));
            }

            return(Created("", new { user = model.Email }));
        }
Example #2
0
        public async Task <IActionResult> CreateToken([FromBody] AccountRegisterLogin model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Invalid body content");
                }

                //var user = await _userManager.FindByEmailAsync(model.Email);
                var user = _userManager.Users.ToList().First(n => n.Email == model.Email);
                if (user == null ||
                    _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password)
                    != PasswordVerificationResult.Success)
                {
                    if (user != null || _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password)
                        == PasswordVerificationResult.SuccessRehashNeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, model.Password);
                        await _db.SaveChangesAsync();
                    }
                    else
                    {
                        return(BadRequest());
                    }
                }

                var token = await GetJwtSecurityToken(user);

                return(Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Faild to generate token: +{ex}");
            }
            return(BadRequest("Faild to generate token"));
        }