Example #1
0
        public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false)
        {
            _userEventHandler.LoggingIn(userNameOrEmail, password);

            var user = ValidateLogOn(userNameOrEmail, password);

            if (!ModelState.IsValid)
            {
                return(View(_openIdProviders));
            }

            var membershipSettings = _membershipService.GetSettings();

            if (user != null &&
                membershipSettings.EnableCustomPasswordPolicy &&
                membershipSettings.EnablePasswordExpiration &&
                _membershipService.PasswordIsExpired(user, membershipSettings.PasswordExpirationTimeInDays))
            {
                return(RedirectToAction("ChangeExpiredPassword", new { username = user.UserName }));
            }

            _authenticationService.SignIn(user, rememberMe);
            _userEventHandler.LoggedIn(user);

            return(this.RedirectLocal(returnUrl));
        }
Example #2
0
        public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false)
        {
            _userEventHandler.LoggingIn(userNameOrEmail, password);

            var user = ValidateLogOn(userNameOrEmail, password);

            if (!ModelState.IsValid)
            {
                var shape = _orchardServices.New.LogOn().Title(T("Log On").Text);

                return(new ShapeResult(this, shape));
            }

            var membershipSettings = _membershipService.GetSettings();

            if (user != null &&
                membershipSettings.EnableCustomPasswordPolicy &&
                membershipSettings.EnablePasswordExpiration &&
                _membershipService.PasswordIsExpired(user, membershipSettings.PasswordExpirationTimeInDays))
            {
                return(RedirectToAction("ChangeExpiredPassword", new { username = user.UserName }));
            }
            _authenticationService.SignIn(user, rememberMe);
            _userEventHandler.LoggedIn(user);
            if (user != null)
            {
                var token = _authService.GenerateLocalAccessTokenResponse(user.UserName);
                TempData["Token"] = token;
            }
            return(this.RedirectLocal(returnUrl));
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var userNameOrEmail        = activityContext.GetState <string>("UserNameOrEmail");
            var password               = activityContext.GetState <string>("Password");
            var createPersistentCookie = IsTrueish(activityContext.GetState <string>("CreatePersistentCookie"));
            var user = workflowContext.Content != null?workflowContext.Content.As <IUser>() : default(IUser);

            if (user == null)
            {
                if (String.IsNullOrWhiteSpace(userNameOrEmail) || String.IsNullOrWhiteSpace(password))
                {
                    yield return(T("IncorrectUserNameOrPassword"));

                    yield break;
                }

                user = _membershipService.ValidateUser(userNameOrEmail, password);
            }

            if (user == null)
            {
                yield return(T("IncorrectUserNameOrPassword"));

                yield break;
            }

            _userEventHandler.LoggingIn(userNameOrEmail, password);
            _authenticationService.SignIn(user, createPersistentCookie);
            _userEventHandler.LoggedIn(user);

            yield return(T("Done"));
        }
Example #4
0
        public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false)
        {
            _userEventHandler.LoggingIn(userNameOrEmail, password);

            var user = ValidateLogOn(userNameOrEmail, password);

            if (!ModelState.IsValid)
            {
                var shape = _tomeltServices.New.LogOn().Title(T("系统登陆").Text);
                return(new ShapeResult(this, shape));
            }

            _authenticationService.SignIn(user, rememberMe);
            _userEventHandler.LoggedIn(user);
            return(this.RedirectLocal(returnUrl));
        }
Example #5
0
        public ActionResult LogOn(LogonViewModel model)
        {
            if (ModelState.IsValid)
            {
                _userEventHandler.LoggingIn(model.UserNameOrEmail, model.Password);
                var user = ValidateLogOn(model.UserNameOrEmail, model.Password);
                _authenticationService.SignIn(user, model.RememberMe);
                _userEventHandler.LoggedIn(user);
                return(this.RedirectLocal(model.ReturnUrl));
            }

            return(View("Logon", "Layout2"));
        }
        public ActionResult CheckTFALogin(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false)
        {
            _userEventHandler.LoggingIn(userNameOrEmail, password);

            var user = ValidateLogOn(userNameOrEmail, password);

            if (!ModelState.IsValid)
            {
                //var errors = ModelState.Keys.SelectMany(k => ModelState[k].Errors).Select(m => m.ErrorMessage).ToArray();
                var errorList = (from item in ModelState
                                 where item.Value.Errors.Any()
                                 select item.Value.Errors[0].ErrorMessage).ToList();
                return(Json(new { error = true, errors = errorList }));
            }

            //Handle TFA
            var userTFA  = user.As <TwoFactorAuthenticationPart>();
            var settings = _orchardServices.WorkContext.CurrentSite.As <TwoFactorAuthenticationSettingsPart>();

            if (!userTFA.CanLoginWithoutTFA && (settings.RequireTFA || userTFA.EnableTFA))
            {
                Session["user"]                = user;
                Session["rememberMe"]          = rememberMe;
                Session["displayTFAChallenge"] = true;
                return(Json(new { displayTFAChallenge = "True", error = false }));
            }

            //Messages
            if (userTFA.CanLoginWithoutTFA && (settings.RequireTFA || userTFA.EnableTFA))
            {
                _notifier.Information(T("An admin has allowed you to login without Two-Factor Authentication."));

                if (settings.RequireTFA)
                {
                    _notifier.Information(T("Two-Factor Authentication is required. Please ensure TFA has been set up prior to logging out."));
                }
                else
                {
                    _notifier.Information(T("Please disable or ensure correct setup of TFA prior to logging out."));
                }

                //Some way of not hardcoding this???
                returnUrl = "/Admin/MyProfile";
            }

            _authenticationService.SignIn(user, rememberMe);
            _userEventHandler.LoggedIn(user);

            return(Json(new { displayTFAChallenge = "False", returnUrl = returnUrl, error = false }));
        }
Example #7
0
        public ActionResult Register(string userName, string email, string password, string confirmPassword, string returnUrl = null, bool createPersistentCookie = false)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = Request.QueryString["ReturnUrl"];
            }
            // ensure users can register
            var membershipSettings = _membershipService.GetSettings();

            if (!membershipSettings.UsersCanRegister)
            {
                return(HttpNotFound());
            }

            ViewData["PasswordLength"]              = membershipSettings.GetMinimumPasswordLength();
            ViewData["LowercaseRequirement"]        = membershipSettings.GetPasswordLowercaseRequirement();
            ViewData["UppercaseRequirement"]        = membershipSettings.GetPasswordUppercaseRequirement();
            ViewData["SpecialCharacterRequirement"] = membershipSettings.GetPasswordSpecialRequirement();
            ViewData["NumberRequirement"]           = membershipSettings.GetPasswordNumberRequirement();

            var shape = _orchardServices.New.Register();

            // validate user part, create a temp user part to validate input
            var userPart = _contentManager.New("User");

            if (userPart != null && !_frontEndProfileService.UserHasNoProfilePart(userPart.As <IUser>()))
            {
                shape.UserProfile = ((IFrontEndEditService)_frontEndProfileService).BuildFrontEndShape(
                    _contentManager.UpdateEditor(userPart, this),
                    _frontEndProfileService.MayAllowPartEdit,
                    _frontEndProfileService.MayAllowFieldEdit);
                if (!ModelState.IsValid)
                {
                    _orchardServices.TransactionManager.Cancel();
                    return(new ShapeResult(this, shape));
                }
            }

            if (ValidateRegistration(userName, email, password, confirmPassword))
            {
                // Attempt to register the user
                // No need to report this to IUserEventHandler because _membershipService does that for us
                var user = _membershipService.CreateUser(new CreateUserParams(userName, password, email, null, null, false));

                if (user != null)
                {
                    if (!_frontEndProfileService.UserHasNoProfilePart(user))
                    {
                        // we know userpart data is ok, now we update the 'real' recently published userpart
                        ((IFrontEndEditService)_frontEndProfileService).BuildFrontEndShape(
                            _contentManager.UpdateEditor(user, this),
                            _frontEndProfileService.MayAllowPartEdit,
                            _frontEndProfileService.MayAllowFieldEdit);
                    }

                    var userPart2 = user.As <UserPart>();
                    if (user.As <UserPart>().EmailStatus == UserStatus.Pending)
                    {
                        _userService.SendChallengeEmail(user.As <UserPart>(), nonce => Url.AbsoluteAction(() => Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce })));

                        _userEventHandler.SentChallengeEmail(user);
                        return(RedirectToAction("ChallengeEmailSent", "Account", new { area = "Orchard.Users" }));
                    }

                    if (user.As <UserPart>().RegistrationStatus == UserStatus.Pending)
                    {
                        return(RedirectToAction("RegistrationPending", "Account", new { area = "Orchard.Users" }));
                    }

                    _userEventHandler.LoggingIn(userName, password);
                    _authenticationService.SignIn(user, createPersistentCookie);
                    _userEventHandler.LoggedIn(user);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(this.RedirectLocal(returnUrl));
                    }

                    return(Redirect(string.IsNullOrWhiteSpace(_shellSettings.RequestUrlPrefix) ?
                                    "~/" :
                                    "~/" + _shellSettings.RequestUrlPrefix.Trim('/')));
                }

                ModelState.AddModelError("_FORM", T(ErrorCodeToString(/*createStatus*/ MembershipCreateStatus.ProviderError)));
            }

            // If we got this far, something failed, redisplay form
            //var shape = _orchardServices.New.Register();
            return(new ShapeResult(this, shape));
        }
Example #8
0
        public void Register(UserRegistration userRegistrationParams)
        {
            if (RegistrationSettings.UsersCanRegister)
            {
                var policyAnswers = new List <PolicyForUserViewModel>();
                if (_utilsServices.FeatureIsEnabled("Laser.Orchard.Policy") &&
                    UserRegistrationExtensionsSettings.IncludePendingPolicy == Policy.IncludePendingPolicyOptions.Yes)
                {
                    IEnumerable <PolicyTextInfoPart> policies = GetUserLinkedPolicies(userRegistrationParams.Culture);
                    // controllo che tutte le policy abbiano una risposta e che le policy obbligatorie siano accettate
                    var allRight = true;
                    foreach (var policy in policies)
                    {
                        var policyId       = policy.Id;
                        var policyRequired = policy.UserHaveToAccept;
                        var answer         = userRegistrationParams.PolicyAnswers.Where(w => w.PolicyId == policyId).SingleOrDefault();
                        if (answer != null)
                        {
                            if (!answer.PolicyAnswer && policyRequired)
                            {
                                allRight = false;
                            }
                        }
                        else if (answer == null && policyRequired)
                        {
                            allRight = false;
                        }
                        if (answer != null)
                        {
                            policyAnswers.Add(new PolicyForUserViewModel {
                                OldAccepted  = false,
                                PolicyTextId = policyId,
                                Accepted     = answer.PolicyAnswer,
                                AnswerDate   = DateTime.Now
                            });
                        }
                    }
                    if (!allRight)
                    {
                        throw new SecurityException(T("User has to accept policies!").Text);
                    }
                }
                var registrationErrors = new List <string>();
                if (ValidateRegistration(userRegistrationParams.Username, userRegistrationParams.Email,
                                         userRegistrationParams.Password, userRegistrationParams.ConfirmPassword, out registrationErrors))
                {
                    var createdUser = _membershipService.CreateUser(new CreateUserParams(
                                                                        userRegistrationParams.Username,
                                                                        userRegistrationParams.Password,
                                                                        userRegistrationParams.Email,
                                                                        userRegistrationParams.PasswordQuestion,
                                                                        userRegistrationParams.PasswordAnswer,
                                                                        (RegistrationSettings.UsersAreModerated == false) && (RegistrationSettings.UsersMustValidateEmail == false),
                                                                        false
                                                                        ));
                    // _membershipService.CreateUser may return null and tell nothing about why it failed to create the user
                    // if the Creating user event handlers set the flag to cancel user creation.
                    if (createdUser == null)
                    {
                        throw new SecurityException(T("User registration failed.").Text);
                    }
                    // here user was created
                    var favCulture = createdUser.As <FavoriteCulturePart>();
                    if (favCulture != null)
                    {
                        var culture = _commonsServices.ListCultures().SingleOrDefault(x => x.Culture.Equals(userRegistrationParams.Culture));
                        if (culture != null)
                        {
                            favCulture.Culture_Id = culture.Id;
                        }
                        else
                        {
                            // usa la culture di default del sito
                            favCulture.Culture_Id = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture()).Id;
                        }
                    }
                    if ((RegistrationSettings.UsersAreModerated == false) && (RegistrationSettings.UsersMustValidateEmail == false))
                    {
                        _userEventHandler.LoggingIn(userRegistrationParams.Username, userRegistrationParams.Password);
                        _authenticationService.SignIn(createdUser, userRegistrationParams.CreatePersistentCookie);
                        // solleva l'evento LoggedIn sull'utente
                        _userEventHandler.LoggedIn(createdUser);
                    }

                    // [HS] BEGIN: Whe have to save the PoliciesAnswers cookie and persist answers on the DB after Login/SignIn events because during Login/Signin events database is not updated yet and those events override cookie in an unconsistent way.
                    if (_utilsServices.FeatureIsEnabled("Laser.Orchard.Policy") && UserRegistrationExtensionsSettings.IncludePendingPolicy == Policy.IncludePendingPolicyOptions.Yes)
                    {
                        _policyServices.PolicyForUserMassiveUpdate(policyAnswers, createdUser);
                    }
                    // [HS] END

                    if (RegistrationSettings.UsersMustValidateEmail)
                    {
                        // send challenge e-mail
                        var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
                        if (string.IsNullOrWhiteSpace(siteUrl))
                        {
                            siteUrl = HttpContext.Current.Request.ToRootUrlString();
                        }
                        UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                        _userService.SendChallengeEmail(createdUser, nonce => urlHelper.MakeAbsolute(urlHelper.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
                    }
                }
                else
                {
                    throw new SecurityException(String.Join(", ", registrationErrors));
                }
            }
            else
            {
                throw new SecurityException(T("User cannot register due to Site settings").Text);
            }
        }
        public ActionResult Register(UserRegistrationViewModel viewModel, string returnUrl = null)
        {
            var membershipSettings = membershipService.GetSettings();

            // ensure users can register
            if (!membershipSettings.UsersCanRegister)
            {
                return(HttpNotFound());
            }

            if (!ModelState.IsValid)
            {
                return(new ShapeResult(this, CreateRegisterShape(viewModel, membershipSettings)));
            }

            // Generate a username from username + random 8 characters this will be useful for searching later
            var username = $"{viewModel.FirstName.Trim()}-{RandomHelper.GenerateRandomCharacters(8)}";

            if (ValidateRegistration(username, viewModel.Email, viewModel.Password, viewModel.ConfirmPassword))
            {
                // Attempt to register the user
                // No need to report this to IUserEventHandler because _membershipService does that for us
                var user = membershipService.CreateUser(
                    new CreateUserParams(
                        username,
                        viewModel.Password,
                        viewModel.Email,
                        null,
                        null,
                        false
                        )
                    );

                if (user != null)
                {
                    UpdateUserProfile(user, viewModel);
                    TempData["Email"] = viewModel.Email;

                    if (user.As <UserPart>().EmailStatus == UserStatus.Pending)
                    {
                        var siteUrl = orchardService.WorkContext.CurrentSite.BaseUrl;
                        if (string.IsNullOrWhiteSpace(siteUrl))
                        {
                            siteUrl = HttpContext.Request.ToRootUrlString();
                        }

                        // To make it available in an email template without changing Orchard.User core project
                        HttpContext.Items["userProfilePart"] = user.As <BasicUserProfilePart>();

                        userService.SendChallengeEmail(
                            user.As <UserPart>(),
                            nonce => Url.MakeAbsolute(
                                Url.Action("ChallengeEmail",
                                           "Account",
                                           new { Area = "Orchard.Users", nonce }),
                                siteUrl
                                )
                            );

                        userEventHandler.SentChallengeEmail(user);
                        return(RedirectToAction(
                                   nameof(OrchardAccountController.ChallengeEmailSent),
                                   "Account",
                                   new { ReturnUrl = returnUrl, Area = "Orchard.Users" }
                                   ));
                    }

                    if (user.As <UserPart>().RegistrationStatus == UserStatus.Pending)
                    {
                        return(RedirectToAction(
                                   nameof(OrchardAccountController.RegistrationPending),
                                   "Account",
                                   new { ReturnUrl = returnUrl, Area = "Orchard.Users" }
                                   ));
                    }

                    userEventHandler.LoggingIn(username, viewModel.Password);
                    // Force log in user
                    authenticationService.SignIn(user, false /* createPersistentCookie */);
                    userEventHandler.LoggedIn(user);
                    return(this.RedirectLocal(returnUrl));
                }

                ModelState.AddModelError(
                    "_FORM",
                    T(ErrorCodeToString(/*createStatus*/ MembershipCreateStatus.ProviderError))
                    );
            }

            // If we got this far, something failed, redisplay form
            return(new ShapeResult(this, CreateRegisterShape(viewModel, membershipSettings)));
        }