public async Task Email_ClientForceChangeEmailTest() { var testRequest = new ChangeEmailRequest("ru", "email", 1); var accountRepository = container.Resolve <IAccountRepository>(); var accountRepositoryMock = Mock.Get(accountRepository); accountRepositoryMock .Setup(s => s.FindByUserId(It.IsAny <int>())) .Returns <int>(x => Task.FromResult(new Account { Id = x })); using (var http = new HttpClient()) { var client = new Domain0Client(TEST_URL, http); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TestContainerBuilder.BuildToken(container, 1, TokenClaims.CLAIM_PERMISSIONS_FORCE_CHANGE_EMAIL)); await client.ForceChangeEmailAsync(testRequest); accountRepositoryMock.Verify(ar => ar.Update(It.Is <Account>(a => a.Id == testRequest.UserId && a.Email == testRequest.NewEmail)), Times.Once()); } }
public bool ChangeEmail(int userId, ChangeEmailRequest request) { var user = Fetch(userId); if (user == null) { return(false); } //verify its not already being used var exists = _context.Users .Where(u => u.Email == request.email) .FirstOrDefault(e => e.Id != userId); if (exists != null) { return(false); } var helper = new GravatarHelper(); user.Email = request.email; user.EmailMd5 = helper.CalculateMD5Hash(request.email); _context.Users.Update(user); _context.SaveChanges(); return(true); }
public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailRequest request) { OperationResult result = await accountService.ChangeEmail(GetCurrentUserId(), request.Email, request.Password); return(ToActionResult(result)); }
public async Task <IActionResult> ChangeEmail(ChangeEmailRequest request) { var loginSession = HttpContext.GetLoginSession(); if (request.NewEmail == null || !IsValidEmail(request.NewEmail)) { return(BadRequest()); } var existingUserOnNewEmail = await _accountLogic.GetUser(request.NewEmail); if (existingUserOnNewEmail != null) { return(BadRequest()); } var result = await _accountLogic.ChangeEmail(loginSession.Email, request.NewEmail); if (result) { return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailRequest request) { if (!ModelState.IsValid) { return(BadRequest()); } var user = await _userManager.FindByNameAsync(User.Identity.Name); if (user == null) { return(Ok()); } var result = await _userManager.ChangeEmailAsync(user, request.NewEmailAddress, request.Code); if (!result.Succeeded) { return(BadRequest()); } user.EmailConfirmed = false; await _userManager.UpdateAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); string baseURL = $"{Request.Scheme}://{Request.Host.Value}"; await _emailSender.SendConfirmationEmail(user, code, baseURL); return(await GetToken(user)); }
public async Task <IActionResult> ChangeEmail([FromQuery] ChangeEmailRequest request) { var response = await mediator.Send(request); Log.Information($"User #{HttpContext.GetCurrentUserId()} changed their email address to: {request.NewEmail}"); return(this.CreateResponse(response)); }
public async Task <IActionResult> ChangeEmail([FromQuery] ChangeEmailRequest request) { var response = await mediator.Send(request); logger.LogResponse($"User #{HttpContext.GetCurrentUserId()} changed email to: {request.NewEmail}", response.Error); return(this.CreateResponse(response)); }
public async Task <IHttpActionResult> ChangeEmailAsync([FromBody] ChangeEmailRequest request) { User user = await GetCurrentUserAsync() ?? throw new ActionForbiddenException(); await _profileService.ChangeEmailAsync(user, request.Email); await UnitOfWork.SaveChangesAsync(); return(Ok()); }
public ActionResult ChangeEmail([FromBody] ChangeEmailRequest request) { var deleted = _userService.ChangeEmail(Convert.ToInt32(User.Identity.Name), request); if (!deleted) { return(BadRequest(new { message = "Email is already in use." })); } return(Ok()); }
/// <summary> /// Change Email Async. /// </summary> /// <param name="request">The <see cref="ChangeEmailRequest{TIdentity}"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>Void.</returns> public virtual async Task ChangeEmailAsync(ChangeEmailRequest <TIdentity> request, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } request.Controller = BaseIdentityApi <TUser, TIdentity> .IdentityController; await this.InvokeAsync(request, cancellationToken); }
public ActionResult ChangeEmail(ChangeEmailRequest model) { var response = _UserService.ChangeEmail(model); if (response == null) { return(BadRequest("Something went wrong")); } return(Ok(response)); }
public async Task <IActionResult> ChangeEmailAsync([FromBody] ChangeEmailRequest changeEmailRequest) { try { if (GetCurrentUserId() != changeEmailRequest.Id) { throw new MethodAccessException(); } bool exist = await userManager.Users.AnyAsync(u => u.Email == changeEmailRequest.NewEmail); if (exist) { throw new MethodAccessException(); } var currentUser = await userManager.FindByIdAsync(changeEmailRequest.Id.ToString()) ?? throw new ArgumentNullException(); if (currentUser.Email != changeEmailRequest.OldEmail) { throw new ArgumentException(); } string emailConfirmationToken = await userManager.GenerateChangeEmailTokenAsync(currentUser, changeEmailRequest.NewEmail); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = changeEmailRequest.Id, token = emailConfirmationToken, newEmail = changeEmailRequest.NewEmail }, protocol: "https"); await emailSender.SendEmailConfirmationAsync(changeEmailRequest.NewEmail, callbackUrl); return(Ok()); } catch (ArgumentNullException ane) { logger.LogDebug(ane.Message + "\n" + ane.StackTrace); return(NotFound($"Can't find current user")); } catch (ArgumentException ae) { logger.LogDebug(ae.Message + "\n" + ae.StackTrace); return(BadRequest("Old email isn't match current user's email")); } catch (MethodAccessException mae) { logger.LogDebug(mae.Message + "\n" + mae.StackTrace); logger.LogDebug($"User {GetCurrentUserId()} can't change {changeEmailRequest.Id} email to {changeEmailRequest.NewEmail}"); return(Forbid(JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme)); } }
public async Task <ServiceResponseResult> UpdateAdminProfile(AdminProfileUpdateReqModel model, long userId, long locationId) { Logger.WriteInformation("Updating admin profile data."); var user = await _context.User.FirstOrDefaultAsync(x => x.Id == userId); var token = Guid.NewGuid().ToString(); var now = DateTime.UtcNow; if (!string.IsNullOrEmpty(model.Email)) { if (await _context.User.AnyAsync(x => x.Email == model.Email.ToLower()) || await _context.ChangeEmailRequest.AnyAsync(x => x.Email == model.Email.ToLower())) { return(new ServiceResponseResult { StatusCode = System.Net.HttpStatusCode.BadRequest, Result = new { Message = "An user with the email already exists." }, }); } var emailChange = new ChangeEmailRequest { Email = model.Email, RequestedOn = DateTime.UtcNow, UserId = userId, VerificationToken = token, VerificationTokenExpiry = now.AddHours(24) }; _context.ChangeEmailRequest.Add(emailChange); var emailData = await _emailService.ConstructEmailVerification(user.VerificationToken); await _emailSender.SendMailViaSmtpClientAsync(new string[] { model.Email }, new string[] { }, new string[] { }, emailData); } if (!string.IsNullOrEmpty(model.Name)) { user = user.UpdateName(model.Name); } user = user.UpdateVerificationToken(token) .UpdateVerificationTokenExpiry(now.AddHours(24)) .UpdateLastUpdatedOn(DateTime.UtcNow) .UpdateLastUpdatedBy(userId); _context.User.Update(user); await _context.SaveChangesAsync(); Logger.WriteInformation("Updating admin profile data completed."); return(await GetAdminProfile(locationId, userId)); }
public ActionResult <ResponseModel <string> > ChangeEmail([FromHeader] string Authorization , ChangeEmailRequest request) { string token = Authorization.Split()[1]; bool result = _userService.ChangeEmail(token, request.Password, request.NewEmail); if (result) { return(new ResponseModel <string>(null)); } return(new ResponseModel <string>(null, false, new [] { "Wrong password" })); }
public string ChangeEmail(ChangeEmailRequest model) { var user = _Users.Find(x => x.Id == model.id).SingleOrDefault(); if (user == null) { return(null); } user.email = model.email; _Users.ReplaceOne(sub => sub.Id == model.id, user); return(generateJwtToken(user)); }
public async Task <IActionResult> ConfirmChangeEmail([FromQuery] ChangeEmailRequest request, CancellationToken cancellationToken) { var result = await _identityService.ConfirmChangeEmail(new ConfirmChangeEmail.Request { UserId = request.UserId, Token = request.Token, NewEmail = request.NewEmail }, cancellationToken); if (!result.isSuccess) { return(BadRequest("Токен или маил не верные")); } return(Ok($"Почта изменена на {request.NewEmail}")); }
public async Task <IdentityResult> ChangeEmail(ChangeEmailRequest request) { var user = await Find(request); if (user != null) { var oldEmail = user.Email; var token = await _userManager.GenerateChangeEmailTokenAsync(user, request.NewEmail); var result = await _userManager.ChangeEmailAsync(user, request.NewEmail, token); if (result.Succeeded) { _notifier.SendNotificationAsync(user, new ChangeEmailNotification(oldEmail, request.NewEmail)); } return(result); } return(NoSuchUserResult()); }
public async Task <IActionResult> ChangeEmailAddress(ChangeEmailRequest request) { var accessToken = HttpContext.Request.Headers["Authorization"].ToString(); if (accessToken == null) { return(NotFound("Something is wrong with your authorization token")); } if (request == null) { return(BadRequest("You must fill in all the fields")); } var changeEmail = await _identityService.ChangeEmailAddress(request.NewEmail, request.Password, request.Token, accessToken); if (changeEmail.Success) { return(Ok(new SimpleSuccessResponse { Success = true, Message = "Your email has been changed" })); } else { if (changeEmail.Errors.Count() > 1) { return(BadRequest(new AuthenticationFailedResponse { Errors = changeEmail.Errors })); } else { return(BadRequest(changeEmail.Errors.ToList()[0])); } } }
public void UpdateEmail() { if (Panel != null) { bool isActive = Panel.activeSelf; Panel.SetActive(!isActive); } var newEmail = newEmailInput.GetComponent <InputField>().text; ChangeEmailRequest req = new ChangeEmailRequest("changeEmail", Global.getID(), Global.getToken(), newEmail); string json = JsonConvert.SerializeObject(req); Byte[] data = System.Text.Encoding.ASCII.GetBytes(json); Global.stream.Write(data, 0, data.Length); data = new Byte[256]; string responseData = string.Empty; Int32 bytes = Global.stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); }
private async Task ForceChangeEmail() { var changeData = await _shell.ShowForceChangeDialog( EditViewModel.Email, "Email", Locales.FirstOrDefault(), Locales.ToList()); if (changeData != null) { try { var request = new ChangeEmailRequest(changeData.Locale, changeData.Input, EditViewModel.Id.Value); await _domain0.Client.ForceChangeEmailAsync(request); EditViewModel.Email = changeData.Input; Models.AddOrUpdate(EditModel); } catch (Exception e) { await _shell.HandleException(e, "Failed to Change Email"); } } }
public async Task <IActionResult> ChangeEmailAsync([FromBody] ChangeEmailRequest request) { await _authenticationService.ChangeEmailAsync(User.Identity.Name, request.Email); return(Ok(new EmptyResponse())); }
/// <summary> /// SSO platforms use this call to update a user’s email address at WePay. /// WePay assumes any new email address is verified. /// Note that WePay is unable to update user email addresses via API for non-SSO users at this time. /// As this is a high-security operation, WePay expects MFA to be checked before making this API call. /// If your platform is using WePay’s MFA service, the trust cookie must be sent. /// PERMISSION REQUIRED /// </summary> /// <param name="changeEmailRequest"></param> /// <param name="accessToken"></param> /// <param name="useStaging"></param> /// <returns></returns> public async Task <LookupResponse> ChangeEmailAsync(ChangeEmailRequest changeEmailRequest, string accessToken = null, bool?useStaging = null) { return(await PostRequestAsync(changeEmailRequest, EndPointUrls.ChangeEmail, accessToken, useStaging)); }
public static ChangeEmailRequest UpdateVerificationToken(this ChangeEmailRequest changeEmailRequest, string verificationToken) { changeEmailRequest.VerificationToken = verificationToken; return(changeEmailRequest); }
public async Task <IActionResult> ChangeEmail([FromBody] ChangeEmailRequest request) { var result = await _service.ChangeEmail(request); return(GetResult(result, 204)); }
public static ChangeEmailRequest UpdateVerificationTokenExpiry(this ChangeEmailRequest changeEmailRequest, DateTime?verificationTokenExpiry) { changeEmailRequest.VerificationTokenExpiry = verificationTokenExpiry; return(changeEmailRequest); }
public async Task <UserProfileDto?> UpdateUserAccountAsync( int locationId, IEnumerable <Claim> claims, UpdateNameEmailDto update) { var user_id = claims?.FirstOrDefault(x => x.Type == "ID"); int id; if (!int.TryParse(user_id?.Value, out id)) { return(null); } var user = await _context.Users .Include(x => x.UserKeyMappings) .ThenInclude(x => x.Keyholder) .Include(x => x.ChangeEmailRequests) .Include(x => x.UserLocations) .FirstOrDefaultAsync(x => x.UserID == id); var keyholdemap = user?.UserKeyMappings?.FirstOrDefault(x => x.LocationId == locationId); if (keyholdemap == null) { return(null); } ; if (update.name != null) { user.Name = update.name; } Task save; if (update.email != null) { var email = EmailOperations.sendVerificationEmail( user.Name, update.email, user.VerificationToken, true); user.Email = update.email; user.VerificationToken = Authentication.generateEmailTokenHash(); user.VerificationTokenExpiry = DateTime.UtcNow.AddDays(1); var changeRequest = new ChangeEmailRequest() { User = user, RequestedOn = DateTime.UtcNow, Email = update.email, VerificationToken = user.VerificationToken, VerificationTokenExpiry = user.VerificationTokenExpiry, }; await _context.EmailChangeRequests.AddAsync(changeRequest); _context.Users.Update(user); await email; save = _context.SaveChangesAsync(); } else { _context.Users.Update(user); save = _context.SaveChangesAsync(); } var model = _mapper.Map <UserProfileDto>(user); model.locationId = locationId; var tookit = _mapper.Map <ToolkitInfoDto>(keyholdemap.Keyholder); model.toolkitInfo = tookit; await save; return(model); }
public async Task <ServiceResponseResult> UpdatedAdmin(long locationId, long userId, long adminUserId, AdministratorUpdateReqModel model) { Logger.WriteInformation("Getiing admin activity data."); var userLoc = await _context.UserLocation.FirstOrDefaultAsync(x => x.UserId == adminUserId && x.LocationId == locationId); if (userLoc == null) { return(new ServiceResponseResult { Result = new { Message = $"User does not exists in this location {locationId}" }, StatusCode = System.Net.HttpStatusCode.NotFound }); } var user = await _context.User.FindAsync(adminUserId); if (!string.IsNullOrEmpty(model.Email) && model.Email != user.Email) { var doesEmailExists = await _context.ChangeEmailRequest.AnyAsync(x => x.Email == model.Email.ToLower()) || await _context.User.AnyAsync(x => x.Email == model.Email.ToLower()); if (doesEmailExists) { return(new ServiceResponseResult { Result = new { Message = $"Could not update the email as it is already exists" }, StatusCode = System.Net.HttpStatusCode.BadRequest }); } var emailChange = new ChangeEmailRequest { Email = model.Email, RequestedOn = DateTime.UtcNow, UserId = adminUserId, VerificationToken = Guid.NewGuid().ToString(), VerificationTokenExpiry = DateTime.UtcNow.AddHours(24) }; _context.ChangeEmailRequest.Add(emailChange); var emailData = await _emailService.ConstructEmailVerification(emailChange.VerificationToken); await _emailSender.SendMailViaSmtpClientAsync(new string[] { emailChange.Email }, new string[] { }, new string[] { }, emailData); } if (!string.IsNullOrEmpty(model.Name)) { user = user.UpdateName(model.Name).UpdateLastUpdatedBy(userId) .UpdateLastUpdatedOn(DateTime.UtcNow); } _context.Update <User>(user); if (model.State.HasValue) { if (model.State.Value == AdministratorState.Disabled && string.IsNullOrEmpty(model.DisabledReason)) { return(new ServiceResponseResult { Result = new { Message = $"DisabledReason is required for disable state." }, StatusCode = System.Net.HttpStatusCode.BadRequest }); } userLoc.State = (int)model.State.Value; userLoc.LastUpdatedBy = userId; userLoc.LastUpdatedOn = DateTime.UtcNow; _context.Update(userLoc); } var response = new AdministratorResult(user, userLoc); if (model.Status != null) { var status = await _context.UserStatus.FirstOrDefaultAsync(x => x.Id == model.Status.Id && x.LocationId == locationId); if (status != null) { userLoc.StatusId = status.Id; userLoc.LastUpdatedBy = userId; userLoc.LastUpdatedOn = DateTime.UtcNow; _context.Update(userLoc); response.AddStatus(status); } } var userPermission = await _context.UserPermission.FirstOrDefaultAsync(x => x.UserLocationId == userLoc.Id); if (userPermission == null) { userPermission = UserPermissionMapper.ToUserPermission(model.Permissions) .UpdateLastUpdatedOn(DateTime.UtcNow) .UpdateUserLocationId(userLoc.Id); _context.Add <UserPermission>(userPermission); } else { userPermission = UserPermissionMapper.ToUserPermission(model.Permissions); userPermission = userPermission.UpdateLastUpdatedBy(userId) .UpdateId(userPermission.Id) .UpdateLastUpdatedOn(DateTime.UtcNow) .UpdateUserLocationId(userLoc.Id); _context.Update <UserPermission>(userPermission); } response.AddPermission(userPermission); var key = await _context.KeyHolder.FirstOrDefaultAsync(x => x.KeySerialNumber == model.KeySerialNumber); var userKeyMapping = await _context.UserKeyMapping .FirstOrDefaultAsync(x => x.UserId == adminUserId && x.LocationId == locationId && x.KeySerialNumber == model.KeySerialNumber); if (key != null) { if (userKeyMapping == null) { userKeyMapping = new UserKeyMapping { AppliedOn = DateTime.UtcNow, KeySerialNumber = key.KeySerialNumber, LocationId = locationId, UserId = user.Id }; userLoc.UpdateIsToolKitEnabled(true); _context.Update(userLoc); _context.Add <UserKeyMapping>(userKeyMapping); } response.AddToolkit(key); } await _context.SaveChangesAsync(); Logger.WriteInformation("Updating admin activity data completed."); return(new ServiceResponseResult { StatusCode = System.Net.HttpStatusCode.OK, Result = response }); }