public async Task <IActionResult> Delete(string id) { var user = await _userManager.FindByIdAsync(id); if (user == null) { return(StatusCode(404, ResponseDto <int> .NotFound("Пользователя с таким id не существует"))); } var isAdmin = await _userManager.IsInRoleAsync(user, "Admin"); if (isAdmin) { StatusCode(400, ResponseDto <int> .BadRequest("Невозможно удалить администратора")); } var result = await _userManager.DeleteAsync(user); if (result.Succeeded) { return(NoContent()); } return(StatusCode(400, ResponseDto <int> .BadRequest("Невозможно удалить пользователя"))); }
public async Task <ActionResult> RaisePrice(Guid id, [FromBody] NewPriceRaiseDto newPriceRaiseDto) { var curLastRaise = (await _raiseRepository.ListAllAsync()) .Where(r => r.AuctionId == id) .OrderByDescending(r => r.Date) .FirstOrDefault(); var raise = _mapper.Map <PriceRaise>(newPriceRaiseDto); raise.RaisedUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); raise.AuctionId = id; raise.Date = DateTime.Now; // FEATURE to update user balance on each price raise (automatically returns to prev user) var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var user = await _userManager.FindByIdAsync(userId); var balance = user.Balance; if (curLastRaise != null && curLastRaise.RaisedUserId == user.Id) { balance += curLastRaise.EndPrice; } if (balance < raise.EndPrice) { return(StatusCode(400, ResponseDto <int> .BadRequest("Недостаточный баланс"))); } var result = await _raiseRepository.AddAsync(raise); if (result == null) { return(BadRequest()); } if (curLastRaise != null) { var prevUser = await _userManager.FindByIdAsync(curLastRaise.RaisedUserId); prevUser.Balance += curLastRaise.EndPrice; await _userManager.UpdateAsync(prevUser); } user.Balance -= raise.EndPrice; await _userManager.UpdateAsync(user); return(Ok(ResponseDto <int> .Ok())); }
public async Task <IActionResult> ChangePassword([FromBody] PasswordChangeDto passwordChangeDto) { if (passwordChangeDto.NewPassword != passwordChangeDto.NewPasswordConfirmation) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пароли не совпадают"))); } var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var user = await _userManager.FindByIdAsync(userId); var result = await _userManager.ChangePasswordAsync(user, passwordChangeDto.CurrentPassword, passwordChangeDto.NewPassword); if (result.Succeeded) { return(Ok(ResponseDto <int> .Ok())); } return(StatusCode(400, ResponseDto <int> .BadRequest("Неверный текущий пароль"))); }
public async Task <IActionResult> ValidateRegistration([FromBody] RegisterDto registerDto) { if (string.IsNullOrEmpty(registerDto.Email)) { return(StatusCode(400, ResponseDto <int> .BadRequest("Email не может быть пуст"))); } if (string.IsNullOrEmpty(registerDto.Username)) { return(StatusCode(400, ResponseDto <int> .BadRequest("Username не может быть пуст"))); } if (string.IsNullOrEmpty(registerDto.Password)) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пароль не может быть пуст"))); } if (string.IsNullOrEmpty(registerDto.PasswordConfirmation)) { return(StatusCode(400, ResponseDto <int> .BadRequest("Подтверждение не может быть пусто"))); } if (registerDto.Password != registerDto.PasswordConfirmation) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пароли не совпадают"))); } var user = await _userManager.FindByNameAsync(registerDto.Username); if (user != null) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пользователь с таким именем существует"))); } user = await _userManager.FindByEmailAsync(registerDto.Email); if (user != null) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пользователь с таким email существует"))); } return(Ok(ResponseDto <int> .Ok())); }
public async Task <IActionResult> CreateToken([FromBody] LoginDto loginDto) { if (!ModelState.IsValid) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пароли не совпадают"))); } var loginResult = await _signInManager.PasswordSignInAsync(loginDto.Username, loginDto.Password, false, false); if (!loginResult.Succeeded) { return(StatusCode(400, ResponseDto <int> .BadRequest("Неверный пароль"))); } var user = await _userManager.FindByNameAsync(loginDto.Username); var token = new TokenDto { Token = await GetToken(user) }; return(Ok(ResponseDto <TokenDto> .Ok(token))); }
public async Task <IActionResult> Register([FromBody] RegisterDto registerDto) { if (registerDto.Password != registerDto.PasswordConfirmation) { return(StatusCode(400, ResponseDto <int> .BadRequest("Пароли не совпадают"))); } if (!ValidateCreditCard(registerDto.CardNumber)) { return(StatusCode(400, ResponseDto <int> .BadRequest("Неверный формат номера карты"))); } try { _mapper.Map <ApplicationUser>(registerDto); } catch (Exception e) { StatusCode(400, ResponseDto <int> .BadRequest("Неверный формат даты")); } var user = _mapper.Map <ApplicationUser>(registerDto); user.RegistrationDate = DateTime.Now; var identityResult = await _userManager.CreateAsync(user, registerDto.Password); if (!identityResult.Succeeded) { return(BadRequest(identityResult.Errors)); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var base64 = Convert.ToBase64String(Encoding.Unicode.GetBytes(code)); var request = ControllerContext.HttpContext.Request; var uriBuilder = new UriBuilder { Scheme = request.Scheme, Host = request.Host.Host, Path = "api/auth/confirmation", Query = $"username={user.UserName}&code={base64}" }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var callbackUrl = uriBuilder.Uri.ToString(); try { _emailSender.SendEmail(registerDto.Email, "Confirm your email", $"Please confirm your account by <a href=\"{callbackUrl}\">clicking here</a>."); } catch (Exception e) { Console.WriteLine(e.Message); } return(Ok(ResponseDto <int> .Ok())); //await _signInManager.SignInAsync(user, false); //var token = new TokenDto {Token = await GetToken(user)}; //return Ok(ResponseDto<TokenDto>.Ok(token)); }