Ejemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> SignUp(SignUpViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // --- Sign in the user
                    await SignInManager.SignInAsync(user, false, false);

                    // --- Create the subscription for the user
                    var subscrSrv = ServiceManager.GetService <ISubscriptionService>();
                    var newSubscr = new SubscriptionDto
                    {
                        SubscriberName = user.UserName,
                        PrimaryEmail   = user.Email,
                        CreatedUtc     = DateTimeOffset.UtcNow,
                    };
                    var subscriptionId = await subscrSrv.CreateSubscriptionAsync(newSubscr, user.Id);

                    CreateAuthenticationTicket(false, new Guid(user.Id), user.UserName, false, subscriptionId, true);
                    return(RedirectToAction("SelectSubscriptionPackage"));
                }
                AddErrors(result);
            }
            return(View(model));
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> Handle(RegisterCommand request, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            _unitOfWork.BeginTransaction();

            var appUser = _mapper.Map <AppIdentityUser>(request.User);
            var result  = await _identityUserManager.CreateAsync(appUser, request.Password);

            if (result.Succeeded)
            {
                var userPrincipal = await _signInManager.CreateUserPrincipalAsync(appUser);

                var userId = int.Parse(_identityUserManager.GetUserId(userPrincipal));

                await _signInManager.SignInAsync(appUser, true);

                _unitOfWork.Commit();

                return(new ActionResult {
                    Suceeded = true
                });
            }
            else
            {
                _unitOfWork.Rollback();

                return(new ActionResult
                {
                    Suceeded = false,
                    ErrorMessages = result.Errors.Select(x => x.Description).ToList()
                });
            }
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> GoogleResponse()
        {
            ExternalLoginInfo info = await AppSignInManager.GetExternalLoginInfoAsync();

            var result = await AppSignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false);

            string[] userInfo = { info.Principal.FindFirst(ClaimTypes.Name).Value, info.Principal.FindFirst(ClaimTypes.Email).Value };
            if (result.Succeeded)
            {
                return(LocalRedirect("/"));
            }
            else
            {
                AppUser user = new AppUser
                {
                    Email    = info.Principal.FindFirst(ClaimTypes.Email).Value,
                    UserName = info.Principal.FindFirst(ClaimTypes.Email).Value,
                };

                IdentityResult identResult = await AppUserManager.CreateAsync(user);

                if (identResult.Succeeded)
                {
                    identResult = await AppUserManager.AddLoginAsync(user, info);

                    if (identResult.Succeeded)
                    {
                        await AppSignInManager.SignInAsync(user, false);

                        return(LocalRedirect("/"));
                    }
                }
                return(LocalRedirect("/"));
            }
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> ChangePassword(ProfileViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("EditProfile", new ProfileViewModel {
                    Passwords = model.Passwords, User = CurrentUser
                }));
            }

            var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId <int>(), model.Passwords.OldPassword, model.Passwords.NewPassword);

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(User.Identity.GetUserId <int>());

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }

                this.SetNotificationMessage(NotificationType.Success, "The password was changed successfully.");

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

            foreach (var error in result.Errors)
            {
                this.SetNotificationMessage(NotificationType.Error, error);
            }

            return(View("EditProfile", new ProfileViewModel {
                Passwords = model.Passwords, User = CurrentUser
            }));
        }
Ejemplo n.º 6
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());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> LoginAs(string id)
        {
            var user = await _userManager.FindByIdAsync(id);

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

            return(RedirectToAction("Index", "Home"));
        }
        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));
        }
Ejemplo n.º 9
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());
        }
Ejemplo n.º 10
0
        public async Task <ActionResult> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            _unitOfWork.BeginTransaction();

            var user = await _identityUserManager.FindByNameAsync(request.Email);

            if (user == null)
            {
                return(new ActionResult
                {
                    Suceeded = false,
                    ErrorMessages = new List <string> {
                        "E-mail or password is incorrect!"
                    }
                });
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, request.RememberMe);

                _unitOfWork.Commit();

                return(new ActionResult {
                    Suceeded = true
                });
            }
            else
            {
                var loginResult = new ActionResult {
                    Suceeded = false
                };

                if (result.IsLockedOut)
                {
                    loginResult.ErrorMessages.Add("Your account is locked out!");
                }
                else
                {
                    loginResult.ErrorMessages.Add("E-mail or password is incorrect!");
                }

                _unitOfWork.Rollback();

                return(loginResult);
            }
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    Id             = Guid.NewGuid().ToString("N"),
                    UserName       = model.Email,
                    Email          = model.Email,
                    DisplayName    = model.UserNickName,
                    CreateTime     = DateTimeOffset.Now,
                    Deleted        = false,
                    IsActive       = true,
                    EmailConfirmed = false,
                };
                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));
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> LogIn([FromForm] UserLogInModel userLogIn)
        {
            AppUser user = await AppUserManager.FindByNameAsync(userLogIn.UserName);

            if (user != null)
            {
                if (await AppUserManager.CheckPasswordAsync(user, userLogIn.Password))
                {
                    await AppSignInManager.SignInAsync(user, isPersistent : true);

                    return(Json(new { success = true }));
                }
            }
            return(Json(new { success = false }));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> ExternalLoginConfirm(ExternalLoginConfirm model, string returnTo = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(View("Error"));
            }

            var user = new User
            {
                Email          = model.Email,
                UserName       = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(user);

            if (result.Succeeded)
            {
                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

                    return(RedirectToLocal(returnTo));
                }

                AddErrors(result);

                return(View());
            }

            AddErrors(result);

            return(View());
        }
        public async Task <ActionResult> SignUp(AccountSignUpViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var adminUser = new AppUserEntity
                {
                    FullName    = model.Name,
                    Email       = model.Email,
                    CultureId   = User.Culture.Name,
                    UICultureId = User.UICulture.Name,
                    TimeZoneId  = User.TimeZone.Id
                };

                //
                adminUser.SetDefaultUserName();

                //
                adminUser.Realms.Add(Realm.AdminWebsite);

                //
                adminUser.Roles.Add(Role.Basic);

                //
                var result = await _appUserManager.CreateAsync(adminUser, model.Password);

                if (result.Succeeded)
                {
                    var isPersistent = false;

                    _signInManager.InitialPersistenceState = isPersistent;

                    await _signInManager.SignInAsync(
                        adminUser,
                        isPersistent,
                        rememberBrowser : false
                        );

                    return(RedirectToLocal(returnUrl));
                }

                ModelState.AddModelError(string.Empty, GetLocalizedString <AreaResources>("DefaultErrorMessage"));
            }

            ViewBag.ReturnUrl = returnUrl;

            return(View(model));
        }
Ejemplo n.º 15
0
        public async Task <bool> SignInUserAsync(UserSignInDto user)
        {
            try
            {
                var appUser = new ApplicationUser
                {
                    Id       = user.UserId,
                    UserName = user.UserName,
                    Email    = user.UserEmail
                };

                await AppSignInManager.SignInAsync(appUser, user.IsPersistence, user.RememberBrowser);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

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

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
        public async Task <IHttpActionResult> UpdateUser(UpdateUserBindingModel model)
        {
            string slog = string.Format("UpdateUser model: {0}", JsonConvert.SerializeObject(model));

            logger.Debug(slog);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User user = userService.GetUser(model.Id);

            if (user != null)
            {
                try
                {
                    bool   isPhonenumberChanged = false;
                    string phoneCode            = string.Empty;
                    Random rnd = new Random(DateTime.Now.Second);
                    phoneCode = rnd.Next(1000, 9999).ToString();

                    if (user.PhoneNumber != model.phoneNumber)
                    {
                        isPhonenumberChanged = true;
                        user.PhoneNumberCode = phoneCode;
                        user.PhoneNumber     = model.phoneNumber;
                    }

                    user.FirstName     = model.firstName;
                    user.LastName      = model.lastName;
                    user.PostalCode    = model.billingZipCode;
                    user.StreetAddress = model.billingStreetNumber;
                    userService.Update(model.Id, user);

                    if (isPhonenumberChanged)
                    {
                        // Send SMS to phone
                        await this.AppUserManager.SendSmsAsync(user.Id, "Vethentia Phone code is " + phoneCode);
                    }

                    await AppSignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                catch (Exception ex)
                {
                    logger.Error("UpdateUser", ex);
                    throw;
                }
            }

            // return Created(locationHeader, TheModelFactory.Create(user));
            RegisterResponseBindingModel resModel = new RegisterResponseBindingModel()
            {
                msgId       = 16,
                phoneNumber = model.phoneNumber,
                status      = 0,
                userId      = user.Id
            };

            return(Ok(resModel));
        }
        public async Task <IHttpActionResult> Register(CreateUserBindingModel model)
        {
            string slog = string.Format("Register model: {0}", JsonConvert.SerializeObject(model));

            logger.Debug(slog);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string phoneCode = string.Empty;
            Random rnd       = new Random(DateTime.Now.Second);

            phoneCode = rnd.Next(1000, 9999).ToString();

            var user = new User()
            {
                UserName        = model.emailAddress,
                Email           = model.emailAddress,
                FirstName       = model.firstName,
                LastName        = model.lastName,
                PhoneNumber     = model.phoneNumber,
                PostalCode      = model.billingZipCode,
                StreetAddress   = model.billingStreetNumber,
                RegisteredAt    = DateTime.Now,
                PhoneNumberCode = phoneCode
            };

            try
            {
                string userId = string.Empty;

                User userCheck = userService.GetUserByEmail(model.emailAddress);
                if (userCheck == null || (userCheck != null && (!userCheck.EmailConfirmed || !userCheck.PhoneNumberConfirmed)))
                {
                    if (userCheck == null)
                    {
                        bool val = userService.IsPhoneNumberRegistered(model.phoneNumber);
                        if (val)
                        {
                            ModelState.AddModelError("", string.Format("{0} is already registered.", model.phoneNumber));
                            return(BadRequest(ModelState));
                        }

                        IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, model.password);

                        if (!addUserResult.Succeeded)
                        {
                            return(GetErrorResult(addUserResult));
                        }
                        await AppSignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        userId = user.Id;
                    }
                    else
                    {
                        userCheck.FirstName       = model.firstName;
                        userCheck.LastName        = model.lastName;
                        userCheck.PhoneNumber     = model.phoneNumber;
                        userCheck.StreetAddress   = model.billingStreetNumber;
                        userCheck.PostalCode      = model.billingZipCode;
                        userCheck.PhoneNumberCode = phoneCode;
                        userService.Update(userCheck.Id, userCheck);
                        userId = userCheck.Id;
                    }

                    string name = user.FirstName + " " + user.LastName;
                    string code = await this.AppUserManager.GenerateEmailConfirmationTokenAsync(userId);

                    code = HttpUtility.UrlEncode(code);

                    string uri         = HttpContext.Current.Request.Url.AbsoluteUri;
                    string host        = uri.Substring(0, uri.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
                    var    callbackUrl = string.Format("{0}/Account/ConfirmEmail?userId={1}&code={2}", host, user.Id, code);

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

                    string body = "Hello " + name + ",";
                    body += "<br /><br />Please click the following link to activate your account";
                    body += "<br /><a href = '" + callbackUrl + "'>Click here to activate your account.</a>";
                    body += "<br /><br />Thanks";

                    // Send Email out
                    await AppUserManager.SendEmailAsync(userId, "Confirm your account", body);

                    // Send SMS to phone
                    await this.AppUserManager.SendSmsAsync(userId, "Vethentia Phone code is " + phoneCode);
                }
                else
                {
                    ModelState.AddModelError("", string.Format("{0} is already registered.", model.phoneNumber));
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Register", ex);
                throw;
            }
            Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            // return Created(locationHeader, TheModelFactory.Create(user));
            RegisterResponseBindingModel resModel = new RegisterResponseBindingModel()
            {
                msgId       = 16,
                phoneNumber = model.phoneNumber,
                status      = 0,
                userId      = user.Id
            };

            return(Ok(resModel));
        }