/// <summary> /// Creates a new record. /// </summary> /// <returns>Id of new record</returns> public override async Task <int> Create([FromBody] UserDto entity) { if (!string.IsNullOrWhiteSpace(entity.Password)) { entity.Password = PasswordSecurityHelper.HashPassword(entity.Password, _appSettings.PasswordSalt); } return(await base.Create(entity).ConfigureAwait(false)); }
public async Task <AuthResponseDto> Authenticate(string email, string password, CancellationToken cancellationToken) { var userRecord = await _userQueries.GetUserAsync(_ajkaShopDbContext, email, cancellationToken).ConfigureAwait(false); if (userRecord == null) { return(new AuthResponseDto { ErrorMessage = AuthConstants.errorNameOrPasswordIsInvalid }); } if (!userRecord.Password.Equals(PasswordSecurityHelper.HashPassword(password, _appSettings.PasswordSalt))) { return(new AuthResponseDto { ErrorMessage = AuthConstants.errorNameOrPasswordIsInvalid }); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.ClientSecret); var claim = new Claim(ClaimTypes.Role, RoleConstants.LoggedInUserRole); if (userRecord.IsAdministrator) { claim = new Claim(ClaimTypes.Role, RoleConstants.AdministratorRole); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { claim, new Claim(ClaimTypes.Name, userRecord?.Name), new Claim(ClaimTypes.Surname, userRecord?.Surname), new Claim(ClaimTypes.Email, userRecord?.Email) }), Expires = DateTime.UtcNow.AddHours(6), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(new AuthResponseDto { UserId = userRecord.Id, AccessToken = tokenHandler.WriteToken(token) }); }
/// <summary> /// Update a record. /// </summary> /// <param name="entity">Entity with valid Id</param> /// <returns>true=success</returns> public override async Task <bool> Update([FromBody] UserDto entity) { if (!string.IsNullOrWhiteSpace(entity.Password)) { entity.Password = PasswordSecurityHelper.HashPassword(entity.Password, _appSettings.PasswordSalt); } else { var previousEntity = await Get(entity.Id).ConfigureAwait(false); if (previousEntity != null) { entity.Password = previousEntity.Password; } } return(await base.Update(entity).ConfigureAwait(false)); }