private async Task SendConfirmEmailAsync(string customerName, string customerEmail , string confirmLink, string companyContactLink, string companyName, string companyEmail) { ConfirmEmailViewModel model = new ConfirmEmailViewModel(); model.CustomerName = customerName; model.ConfirmLink = confirmLink; model.CompanyContactLink = companyContactLink; model.CompanyName = companyName; var htmlContent = await base._viewRenderer.RenderViewToString("Views/Identity/ConfirmEmail.cshtml", model); var plainTextContent = base._plainTextContentRenderer.RenderModelToString(new { Memsagem = $"Olá {customerName}! Criamos uma conta para você. Confirme o seu email e escolha uma nova senha", Link = confirmLink }); var emailDetail = new EmailDetail() { ToEmail = customerEmail, ToName = customerName, Subject = "Confirme seu email", PlainTextContent = plainTextContent, HtmlContent = htmlContent, FromEmail = companyEmail, FromName = companyName, }; await this._emailService.SendEmail(emailDetail); }
public async Task <IActionResult> ConfirmInvitedUserByEmail(Guid?userId, string confirmToken) { if (!userId.HasValue || string.IsNullOrEmpty(confirmToken)) { return(NotFound()); } if (!_httpContextAccessor.HttpContext.User.IsAuthenticated()) { await _httpContextAccessor.HttpContext.SignOutAsync(); } var currentUser = await _userManager.UserManager.Users.FirstOrDefaultAsync(x => x.Id.Equals(userId)); if (currentUser == null) { return(NotFound()); } var model = new ConfirmEmailViewModel { UserId = currentUser.Id, UserName = currentUser.UserName, Email = currentUser.Email, Token = confirmToken }; return(View(model)); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(this.RedirectToPage("/Index")); } var user = await this._userService.GetByIdAsync(userId); if (user == null) { return(this.NotFound($"Unable to load user with ID '{userId}'.")); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await this._userService.ConfirmEmailAsync(userId, code); var viewModel = new ConfirmEmailViewModel { StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.", Succeeded = result.Succeeded, }; return(this.View(viewModel)); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(Redirect("~/")); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Unable to load user with ID '{userId}'.")); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ConfirmEmailAsync(user, code); var vm = new ConfirmEmailViewModel { StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email." }; return(View(vm)); }
public async Task <ActionResult> SendEmailConfirmationCode(ConfirmEmailViewModel confirmEmailViewModel) { if (!ModelState.IsValid) { return(View()); } List <Claim> claims = new List <Claim>() { new Claim(WellKnown.ConfirmEmailViewModelClaim, JsonConvert.SerializeObject(confirmEmailViewModel)) }; var now = DateTime.UtcNow; var lifetime = new Lifetime(now, now.AddMinutes(30)); var jwt = IdentityTokenHelper.BuildJWT(claims, WellKnown.ValidIssuer, WellKnown.EmailConfirmationAudience, lifetime); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = confirmEmailViewModel.UserId, code = jwt }, protocol: Request.Url.Scheme); await UserManager.EmailService.SendAsync(new IdentityMessage() { Destination = confirmEmailViewModel.Email, Subject = "Confirm your account!", Body = "You have 30 minutes to confirm your account by clicking here: " + callbackUrl }); // Generate the token and send it return(RedirectToAction("EmailConfirmationSent", "Account", new { email = confirmEmailViewModel.Email })); }
public async Task <ApiResponse> ConfirmEmail(ConfirmEmailViewModel parameters) { if (parameters.UserId == null || parameters.Token == null) { return(new ApiResponse(Status404NotFound, L["The user doesn't exist"])); } var user = await _userManager.FindByIdAsync(parameters.UserId); if (user == null) { _logger.LogInformation(L["The user {0} doesn't exist", parameters.UserId]); return(new ApiResponse(Status404NotFound, L["The user doesn't exist"])); } var token = parameters.Token; var result = await _userManager.ConfirmEmailAsync(user, token); if (!result.Succeeded) { var msg = string.Join(",", result.Errors.Select(i => i.Description)); _logger.LogWarning("User Email Confirmation Failed: {0}", msg); return(new ApiResponse(Status400BadRequest, msg)); } await _signInManager.SignInAsync(user, true); return(new ApiResponse(Status200OK, L["EmailVerificationSuccessful"])); }
public async Task <IActionResult> ConfirmEmail(string area, string userId, string code) { if (userId == null || code == null) { return(RedirectToAction("Index", "Home")); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Không tồn tại User - '{userId}'.")); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); // Xác thực email var result = await _userManager.ConfirmEmailAsync(user, code); var model = new ConfirmEmailViewModel(); if (result.Succeeded) { // Đăng nhập luôn nếu xác thực email thành công await _signManager.SignInAsync(user, false); return(RedirectToAction("Index", "Home")); } else { model.StatusMessage = "Lỗi xác nhận email"; } return(View(model)); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailViewModel confirmEmailViewModel) { return(await Validation_UserExistance_ModelState(confirmEmailViewModel.Email, ModelState, async (user) => { var tokenState = userBehaviour.VerifyCustomToken(confirmEmailViewModel.Token, user.Id, TokenType.Confirmation); switch (tokenState) { case CustomTokenState.Valid: var token = await userManager.GenerateEmailConfirmationTokenAsync(user); var result = await userManager.ConfirmEmailAsync(user, token); var authTokens = GetAuthTokens(user); if (result.Succeeded) { return Ok(authTokens); } return ConflictInternalErrors(result); case CustomTokenState.Invalid: return Conflict("Incorrect token."); case CustomTokenState.Expired: return Conflict("Expired token."); case CustomTokenState.SelfDestruct: return Conflict("Destroyed token."); case CustomTokenState.NotCreated: return Conflict("No token."); default: return Conflict(); } })); }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailViewModel model) { if (model.UserId == null || model.Code == null) { return(BadRequest(Errors.AddErrorToModelState("NoUserIdOrCode", "NoUserIdOrCode", ModelState))); } var user = await _userManager.FindByIdAsync(model.UserId); if (user == null) { return(BadRequest(Errors.AddErrorToModelState("UserNotFound", "UserNotFound", ModelState))); } var decodedCode = model.Code.Replace(" ", "+"); var result = await _userManager.ConfirmEmailAsync(user, decodedCode); try { if (result.Succeeded) { return(new OkObjectResult("")); } else { return(BadRequest(result.Errors)); } } catch (Exception ex) { return(Content(ex.Message)); } }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel confirmEmail) { if (!ModelState.IsValid) { NotifyModelStateErrors(); return(ResponseBadRequest()); } var user = await _accessManager.GetUserByUsername(confirmEmail.Username); if (user == null) { NotifyError("user", $"Username is incorrect."); return(ResponseBadRequest()); } var result = await _accessManager.ConfirmEmailToken(user, confirmEmail.Code); if (result.Succeeded) { return(Response($"Email successfully confirmed")); } await AddIdentityErrors(result); return(ResponseBadRequest()); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel model) { if (ModelState.IsValid) { await SignInManager.SignOutAsync(); var user = AuthContext.Users.SingleOrDefault(w => w.UserName == model.NickName); if (user == null) { ModelState.AddModelError(string.Empty, $"User [{ model.NickName }] not found!"); return(View(model)); } var result = await UserManager.ConfirmEmailAsync(user, model.ConfirmationToken); if (result.Succeeded) { model.Confirmed = true; model.FirstName = user.FirstName; } Logger.LogVerbose("Confirmation errors."); foreach (var e in result.Errors) { ModelState.AddModelError(string.Empty, e.Description); } } return(View(model)); }
public async Task <ActionResult> ConfirmEmail(ConfirmEmailViewModel model) { if (ModelState.IsValid) { const String URI_ADDRESS = "api/Account/ConfirmEmail"; try { var client = GlobalWebApiClient.GetClient(); var dataJson = JsonConvert.SerializeObject(model); var content = new StringContent(dataJson, Encoding.UTF8, "application/json"); var response = await client.PostAsync(URI_ADDRESS, content); if (response.IsSuccessStatusCode) { var confirmEmailResponse = await response.Content.ReadAsAsync <ConfirmEmailViewModel>(); return(RedirectToAction("Login", "Accounts")); } } catch (Exception) { throw; } } return(View(model)); }
public async Task <ApiResponseDto> ConfirmEmail(ConfirmEmailViewModel parameters) { ApiResponseDto apiResponse = await _authorizeApi.ConfirmEmail(parameters); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); return(apiResponse); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel model) { if (ModelState.IsValid) { var result = await _platoUserManager.GetEmailConfirmationUserAsync(model.UserIdentifier); if (result.Succeeded) { var user = result.Response; if (user != null) { user.ConfirmationToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(user.ConfirmationToken)); var emailResult = await _userEmails.SendEmailConfirmationTokenAsync(user); if (!emailResult.Succeeded) { foreach (var error in emailResult.Errors) { ViewData.ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); } } } } return(RedirectToAction(nameof(ConfirmEmailConfirmation))); }
public async Task <IActionResult> confirmEmail([FromBody] ConfirmEmailViewModel model) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByIdAsync(model.userid); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{model.userid}'."); } var result = await _userManager.ConfirmEmailAsync(user, model.code); if (result.Succeeded) { return(Ok("account registration success")); } else { return(BadRequest("confirm email error")); } } catch (Exception e) { return(BadRequest(e)); } }
async public Task <IActionResult> Register(RegisterViewModel model) { string error = ""; var result = await _userManager.CreateAsync(new ApplicationUser { Email = model.Email, EmailConfirmed = false, UserName = model.Login, FirstName = model.FirstName, LastName = model.LastName, }, model.Password); if (!result.Succeeded) { error = String.Join("\r\n", result.Errors.Select(s => s.Description).ToArray()); } else { var user = await _userManager.FindByNameAsync(model.Login); if (user != null) { int countAddInfo = (await _roleManager.FindByNameAsync("default")).MoreInfoCount; user.MoreInfoCount = countAddInfo; _db.SaveChanges(); var res = await _userManager.AddToRoleAsync(user, "default"); if (!res.Succeeded) { error = String.Join("\r\n", result.Errors.Select(s => s.Description).ToArray()); } else { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); var emailModel = new ConfirmEmailViewModel { ConfirmLink = callbackUrl, FirstName = user.FirstName, LastName = user.LastName }; var htmlEmailText = await _viewRenderService.RenderToStringAsync("Emails/ConfirmationEmailTemplate", emailModel); await _emailSender.SendEmailConfirmationAsync(model.Email, "Confirm your email", htmlEmailText); } } else { error = "Can not find user: " + model.Login; } } return(Json(new { error = error })); }
private async Task <string> GetPasswordResetEmailMessageHtml(ClassicGuildBankUser user, string code) { var url = $"{ _configuration.GetSection("ClientUrl").Value}/user/reset"; var model = new ConfirmEmailViewModel() { Username = user.UserName, Code = code, CallbackUrl = url }; return(await _razorService.RenderView("ResetPasswordEmailView", model)); }
private async Task <ConfirmEmailViewModel> BuildConfirmationEmailViewModel(string ReturnUrl, string userEmail) { var vm = new ConfirmEmailViewModel() { ReturnUrl = ReturnUrl, Email = userEmail }; return(vm); }
public async Task <ActionResult <DefaultResponse <bool> > > ConfirmEmail([FromBody] ConfirmEmailViewModel model) { if (!ModelState.IsValid) { NotifyModelStateErrors(); return(Response(false)); } await _userAppService.ConfirmEmail(model); return(Response(true)); }
public IActionResult ConfirmEmail() { ConfirmEmailViewModel model = new ConfirmEmailViewModel() { CustomerName = "CustomerName", ConfirmLink = "ConfirmLink.com", CompanyContactLink = "CompanyContactLink.", CompanyName = "CompanyName" }; return(View(model)); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel model) { var user = await _userManager.FindByIdAsync(model.UserId); var result = await _userManager.ConfirmEmailAsync(user, model.Token); if (result.Succeeded) { return(Ok()); } return(BadRequest()); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel confirmEmailViewModel) { try { var ExistingUserName = _userService.GetUserByUserName(confirmEmailViewModel.Email); if (confirmEmailViewModel.Password != confirmEmailViewModel.ConfirmPassword) { return(BadRequest("Email is not confirmed")); } else if (ExistingUserName != null) { return(BadRequest("UserName already exists")); } else { try { User user = new User(); user.Id = Guid.NewGuid(); user.Email = confirmEmailViewModel.Email; user.UserName = confirmEmailViewModel.Email; user.NormalizedUserName = confirmEmailViewModel.Email; user.NormalizedEmail = confirmEmailViewModel.Email; user.EmailConfirmed = true; user.PasswordHash = _passwordService.Hash(confirmEmailViewModel.Password); user.PhoneNumberConfirmed = false; user.TwoFactorEnabled = false; user.LockoutEnabled = false; user.AccessFailedCount = 0; user.CreationDate = DateTime.Now; var NewUserId = await _userService.InsertUser(user); var invite = _inviteservice.GetInviteByEmailId(confirmEmailViewModel.Email); UserRole userRole = new UserRole(); userRole.RoleId = invite.RoleId; userRole.UserId = NewUserId; //await _userRolesService.InsertRoleUser(userRole); var invitedelete = _inviteservice.DeleteInvite(invite.Id); return(Ok(user)); } catch (Exception ex) { return(BadRequest(ex.Message)); } } } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public PartialViewResult ConfirmEmailPartial() { var currentUserId = User.Identity.GetUserId(); var isConfirmed = UserManager.IsEmailConfirmed(currentUserId); var email = UserManager.GetEmail(currentUserId); ConfirmEmailViewModel model = new ConfirmEmailViewModel() { IsConfirmed = isConfirmed, Email = email }; return(PartialView("_ConfirmEmail", model)); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel model) { var employer = await _userManager.FindByIdAsync(model.UserId); var confirm = await _userManager.ConfirmEmailAsync(employer, Uri.UnescapeDataString(model.Token)); if (confirm.Succeeded) { return(Ok()); } return(Unauthorized()); }
public async Task <ActionResult> ConfirmEmail(string username, [FromBody] ConfirmEmailViewModel model) { if (!ModelState.IsValid) { NotifyModelStateErrors(); return(ModelStateErrorResponseError()); } model.Email = username; await _userAppService.ConfirmEmail(model); return(Ok()); }
public async Task <IActionResult> ConfirmEmail(ConfirmEmailViewModel _model) { try { var user = await _userManager.FindByEmailAsync(_model.Email); if (user != null) { bool result = _userService.ConfirmEmail(_model.Email, _model.Code).Result; var userstatus = user.UserStatus; if (result) { var webRoot = _hostingEnvironment.WebRootPath; //Get TemplateFile located at wwwroot/Templates/EmailTemplates/Confirm_Account_Registration_Success.html var pathToFile = _hostingEnvironment.WebRootPath + Path.DirectorySeparatorChar.ToString() + Constants.mainTemplatesContainer + Path.DirectorySeparatorChar.ToString() + Constants.emailTemplatesContainer + Path.DirectorySeparatorChar.ToString() + Constants.email_template_Confirm_Account_Registration_Success; var subject = Constants.subject_Confirm_Account_Registration_Success; var name = user.Name; var body = new BodyBuilder(); using (StreamReader reader = System.IO.File.OpenText(pathToFile)) { body.HtmlBody = reader.ReadToEnd(); } string messageBody = body.HtmlBody; messageBody = messageBody.Replace("{name}", name); messageBody = messageBody.Replace("{subject}", subject); await _emailSender.SendEmailAsync(email : user.Email, subject : subject, htmlMessage : messageBody); return(Ok(new { status = StatusCodes.Status200OK, success = true, message = ResponseMessages.msgEmailConfirmationSuccess, userstatus })); } else { return(Ok(new { status = StatusCodes.Status400BadRequest, success = false, message = ResponseMessages.msgInvalidOTP, userstatus })); } } else { return(Ok(new { status = StatusCodes.Status404NotFound, success = false, message = ResponseMessages.msgCouldNotFoundAssociatedUser, userstatus = false })); } } catch (Exception ex) { return(Ok(new { status = StatusCodes.Status500InternalServerError, success = false, message = ResponseMessages.msgSomethingWentWrong + ex.Message, userstatus = false })); } }
public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(model.UserId); if (user == null) { return(Ok()); } if (user.Email != model.Email) { return(Ok()); } var result = await _userManager.ConfirmEmailAsync(user, model.Code.Replace(" ", "+")); if (result.Succeeded) { var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); if (signInResult.IsNotAllowed) { return(Ok(new { error = "Account Requires Email Confirmation", error_description = "You must verify your email address using the confirmation email link before logging in." })); } if (signInResult.Succeeded) { if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail)) { user.Email = user.UnConfirmedEmail; user.UserName = user.UnConfirmedEmail; user.UnConfirmedEmail = ""; await _userManager.UpdateAsync(user); } _logger.LogInformation("User confirmed email successfully."); _userContext.SetUserGuidCookies(user.UserGuid); return(Ok(new { token = await _userContext.GenerateToken(user) })); } if (signInResult.IsLockedOut) { return(Ok(new { error = "Account Locked", error_description = "User account locked out. Please wait 5 minutes before trying to login again." })); } } } return(BadRequest()); }
//GET: /Account/ConfirmEmail public ActionResult ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return(View("Error")); } var confirmEmail = new ConfirmEmailViewModel() { UserId = userId, Code = code }; return(View()); }
private ConfirmEmailViewModel GetConfirmEmailViewModel() { const string title = "Confirm Email"; const string returnUrl = ""; const string mvcActionName = "ConfirmEmail"; var applicationName = MvcApplication.ApplicationName; var applicationVersion = MvcApplication.ApplicationVersion; var area = GetAreaName(); var vm = new ConfirmEmailViewModel(applicationName, applicationVersion, mvcActionName, title, area, () => GetMainMenus(area)) { ReturnUrl = returnUrl }; return(vm); }
public async Task <IActionResult> Change(string userId, string email, string code) { if (userId == null || email == null || code == null) { return(Redirect(_plumPackOptions.MainSiteUrl)); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return(NotFound($"Unable to load user with ID '{userId}'.")); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ChangeEmailAsync(user, email, code); var message = result.Succeeded ? "Thank you for confirming your email change." : "Error changing email."; // Check to see if the logged in user is the user we confirmed the email for. // If so, redirect to the email page, showing a notification. if (User.IsAuthenticated()) { var loggedInUser = await _userManager.GetUserAsync(User); if (loggedInUser.Id == user.Id) { // Same user. if (result.Succeeded) { AddSuccessMessage(message, true); } else { AddFailureMessage(message, true); } return(RedirectToAction("Index", "Email", new { area = "Manage" })); } } var vm = new ConfirmEmailViewModel(); vm.Status = result.Succeeded; vm.StatusMessage = message; return(View(vm)); }