Esempio n. 1
0
        public async Task <ActionResult> Login(UserLoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await _userManager.FindAsync(model.Email, model.Password);

                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid name or password");
                }
                else
                {
                    if (!await _userManager.IsEmailConfirmedAsync(user.Id))
                    {
                        string code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        string callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        _mailingRepository.ActivationMail(user.Email, callbackUrl);
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        return(PartialView("_Error", new string[] { "You must have a confirmed email to log on. Check your email for activation link." }));
                    }

                    ClaimsIdentity ident = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    _authManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    _authManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = false,
                    }, ident);
                    return(Json(new { url = "/" }));
                }
            }
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(PartialView(model));
        }
Esempio n. 2
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                    // 发送包含此链接的电子邮件
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, "确认你的帐户", "请通过单击 <a href=\"" + callbackUrl + "\">这里</a>来确认你的帐户");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
        public async Task <ActionResult> Create(CreateModel model)
        {
            var identiyUser = await _userManager.FindByNameAsync(model.UserName);

            if (identiyUser != null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var user = new ExtendedUser
            {
                UserName = model.UserName,
                FullName = model.FullName
            };

            var result = await _userManager.CreateAsync(user, model.Password);

            //Genrate Token
            var token      = _userManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var confirmUrl = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = token }, Request.Url.Scheme);

            await _userManager.SendEmailAsync(user.Id, "Email Confirmation", $"Use link to confirm email:{confirmUrl}");

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            ModelState.AddModelError("", result.Errors.FirstOrDefault());
            return(View(model));
        }
Esempio n. 4
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Verification email sent. Please check your email.");
            }

            var userId = await _userManager.GetUserIdAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: Request.Scheme);
            await _emailSender.SendEmailAsync(
                Input.Email,
                "Confirm your email",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            ModelState.AddModelError(string.Empty, "Verification email sent. Please check your email.");
            return(Page());
        }
Esempio n. 5
0
        public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser()
            {
                UserName  = createUserModel.Username,
                Email     = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                LastName  = createUserModel.LastName,
                Level     = 3,
                JoinDate  = DateTime.Now.Date,
            };

            var addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            var code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code }));

            await AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
Esempio n. 6
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }


            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: Request.Scheme);
            await _emailSender.SendEmailAsync(
                email,
                "Confirm your email",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            StatusMessage = "Verification email sent. Please check your email.";
            return(RedirectToPage());
        }
        public async Task <ActionResult> VerifyEmailRequest()
        {
            var userId = User.Id;

            //
            if (await _appUserManager.IsEmailConfirmedAsync(userId))
            {
                return(RedirectToAction(nameof(VerifyEmail), new { status = AccountActionStatus.VerifyEmailResponseSuccess.ToLowerCaseString() }));
            }

            //
            var adminUser = await _appUserManager.FindByIdAsync(userId);

            var mailModel = new AccountVerifyEmailMessageViewModel()
            {
                Name             = adminUser.FullName ?? adminUser.UserName,
                PageTitle        = GetLocalizedString <AreaResources>("VerifyEmail"),
                ConfirmationLink = Url.Action("VerifyEmailResponse", "Account", new
                {
                    verifyToken = await _appUserManager.GenerateEmailConfirmationTokenAsync(adminUser.Id)
                }, protocol: Request.Url.Scheme)
            };

            var subject = $"[{GetLocalizedString("AppName")}] {mailModel.PageTitle}";
            var message = RenderViewToString("VerifyEmailMessage", model: mailModel);

            _emailDispatcherService.Dispatch(message, subject, new MailAddress(adminUser.Email, adminUser.FullName));

            return(RedirectToAction(nameof(VerifyEmail), new { status = AccountActionStatus.VerifyEmailRequestSent.ToLowerCaseString() }));
        }
Esempio n. 8
0
        //[HttpPost("sign-up", Name = "PostRegister")]
        public async Task <IActionResult> Register(RegisterAccount account, string returnTo)
        {
            if (ModelState.IsValid)
            {
                User user = new User()
                {
                    UserName      = account.UserName,
                    Email         = account.Email,
                    FirstName     = account.FirstName,
                    LastName      = account.LastName,
                    RegisteredOn  = account.RegisteredOn,
                    PhotoFileName = "user_avatar.png",
                    GeneratedKey  = Guid.NewGuid().ToString("N"),
                    PhoneNumber   = account.PhoneNumberUser
                };

                var result = await _userManager.CreateAsync(user, account.Password);

                if (result.Succeeded)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callBackUrl = Url.RouteUrl("ConfirmEmail", new { code, key = user.GeneratedKey },
                                                       Request.Scheme);

                        var message = $"<a href=\"{callBackUrl}\"> Confirm Email </a>";

                        await _emailSender.SendEmailAsync(user.Email, "Confirm Email", message);

                        return(View("SuccessRegister", user));
                    }
                    if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                    {
                        var token = await _userManager
                                    .GenerateChangePhoneNumberTokenAsync(user, user.PhoneNumber);

                        await _smsSender.SendSmsAsync(account.PhoneNumberUser, token);

                        return(View("ConfirmPhone", new Confirmphone  {
                            Returnto = returnTo, Username = account.UserName
                        }));
                    }

                    // await _signInManager.SignInAsync(user, false);

                    return(RedirectToLocal(returnTo));
                }

                this.AddErrors(result);
            }

            return(View(account));
        }
 public async Task <string> GenerateEmailConfirmationTokenAsync(string userId)
 {
     try
     {
         return(await AppUserManager.GenerateEmailConfirmationTokenAsync(userId));
     }
     catch (Exception)
     {
         return(null);
     }
 }
Esempio n. 10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    TenantId = Input.TenantId, UserName = Input.Email, Email = Input.Email
                };
                //var tenants = _dbContext.Set<Tenant>().Count();

                //_dbContext.DisableFilter();
                //tenants = _dbContext.Set<Tenant>().Count();
                _userManager.TenantId = Input.TenantId;
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    //_dbContext.EnableFilter();
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var role   = Input.Role;
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    await _userManager.AddToRoleAsync(user, role);

                    //Add area
                    Area organization = new Area();
                    organization.Name = Input.Area;
                    _context.Add(organization);
                    if (await _context.SaveChangesAsync() != 0)
                    {
                        user.AreaId = organization.AreaId;
                        await _userManager.UpdateAsync(user);
                    }

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 12
0
        public async Task <IHttpActionResult> CreateUser(UserRegistartionModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new User()
            {
                UserName = createUserModel.UserName,
                Password = createUserModel.Password,
                //DOB = null,
                //Address = null,
                //CreatedOn = DateTime.Now,
                //AdditedOn = DateTime.Now
            };
            //switch (createUserModel.UserNameType)
            //{
            //    case Comman.Enum.UserNameTypes.UserName:
            //        break;
            //    case Comman.Enum.UserNameTypes.Mobile:
            //        user.Mobile = createUserModel.UserName;
            //        break;
            //    case Comman.Enum.UserNameTypes.Email:
            //        user.Email = createUserModel.UserName;
            //        break;
            //    default:
            //        break;
            //}

            CreateUserCommand command = new CreateUserCommand()
            {
                UserToBeCreated = user
            };

            _commandExecuter.Enqueue(command);


            string code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

            await AppUserManager.SendEmailAsync(user.Id,
                                                "Confirm your account",
                                                "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, "User Created Successfully!"));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                // ------------- Add To Admin Role
                //await _userManager.AddToRoleAsync(user, "Admin");

                // ------------- Add Claims To User
                //await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("your-claim", "your-value"));


                // ------------- Add Claims To Role
                //var roles = await _userManager.GetModelRolesAsync(user);
                //await _roleManager.AddClaimAsync(roles.First(), new System.Security.Claims.Claim("your-claim", "your-value"));

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 14
0
        public async Task <IHttpActionResult> Post(AccountModelBinding createUserModel)
        {
            var user = new ApplicationUser()
            {
                UserName = createUserModel.Username,
                Email    = createUserModel.Email,
                JoinDate = DateTime.Now.Date,
            };

            IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            var code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            string site;

#if DEBUG
            site = Constants.Site;
#else
            site = String.Format("https://{0}.azurewebsites.net/",
                                 Environment.ExpandEnvironmentVariables("%WEBSITE_SITE_NAME%")
                                 .ToLower());
#endif
            var callbackUrl      = site + $"account/confirmemail?userId={Uri.EscapeDataString(user.Id)}&code={Uri.EscapeDataString(code)}";
            var subject          = "Welcome to Smalldebts!";
            var plainTextContent = "Please confirm your account by clicking this link:" + callbackUrl;
            var htmlContent      = "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>";


            var emailSent = _mailProvider.SendEmailAsync(
                new Email()
            {
                Address = "*****@*****.**", Name = "Smalldebts team"
            },
                "Welcome to Smalldebts!",
                plainTextContent,
                htmlContent,
                new Email()
            {
                Address = user.Email, Name = user.UserName
            });

            return(Created(callbackUrl, TheModelFactory.Create(user)));
        }
Esempio n. 15
0
        public async Task <IActionResult> OnPostAsync(string returnTo)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var user = new User()
            {
                FirstName    = User.FirstName,
                LastName     = User.LastName,
                UserName     = User.UserName,
                Email        = User.Email,
                RegisteredOn = User.RegisteredOn,
                GeneratedKey = Guid.NewGuid().ToString("N")
            };
            var result = await _userManager.CreateAsync(user, User.Password);

            if (result.Succeeded)
            {
                if (_userManager.Options.SignIn.RequireConfirmedEmail)
                {
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { key = user.GeneratedKey, code = code },
                        protocol: Request.Scheme);

                    var message = $"<a href=\'{callbackUrl}\'> Confirm Email </a>";

                    await _emailSender.SendEmailAsync(user.Email, "Confirm Email", message);

                    await _signInManager.SignInAsync(user, false);

                    return(RedirectToLocal("/VerificationAccount"));
                }

                await _signInManager.SignInAsync(user, true);

                RedirectToLocal("/account/userArea");
            }
            this.AddErrors(result);

            return(Page());
        }
Esempio n. 16
0
        public async Task <IHttpActionResult> SendConfirmEmail()
        {
            var    userId = User.Identity.GetUserId();
            string code   = await AppUserManager.GenerateEmailConfirmationTokenAsync(userId);

            // var callbackUrl = new Uri(Url. Link("ConfirmEmail", new {  userId, code }));

            //we need to do this otherwise the + in the string gets replaced with a space
            var urlCode = Uri.EscapeDataString(code);
            var url     = $"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/auth/verify?userId={userId}&code={urlCode}";

            var body = $"Please confirm your account by clicking <a href=\"{url}\">here</a>";

            await AppUserManager.SendEmailAsync(userId, "Confirm your account", body);

            return(Ok());
        }
Esempio n. 17
0
        public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser
            {
                UserName  = userModel.Email,
                Email     = userModel.Email,
                FirstName = userModel.FirstName,
                LastName  = userModel.LastName,
                BirthDate = userModel.BirthDate.Value,
                Gender    = userModel.Gender.Value,
                JoinDate  = DateTime.Now.Date,
            };

            try
            {
                var addUserResult = await AppUserManager.CreateAsync(user, userModel.Password);

                if (!addUserResult.Succeeded)
                {
                    return(GetErrorResult(addUserResult));
                }

                //var user = await unitOfWork.AccountRepository.FindByNameAsync( createUserModel.Email );

                string code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));

                await AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(Created(new Uri(Url.Link("GetUserById", new { id = user.Id })), user.ToDto()));
            }
            catch (Exception ex)
            {
                await AppUserManager.DeleteAsync(user);

                throw new BusinessLogicException($"Could not create user: {ex.Message}");
            }
        }
Esempio n. 18
0
        public async Task <ActionResult> Register(RegisterUserViewModel model)
        {
            var recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "O captcha é obrigatório.");
                return(View(model));
            }

            var recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponseTaskAsync();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Captcha incorreto.");
                return(View(model));
            }

            if (ModelState.IsValid)
            {
                Mapper.CreateMap <RegisterUserViewModel, AppUser>();
                var user = Mapper.Map <RegisterUserViewModel, AppUser>(model);
                user.Enabled   = true;
                user.IPAddress = GetUserIP(Request);
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, "Confirme sua Conta", callbackUrl);

                    return(View("Created"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> Register(RegisterAccount account, string returnTo)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    UserName     = account.UserName,
                    Email        = account.Email,
                    FirstName    = account.FirstName,
                    LastName     = account.LastName,
                    RegisteredOn = account.RegisteredOn,
                    GeneratedKey = Guid.NewGuid().ToString("N")
                };


                var result = await _userManager.CreateAsync(user, account.Password);

                if (result.Succeeded)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callBackUrl = Url.RouteUrl("ConfirmEmail", new { code, key = user.GeneratedKey },
                                                       Request.Scheme);

                        var message = $"<a href=\"{callBackUrl}\"> Confirm Email </a>";

                        await _emailSender.SendEmailAsync(user.Email, "Confirm Email", message);
                    }

                    await _signInManager.SignInAsync(user, false);

                    return(RedirectToLocal(returnTo));
                }

                this.AddErrors(result);
            }


            return(View(account));
        }
Esempio n. 20
0
        /// <summary>
        /// Sends a confirmation email to the user's email id.
        /// The user must click it to validate his email Id.
        /// </summary>
        /// <param name="appUser"></param>
        /// <returns></returns>
        private async Task <string> SendEmailConfirmationAsync(AppUser appUser)
        {
            // Generate a Url encoded code/token
            string code = await AppUserManager.GenerateEmailConfirmationTokenAsync(appUser.Id);

            var    guiWebsiteBaseUrl = ConfigurationManager.AppSettings[Constants.WebConfig.WebsiteBaseUrlKey];
            var    guiWebsiteConfirmEmailPagePath = ConfigurationManager.AppSettings[Constants.WebConfig.ConfirmEmailPagePathKey];
            string encodedConfirmationCode        = HttpUtility.UrlEncode(code);
            var    callbackApiUrl = $"{guiWebsiteBaseUrl}{guiWebsiteConfirmEmailPagePath}?code={encodedConfirmationCode}";

            try
            {
                await AppUserManager.SendEmailAsync(appUser.Id, Emails.ConfirmEmailTitle, Emails.ConfirmEmailBodyPrefix + callbackApiUrl);
            }
            catch
            {
                return(await Task.FromResult(Errors.FailedToSendConfirmationEmail));
            }
            return(await Task.FromResult(Responses.SendConfirmEmailTokenResponseMessage));
        }
Esempio n. 21
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    Id = Guid.NewGuid().ToString(), UserName = model.Email, Email = model.Email, EmailConfirmed = true
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                    if (!user.EmailConfirmed)
                    {
                        var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                        #region TODO: Código para el envio del correo electrónico

                        /*PLNFramework.Mailing.IEmail email = new PLNFramework.Mailing.Email();
                         * email.Tos = new string[] { model.Email };
                         * email.Subject = "Confirm your account";
                         * email.Body = "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>";
                         * AdminSoft.WebSite.Helpers.EmailHelper.SendMailRegister(email);*/
                        #endregion
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return(View(model));
        }
        public async Task <IHttpActionResult> RegisterUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new ApplicationUser
            {
                UserName  = createUserModel.Username,
                Email     = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                LastName  = createUserModel.LastName,
                Level     = 3,
                JoinDate  = DateTime.Now.Date,
            };

            IdentityResult addResult = await AppUserManager.CreateAsync(user);

            if (!addResult.Succeeded)
            {
                return(GetErrorResult(addResult));
            }


            // Send mail after  creation an account
            //la création d'un code unique (token) qui est valide pour les 6 prochaines heures
            //et lié à cet ID utilisateur, cela se produit uniquement lorsque vous appelez la méthode "GenerateEmailConfirmationTokenAsync",
            string token = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            //code = System.Web.HttpUtility.UrlEncode (code); code = System.Web.HttpUtility.UrlDecode (code)
            Uri callUrl = new Uri(Url.Link("ConfirmEmailRoute", new { id = user.Id, token = System.Web.HttpUtility.UrlEncode(token) }));
            await AppUserManager.SendEmailAsync(user.Id, "Activate your Account", "Please confirm your account by clicking href=\"" + callUrl + "\">here</a>");

            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
Esempio n. 23
0
        public async Task <IHttpActionResult> PostAsync(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            ApplicationUser user          = (ApplicationUser)userModel;
            IdentityResult  addUserResult = await AppUserManager.CreateAsync(user, userModel.Password);

            if (!addUserResult.Succeeded)
            {
                ModelState.AddModelErrorRange(addUserResult.Errors);
                return(BadRequest(ModelState));
            }
            string token = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            const string format = "http://127.0.0.1:5500/#!/konto/activate/token={0}&user={1}";

            AppUserManager.SendEmailAsync(user.Id, "Activate", new Emails.Register()
            {
                Address = string.Format(format, token, user.Id)
            });
            return(Created(Url.Link("UserData", null), user));
        }
        public async Task <IHttpActionResult> CreateUser(IdentityUser user)
        {
            var addUser = await AppUserManager.CreateAsync(user);

            if (!addUser.Succeeded)
            {
                Logger.ServiceLog.Warn("Ошибка регистрации пользователя");
                return(GetErrorResult(addUser));
            }

            var code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            code = HttpUtility.UrlEncode(code);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code }));

            await AppUserManager.SendEmailAsync(user.Id, "Подтверждение аккаунта в DropBoxDuplicate",
                                                "<strong>Подтвердите ваш аккаунт</strong>: <a href=\"" + callbackUrl + "\">Ссылка</a>");

            var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            Logger.ServiceLog.Info($"Пользователь {user.Id} успешно зарегистрирован.");
            return(Created(locationHeader, TheModelFactory.Create(user)));
        }
Esempio n. 25
0
        public async Task <IHttpActionResult> Register(UserModel userModel)
        {
            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
            {
                var user = new ApplicationUser()
                {
                    UserName  = userModel.Email,
                    Email     = userModel.Email,
                    FirstName = string.Empty,
                    LastName  = string.Empty,
                    JoinDate  = DateTime.Now.Date,
                };

                IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, userModel.Password);

                if (!addUserResult.Succeeded)
                {
                    return(GetErrorResult(addUserResult));
                }

                // User has been created, insert a record in the organization table so it's avaiable for updating later
                DynamicParameters pSignup = new DynamicParameters();
                pSignup.Add("@Id", user.Id, dbType: DbType.String, direction: ParameterDirection.Input);
                DatabaseUpdate.Update(pSignup, "dbo.sp_SignUp");


                //The call back URL is stored in the database. This makes it easy to switch between DEV/UAT/PROD
                DynamicParameters pReg = new DynamicParameters();
                pReg.Add("@Name", "CONFIRM_REGISTRATION_URL", dbType: DbType.String, direction: ParameterDirection.Input);
                AppSettings settings = DatabaseGet.GetSingle <AppSettings>(pReg, "dbo.sp_AppSettingsGetByName");
                if (settings == null)
                {
                    throw new ArgumentNullException("settings");
                }


                string code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                code = HttpUtility.UrlEncode(code);

                NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["userId"] = user.Id;
                queryString["code"]   = code;
                string callbackUrl = settings.Value + queryString.ToString();

                await AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

                return(Created(locationHeader, TheModelFactory.Create(user)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(BadRequest(ModelState));
            }
        }
        public async Task <IActionResult> OnPostFormAsync()
        {
            ReturnUrl ??= Url.Page("/Account/Manage/Index");

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName  = Input.Username,
                    Email     = Input.Email,
                    Gender    = Input.Gender,
                    Weight    = Input.Weight,
                    BirthDate = Input.Age,
                };

                var result = await _userManager.CreateAsync(user, Input.Password).ConfigureAwait(false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    if (Input.Interests != null && Input.Interests.Any())
                    {
                        var categories = await _ctx.Categories.AsQueryable()
                                         .Where(c => Input.Interests.Contains(c.Name))
                                         .ToListAsync().ConfigureAwait(false);

                        if (categories.Any())
                        {
                            await _ctx.AddRangeAsync(categories.Select(c => new UserCategory
                            {
                                UserId     = user.Id,
                                CategoryId = c.Id
                            })).ConfigureAwait(false);

                            await _ctx.SaveChangesAsync().ConfigureAwait(false);
                        }
                    }

                    if (Input.Email != default)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = user.Id, code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          await _renderer.RenderPartialToStringAsync("_EmailConfirmationPartial", user, new { callbackUrl })
                                                          .ConfigureAwait(false)).ConfigureAwait(false);

                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            // TODO if I ever decide to enable required accounts, I should probably push a message
                            return(this.JavascriptRedirect(Url.Page("RegisterConfirmation", new { email = Input.Email })));
                        }
                    }

                    await _signInManager.SignInAsync(user, isPersistent : false).ConfigureAwait(false);

                    _messages.PushMessage(await _renderer.RenderPartialToStringAsync("_RegisterSuccessPartial", user)
                                          .ConfigureAwait(false));
                    return(this.JavascriptRedirect(ReturnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            await InitModelAsync().ConfigureAwait(false);

            return(Partial("Forms/_RegisterFormPartial", this));
        }
Esempio n. 27
0
        public async Task <IHttpActionResult> CreateUser(UserDto userDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var foundDepartment = Context.Departments.Where(d => d.Name == userDto.Department);

            var found = foundDepartment.ToList();

            Department dep = null;

            if (found.Count == 0)
            {
                if (userDto.Department != null)
                {
                    if (userDto.Department != "")
                    {
                        return(BadRequest("Department doesn't exist"));
                    }
                }
            }
            else
            {
                dep = found[0];
            }

            var user = new User()
            {
                UserName     = userDto.Username,
                Email        = userDto.Email,
                Name         = userDto.Name,
                DepartmentID = dep.DepartmentID
            };

            string generatedPassword = new RandomStringGenerator().GenerateRandomString(40);

            IdentityResult addUserResult = await AppUserManager.CreateAsync(user, generatedPassword);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            string code = await AppUserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));


            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            user = AppUserManager.FindByName(userDto.Username);

            await AssignRolesToUser(user.Id, new string[] { userDto.RoleName });

            Context.SaveChanges();

            await AppUserManager.SendEmailAsync(user.Id, "Confirm your CWMD account", "Your password is: " + generatedPassword + "\nPlease confirm your account by clicking here: " + callbackUrl);


            user.Department = dep;

            return(Created(locationHeader, TheModelFactory.Create(user)));
        }