/// <summary> /// Conform email by security code /// </summary> /// <param name="email"></param> /// <param name="code"></param> /// <returns></returns> public async Task <bool> ConfirmEmailAsync(string email, string code) { string result = string.Empty; try { ConfirmEmail BE = new ConfirmEmail() { Email = email, Code = code }; var json = JsonConvert.SerializeObject(BE); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(Constants.BaseUrl + Constants.urlConfirmEmail, content); if (response.IsSuccessStatusCode) { return(true); } else { return(false); } } catch (Exception) { throw; } }
public BookingPage StepVerifyConfirmEmail(string confirmEmail) { Assert.AreEqual(ConfirmEmail.GetAttribute("value"), confirmEmail); Console.WriteLine("ConfirmEmail address is correct!"); Thread.Sleep(3000); return(this); }
public virtual async Task <IActionResult> ConfirmEmailAsync([FromBody][Required] ConfirmEmail confirmEmail, CancellationToken cancellationToken = default) { await this.IdentityManager .ConfirmEmailAsync(confirmEmail, cancellationToken); return(this.Ok()); }
public async Task <IHttpActionResult> ConfirmEmail(ConfirmEmail confirm) { if (!ModelState.IsValid) { string firstError = string.Empty; foreach (ModelState modelState in ModelState.Values) { foreach (ModelError error in modelState.Errors) { firstError = error.ErrorMessage; break; } } return(BadRequest(firstError)); } try { string code = HttpUtility.UrlDecode(confirm.Code); string userID = confirm.UserID; IdentityResult result = await this.AppUserManager.ConfirmEmailAsync(userID, code); if (!result.Succeeded) { return(GetErrorResult(result)); } } catch (Exception ex) { return(BadRequest(ex.Message)); } return(Ok()); }
/// <summary> /// Confirms the email of a user. /// </summary> /// <param name="confirmEmail">The <see cref="ConfirmEmail"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>Void.</returns> public virtual async Task ConfirmEmailAsync(ConfirmEmail confirmEmail, CancellationToken cancellationToken = default) { if (confirmEmail == null) { throw new ArgumentNullException(nameof(confirmEmail)); } var user = await this.UserManager .FindByEmailAsync(confirmEmail.EmailAddress); if (user == null) { var invalidEmail = new IdentityErrorDescriber().InvalidEmail(confirmEmail.EmailAddress); throw new TranslationException(invalidEmail.Description); } var result = await this.UserManager .ConfirmEmailAsync(user, confirmEmail.Token); if (result.Succeeded) { return; } this.ThrowIdentityExceptions(result.Errors); }
/// <summary> /// Confirms the email of a user. /// </summary> /// <param name="confirmEmail">The <see cref="ConfirmEmail"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>Void.</returns> public virtual async Task ConfirmEmailAsync(ConfirmEmail confirmEmail, CancellationToken cancellationToken = default) { if (confirmEmail == null) { throw new ArgumentNullException(nameof(confirmEmail)); } var user = await this.UserManager .FindByEmailAsync(confirmEmail.EmailAddress); if (user == null) { throw new NullReferenceException(nameof(user)); } var result = await this.UserManager .ConfirmEmailAsync(user, confirmEmail.Token); if (result.Succeeded) { return; } this.ThrowIdentityExceptions(result.Errors); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { throw new InvalidOperationException($"Specify the '{nameof(userId)}' and the '{nameof(code)}' to confirm email."); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Unable to load user with ID '{userId}'.")); } var result = await _userManager.ConfirmEmailAsync(user, code); if (!result.Succeeded) { throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':"); } var model = new ConfirmEmail(); return(View(model)); }
//public ActionResult AddAccount() //{ // var newAccount = new Friendscrip_Accounts(); // return View(newAccount); //} //[HttpPost] //public ActionResult AddAccount(Friendscrip_Accounts accountToAdd) //{ // var exists = _db.Friendscrip_Accounts.Where(x => x.ID == accountToAdd.ID).Any(); // if(!exists) // { // _db.Entry(accountToAdd).State = EntityState.Added; // } // _db.SaveChanges(); // return RedirectToAction("Index", ""); //} public JsonResult AddAccount(Friendscrip_Accounts accountInfo) { try { var existingAccount = _db.Friendscrip_Accounts.Where(x => x.ID.Equals(accountInfo.ID)).FirstOrDefault(); if (existingAccount == null) { _db.Entry(accountInfo).State = EntityState.Added; _db.SaveChanges(); ConfirmEmail emailConfirmationModel = new ConfirmEmail { Email = accountInfo.Email, ID = accountInfo.ID }; return(Json(emailConfirmationModel, JsonRequestBehavior.AllowGet)); } // SET SESSION VALUES #LITSQUADFAM Session["ID"] = accountInfo.ID; Session["Email"] = accountInfo.Email; Session["Friendscrip"] = accountInfo.Friendscrip; Session["Name"] = accountInfo.Name; return(Json("AlreadyInDB", JsonRequestBehavior.AllowGet)); } catch (Exception e) { return(Json("Failure", JsonRequestBehavior.AllowGet)); } }
public async Task <JsonResult> ConfirmEmail([FromBody] ConfirmEmail model) { try { model.Email = model.Email.ToLower(); InsertUser t; if (!temporaryUsers.TryGetValue(model.Email, out t)) { return(Json(new { Error = 1, Message = "Sorry there was a problem with the registration procedure, Please try again" }.ToJson(jsonWriterSettings))); } var users = _database.GetCollection <InsertUser>("users"); await users.InsertOneAsync(t); var body = await _renderService.RenderToStringAsync("EmailTemplates/RegistrationComplete", new RegistrationCompleteViewModel() { Name = t.FirstName }); await Task.Run(() => _emailHelper.SendEmail("The Curious Carrot - Registration Completed", "*****@*****.**", t.Email, body)); temporaryUsers.Remove(model.Email); return(Json(new { Error = 0, Result = "User correctly created" }.ToJson(jsonWriterSettings))); } catch (Exception ex) { return(Json(ex.RaiseException())); } }
private bool ValidateData() { ErrorOldEmail = string.IsNullOrEmpty(OldEmail) ? AppResources.MailRequired : string.Empty; ErrorNewEmail = string.IsNullOrEmpty(NewEmail) ? AppResources.MailRequired : string.Empty; ErrorConfirmEmail = string.IsNullOrEmpty(ConfirmEmail) ? AppResources.MailRequired : string.Empty; if (string.IsNullOrEmpty(ErrorOldEmail) && string.IsNullOrEmpty(ErrorNewEmail) && string.IsNullOrEmpty(ErrorConfirmEmail)) { ErrorOldEmail = ValidatorHelper.IsValidEmail(OldEmail) ? string.Empty : AppResources.WriteValidEmail; ErrorNewEmail = ValidatorHelper.IsValidEmail(NewEmail) ? string.Empty : AppResources.WriteValidEmail; ErrorConfirmEmail = ValidatorHelper.IsValidEmail(ConfirmEmail) ? string.Empty : AppResources.WriteValidEmail; if (string.IsNullOrEmpty(ErrorOldEmail)) { ErrorOldEmail = OldEmail.Equals(ServiceLocator.Current.GetInstance <ILoginViewModel>().User.UserName) ? string.Empty : AppResources.EmailCurrentError; } if (string.IsNullOrEmpty(ErrorNewEmail) && string.IsNullOrEmpty(ErrorConfirmEmail)) { ErrorConfirmEmail = ConfirmEmail.Equals(NewEmail) ? string.Empty : AppResources.EmailEqualError; } } else { return(false); } return(string.IsNullOrEmpty(ErrorOldEmail) && string.IsNullOrEmpty(ErrorNewEmail) && string.IsNullOrEmpty(ErrorConfirmEmail)); }
private void ConfirmEmail(string recipient, string subject, ConfirmEmail model) { var key = Guid.NewGuid(); var mail = new Mail <ConfirmEmail>("ConfirmEmail", model); mail.ViewBag.AddValue("Recipient", recipient); var sentMail = mail.Send(key, recipient, subject); }
public async Task <ConfirmEmail> ClickConfirmLinkAsync() { var goToConfirm = await Client.GetAsync(_confirmLink.Href); var confirm = await ResponseAssert.IsHtmlDocumentAsync(goToConfirm); return(await ConfirmEmail.Create(_confirmLink, Client, Context)); }
public void ConfirmEmailView_Template_NullParameter_Test() { var template = new ConfirmEmail(null); var output = template.TransformText(); Assert.NotNull(output); Assert.NotEmpty(output); }
public UserController() { userService = new UserService(); roleService = new SiteRoleService(); msgService = new MessageService(); logService = new SiteLogService(); confirmEmail = new ConfirmEmail(); errorPicService = new UserErrorPicService(); }
public void SendConfirmEmail(string emailId, Guid userId) { var confirmEmail = new ConfirmEmail { UserId = userId }; ConfirmEmail(emailId, MailResource.YourRegistration, confirmEmail); }
public void ConfirmEmailView_Template_Test() { var template = new ConfirmEmail(new SmartAppInfo { Id = ApplicationId }); var output = template.TransformText(); Assert.NotNull(output); Assert.NotEmpty(output); }
public async Task <IHttpActionResult> ConfirmEmail(ConfirmEmail info) { IdentityResult result = await UserManager.ConfirmEmailAsync(info.UserId, info.Code); if (info.UserId == 0 || info.Code == null || !result.Succeeded) { return(GetErrorResult(result)); } return(Ok()); }
public override async void HandleURIActivation(Uri uri, Dictionary <string, string> kvps) { if (!kvps.ContainsKey("code")) { Logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Error, "VerifyUserViewModel_HandleURIActivation", "Missing Code", new KeyValuePair <string, string>("queryString", uri.Query)); return; } if (!kvps.ContainsKey("userid")) { Logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Error, "VerifyUserViewModel_HandleURIActivation", "Missing User ID", new KeyValuePair <string, string>("queryString", uri.Query)); return; } var code = kvps["code"]; var userId = kvps["userid"]; if (userId != AuthManager.User.Id) { Logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Error, "VerifyUserViewModel_HandleURIActivation", "Link/User Id Mismatch", new KeyValuePair <string, string>("linkUser", userId), new KeyValuePair <string, string>("currentUser", AuthManager.User.Id)); return; } var result = await PerformNetworkOperation(async() => { var vm = new ConfirmEmail(); vm.ReceivedCode = System.Net.WebUtility.UrlDecode(code); var json = JsonConvert.SerializeObject(vm); var confirmEmailResult = await RestClient.PostAsync("/api/verify/email", vm, new CancellationTokenSource()); if (!confirmEmailResult.Successful) { return(confirmEmailResult); } var refreshResult = await RefreshUserFromServerAsync(); if (!refreshResult.Successful) { return(refreshResult); } Logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Error, "VerifyUserViewModel_HandleURIActivation", "EmailConfirmed", new KeyValuePair <string, string>("userid", userId)); await Popups.ShowAsync(ClientResources.Verify_Email_Confirmed); await RefreshUserFromServerAsync(); return(refreshResult); }); if (result.Successful) { await TransitionToNextView(); } }
internal static async Task <ConfirmEmail> ConfirmEmailAsync(IdentityEmail email, HttpClient client) { var emailBody = HtmlAssert.IsHtmlFragment(email.Body); var linkElement = HtmlAssert.HasElement("a", emailBody); var link = Assert.IsAssignableFrom <IHtmlAnchorElement>(linkElement); return(await ConfirmEmail.Create(link, client, new DefaultUIContext() .WithAuthenticatedUser() .WithExistingUser() .WithConfirmedEmail())); }
public ActionResult Confirm(string email, string ID) { ConfirmEmail emails = new ConfirmEmail { Email = email, ID = ID }; ViewBag.Message = "Confirm Page"; return(View(emails)); }
private async Task SendConfirmEmail(User user) { var confirmationCode = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var route = new ConfirmEmail { UserId = user.Id, Code = confirmationCode }; var callbackUrl = Url.Action("ConfirmEmail", "Account", route, Request.Url?.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); }
public async Task <IActionResult> Index(string token) { string baseUrl; if (Request != null) { baseUrl = Request.Host.ToString(); } else { baseUrl = "https://SudokuCollective.com"; } string emailtTemplatePath; if (!string.IsNullOrEmpty(hostEnvironment.WebRootPath)) { emailtTemplatePath = Path.Combine(hostEnvironment.WebRootPath, "/Content/EmailTemplates/confirm-new-email-inlined.html"); emailtTemplatePath = string.Format("../SudokuCollective.Api{0}", emailtTemplatePath); } else { emailtTemplatePath = "../../Content/EmailTemplates/confirm-new-email-inlined.html"; } var result = await usersService.ConfirmEmail(token, baseUrl, emailtTemplatePath); if (result.Success) { var confirmEmailModel = new ConfirmEmail { UserName = result.UserName, AppTitle = result.AppTitle, Url = result.Url, IsUpdate = result.IsUpdate != null && (bool)result.IsUpdate, NewEmailAddressConfirmed = result.NewEmailAddressConfirmed != null && (bool)result.NewEmailAddressConfirmed, Success = result.Success }; return(View(confirmEmailModel)); } else { var confirmEmailModel = new ConfirmEmail { Success = result.Success }; return(View(confirmEmailModel)); } }
public object Login() { string Email = HttpContext.Current.Request.Form["Email"]; string Password = HttpContext.Current.Request.Form["Password"]; var data = db.Users.Where(p => p.Role.Id != 1).Where(p => p.Email == Email).FirstOrDefault(); if (data == null) { return(new { Message = 1 }); } if (!DevOne.Security.Cryptography.BCrypt.BCryptHelper.CheckPassword(Password, data.Password)) { return(new { Message = 2 }); } if (data.Status == false) { return(new { Message = 3 }); } if (data.LinkStatus == false) { string key = Guid.NewGuid().ToString().Replace('-', '0').Substring(0, 4); ConfirmEmail c = new ConfirmEmail(); c.Key = key; c.User = data; db.ConfirmEmails.Add(c); SendServiceClient sms = new SmsService.SendServiceClient(); long[] recId = null; byte[] status = null; int res = sms.SendSMS("m.atrincom.com", "61758", "10009611", new string[] { data.Mobile.ToString() }, c.Key, false, ref recId, ref status); // } sms.Close(); if (res == 0) { db.SaveChanges(); } else { return new { Message = -4 } }; return(new { Message = 4 }); } return(new { Message = 0, Api_Token = data.Api_Token }); }
public RegisterController() { userService = new UserService(); confirmService = new UserConfirmService(); confirmEmail = new ConfirmEmail(); loginService = new LoginService(); appService = new UserAppService(); menuService = new UserMenuService(); inviteService = new InviteService(); HidePermission(typeof(SecurityController)); }
public Task Email(ConfirmEmail email) { return(SendEmail(email.Recepient, "Регистрация на JoinRpg.Ru", $@"Здравствуйте, и добро пожаловать на joinrpg.ru! Пожалуйста, подтвердите свой аккаунт, кликнув <a href=""{ email.CallbackUrl }"">вот по этой ссылке</a>. Это необходимо для того, чтобы мастера игр, на которые вы заявитесь, могли надежно связываться с вами. Если вдруг вам пришло такое письмо, а вы нигде не регистрировались, ничего страшного! Просто проигнорируйте его. -- {JoinRpgTeam}", _joinRpgSender)); }
public async Task <IActionResult> Get([FromQuery] ConfirmEmail query) { if (query.UId == null || query.Code == null) { return(NotFound()); } var result = await QueryAsync(query); if (!result.Succeeded) { return(NotFound()); } return(Ok()); }
public async Task ConfirmEmail_NotSuccess() { using var db = AppMocks.CreateInMemoryDB(); var registerResult = await RegisterUser(db, "name", "*****@*****.**", "password"); ConfirmEmail confirmEmail = new ConfirmEmail(db, new NullLogger <ConfirmEmail>()); var dbUserBefore = await db.Users.GetByIDAsync(registerResult.Value.Id); Assert.False(dbUserBefore.EmailConfirmed); Assert.NotNull(dbUserBefore.EmailConfirmationSecret); await confirmEmail.Handle(new ConfirmEmailRequest(registerResult.Value.Id, Guid.NewGuid())); var dbUserAfter = await db.Users.GetByIDAsync(registerResult.Value.Id); Assert.False(dbUserBefore.EmailConfirmed); Assert.NotNull(dbUserBefore.EmailConfirmationSecret); }
public HttpResponseMessage Post(RegisterViewModel model) { //nao permitir usuarios com email repetidos nao esta validando criar validaçao try { if (model == null) { return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Campos Inválidos", "text/plain")); } if (ModelState.IsValid) { var Usuario = new Usuario { Email = model.email, Nome = model.nome, Sobrenome = model.sobrenome, DataCadastro = DateTime.UtcNow, //Password = Helper.EncryptSha512(model.password), Password = Hashing.HashPassword(model.password), DataVencimentoLicenca = DateTime.UtcNow.AddMonths(3) }; _UserRepo.Add(Usuario); var ConfirmEmail = new ConfirmEmail { Usuario_Id = Usuario.Id, Token = Guid.NewGuid().ToString() }; _confirEmailRepo.Add(ConfirmEmail); var domainName = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority; var envioEmail = new EnvioEmail(_ServerConfigRepo); envioEmail.EmailCadastro(domainName, ConfirmEmail.Token, Usuario.Email); return(Request.CreateResponse(HttpStatusCode.OK, ConfirmEmail)); } var errorObj = ModelStateErrors.DisplayModelStateError(ModelState); return(Request.CreateResponse(HttpStatusCode.NotAcceptable, errorObj, "text/plain")); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public async Task ConfirmEmailAsync(ConfirmEmail model) { if (string.IsNullOrWhiteSpace(model.Email) || string.IsNullOrWhiteSpace(model.Code)) { throw new ServerException(Constants.Errors.USER_NOT_FOUND); } var user = await _userManager.FindByEmailAsync(model.Email); byte[] codeDecodeBytes = WebEncoders.Base64UrlDecode(model.Code); string codeDecoded = Encoding.UTF8.GetString(codeDecodeBytes); var result = await _userManager.ConfirmEmailAsync(user, codeDecoded); if (!result.Succeeded) { throw new ServerException(Constants.Errors.NOT_CONFIRMED_EMAIL); } await _userManager.UpdateAsync(user); }
public async Task Handle(ConfirmEmail message, IMessageHandlerContext context) { log.Info($"Received confirmation intent for user with email: {message.Email}."); Data.Confirmed = message.VerificationCode == Data.VerificationCode; if (!Data.Confirmed) { log.Info($"Email {message.Email} was attempted for verification with a wrong confirmation code."); return; } // send an internal command to persist email and password await context.Publish(new RegistrationCompleted { EmailAddress = message.Email }); MarkAsComplete(); log.Info($"Email {message.Email} verified. We've got a new user"); }