[HttpPost("[action]")]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordViewModel model)
{
try
{
var account = await _userManager.FindByNameAsync(User.Identity.Name);
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == account.Id);
if (user != null)
{
IdentityResult result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var userName = user.Email;
var password = model.OldPassword;
var principial = await LoginNotConfirmedPrincipial(user.Id);
if (principial == null)
return StatusCode(400, "Invalide username or password");
DateTime now = DateTime.UtcNow;
var jwt = new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
notBefore: now,
claims: principial.Claims,
expires: now.Add(TimeSpan.FromSeconds(AuthOptions.LIFETIME)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
var encodeJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var principalUser = await _userManager.FindByNameAsync(principial.Name);
var response = new
{
token = encodeJwt,
user = new
{
isAuthenticated = true,
name = principalUser.UserName,
roles = await _userManager.GetRolesAsync(principalUser)
}
};
return Ok(response);
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Ok(result.Errors);
}
}
else
{
return new EmptyResult();
}
}
catch (Exception e)
{
return Ok(e.Message);
}
}
private async Task<ClaimsIdentity> LoginNotConfirmedPrincipial(string userId)
{
Account user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
var roles = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
new Claim(ClaimsIdentity.DefaultRoleClaimType, roles[0])
};
ClaimsIdentity claimsIdentity =
new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
return claimsIdentity;
}
return null;
}