Esempio n. 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));
        }
Esempio n. 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"));
        }
Esempio n. 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));
        }
        public ActionResult Index(string userName, string returnUrl = null)
        {
            var workContext = _workContextAccessor.GetContext();

            if (!PermissionService.IsSwitchUserAllowed(workContext))
            {
                return(new HttpUnauthorizedResult());
            }

            var user = _membershipService.GetUser(userName);

            if (user == null)
            {
                return(new HttpUnauthorizedResult());
            }

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

            returnUrl = "~/Admin/";
            //if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/Admin/";
            //if(_workContextAccessor.HttpContext.Request.IsLocal)
            //    return this.RedirectLocal(returnUrl);

            // regirect with new session cookie for init session flag, that allows to user has a user combo
            var redirectId = Guid.NewGuid().ToString();

            workContext.HttpContext.Application.Add(redirectId, "Ok");
            return(this.RedirectToAction("CompleteSwitch", new { RedirectId = redirectId, ReturnUrl = returnUrl }));
        }
Esempio n. 6
0
        public Response Post(JObject message)
        {
            var uuid = GetUUIDFromHeader();

            if (string.IsNullOrWhiteSpace(uuid))
            {
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }
            NonceLoginMessage msgObj;

            try {
                msgObj = message.ToObject <NonceLoginMessage>();
            } catch (Exception) {
                return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
            }

            if (msgObj != null)
            {
                var data = new Dictionary <string, string>();
                data.Add("uuid", uuid);

                var iuser = _nonceService.UserFromNonce(msgObj.Nonce, data);
                if (iuser != null)
                {
                    // log the user in
                    var user = iuser as UserPart;
                    _authenticationService.SignIn(user, true);
                    _userEventHandler.LoggedIn(user);
                    return(_utilsServices.GetUserResponse("", _identityProviders));
                }
            }

            return(_utilsServices.GetResponse(ResponseType.UnAuthorized));
        }
Esempio n. 7
0
        public HttpResponseMessage Login(Login login)
        {
            IUser user = _orchardServices.WorkContext.CurrentUser;

            ApplicationRecord apprecord = _applicationsService.GetApplicationByKey(login.ApiKey);

            if (apprecord == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, new uError("Not Found", 404)));
            }

            if (user != null)
            {
                IUser newUser = ValidateLogOn(login);
                if (newUser != null && newUser.Id == user.Id)
                {
                    Contrib.Foundation.UserProfile.OData.Profile profile = new Contrib.Foundation.UserProfile.OData.Profile(user, Request, _loginsService.GetHash(user.As <UserProfilePart>(), apprecord));
                    _orchardServices.WorkContext.HttpContext.Session["doticca_aid"] = apprecord.Id;
                    return(Request.CreateResponse(HttpStatusCode.OK, profile));
                }
                else
                {
                    LogOut();
                }
            }
            user = ValidateLogOn(login);
            if (user != null)
            {
                UserProfilePart profilePart = user.As <UserProfilePart>(); //_profileService.Get(user).As<UserProfilePart>();
                _profileService.CreateUserForApplicationRecord(profilePart, apprecord);
                _authenticationService.SignIn(user, false);
                _userEventHandler.LoggedIn(user);
                string newHash = login.Hash;
                if (string.IsNullOrWhiteSpace(newHash))
                {
                    newHash = _loginsService.CreateHash(profilePart, apprecord);
                }

                Contrib.Foundation.UserProfile.OData.Profile profile = new Contrib.Foundation.UserProfile.OData.Profile(user, Request, newHash);
                _orchardServices.WorkContext.HttpContext.Session["doticca_aid"] = apprecord.Id;
                return(Request.CreateResponse(HttpStatusCode.OK, profile));
            }
            _orchardServices.WorkContext.HttpContext.Session.Remove("doticca_aid");
            return(Request.CreateResponse(HttpStatusCode.Unauthorized, new uError("User not authorized", 401)));
        }
        public ActionResult ValidateTFALogin(string tfacode, string returnUrl)
        {
            var  user       = (IUser)Session["user"];
            var  userTFA    = user.As <TwoFactorAuthenticationPart>();
            bool rememberMe = Session["rememberMe"] != null ? (bool)Session["rememberMe"] : false;

            ValidateTFA(user, tfacode);
            if (!ModelState.IsValid)
            {
                var shape = _orchardServices.New.LogOn().Title(T("Log On").Text);
                return(new ShapeResult(this, shape));
            }

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

            return(this.RedirectLocal(returnUrl));
        }
Esempio n. 9
0
        private void UserMergeAndSignIn(
            IUser masterUser, AuthenticationResult result, string returnUrl, bool createPersistentCookie = false)
        {
            // If the current user is logged in or settings ask for a user merge and we found a User with the same email
            // create or merge accounts
            _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId,
                                                              masterUser, result.ExtraData);

            _notifier.Information(T("Your {0} account has been attached to your local account.", result.Provider));

            // Handle LoggedIn Event
            var authenticatedUser = _authenticationService.GetAuthenticatedUser();

            if (authenticatedUser == null)
            {
                _authenticationService.SignIn(masterUser, createPersistentCookie);
                _userEventHandler.LoggedIn(masterUser);
                // The LoggedIn event is invoked here, because if authenticateUser != null, then it means the user
                // had already logged in some other time
            }
        }
Esempio n. 10
0
        public bool Login(string providerUserId, bool createPersistentCookie)
        {
            string userName = _orchardOpenAuthDataProvider.GetUserNameFromOpenAuth(ProviderName, providerUserId);

            if (string.IsNullOrWhiteSpace(userName))
            {
                return(false);
            }

            // Orchard's "normal" LogOn process would have the LoggingIn event raised here
            // The parameters for that are Username and Password. Here we do not have the latter

            // Before SignIn, the normal Orchard process attempts to validate the information. In
            // case the validation fails, it raises the LoginFailed event. That has the same parameters
            // as the LoggingIn event, and we still don't have the password to pass along.

            // If GetUser(userName) != null, and we perform SignIn, the next call should in general return the
            // same IUser returned by GetUser(userName), unless that user has been disabled or some other way
            // disallowed from actually signing in. Note that, using the default Orchard.Users IMembershipService
            // along with the default FormsAuthenticationService, neither GetUser(userName) nor SignIn(user, flag)
            // validate that condition: as a consequence, here we could be signing in a disabled user.
            var user = _membershipService.GetUser(userName);

            // if the user is valid, sign them in
            if (user != null)
            {
                // Since this feature depends on Orchard.Users, we are allowed to use the same definition of "Approved"
                // user that is used there.
                var userPart = user.As <UserPart>();
                if (userPart != null &&
                    userPart.EmailStatus == UserStatus.Approved &&
                    userPart.RegistrationStatus == UserStatus.Approved)
                {
                    _authenticationService.SignIn(user, createPersistentCookie);
                }
            }

            // If we have done the SignIn above, this will return user. Otherwise it should return null, unless we
            // are in a weird condition where we are already authenticated and are trying to "add" an OAuth authentication.
            var authenticatedUser = _authenticationService.GetAuthenticatedUser();

            if (authenticatedUser == null)
            {
                return(false);
            }
            else
            {
                // Login was successful using the OAuth provider, so we can fire the LoggedIn event
                _userEventHandler.LoggedIn(authenticatedUser);
                return(true);
            }
        }
Esempio n. 11
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"));
        }
Esempio n. 12
0
        public async Task <ActionResult> Connect(FacebookLogInRequest request, FormCollection form)
        {
            // TODO better error response to client to show why we have error
            ValidateFacebookAccessToken(request);
            var user = GetUser(request);

            if (user == null)
            {
                user = CreateNewUser(request);
            }

            // Always update profile if user make a request to connect because we have chance to get new Facebook information
            user = await UpdateFacebookUserPart(request, user);

            // Server side sign in
            auth.SignIn(user, true);
            // Update last log in, to make valid cookie to client side
            userEventHandler.LoggedIn(user);
            return(new JsonResult());
        }
Esempio n. 13
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));
        }
Esempio n. 14
0
        public ActionResult ExternalLogOn(string returnUrl, bool createPersistentCookie = false)
        {
            AuthenticationResult result = _orchardOpenAuthWebSecurity.VerifyAuthentication(Url.OpenAuthLogOn(returnUrl));

            if (!result.IsSuccessful)
            {
                _notifier.Error(T("Your authentication request failed."));
                return(new RedirectResult(Url.LogOn(returnUrl)));
            }

            if (_orchardOpenAuthWebSecurity.Login(result.Provider, result.ProviderUserId))
            {
                _notifier.Information(T("You have been logged using your {0} account.", result.Provider));

                return(this.RedirectLocal(returnUrl));
            }

            // At this point, login using the OpenAuth provider failed, meaning that we could not find a match
            // between the information from the provider and Orchard's users.

            // Get additional UserData
            if (result.ExtraData.ContainsKey("accesstoken"))
            {
                result = _openAuthClientProvider.GetUserData(result.Provider, result, result.ExtraData["accesstoken"]);
            }
            else
            {
                result = _openAuthClientProvider.GetUserData(result.Provider, result, "");
            }
            // _openAuthClientProvider.GetUserData(params) may return null if there is no configuration for a provider
            // with the given name.
            if (result == null)
            {
                // handle this condition and exit the method
                _notifier.Error(T("Your authentication request failed."));
                return(new RedirectResult(Url.LogOn(returnUrl)));
            }

            // _openAuthClientProvider.NormalizeData(params) may return null if there is no configuration for a provider
            // with the given name. If result != null, that is not the case, because in that condition GetUserData(params)
            // would return null, and we would have already exited the method.
            var userParams = _openAuthClientProvider.NormalizeData(result.Provider, new OpenAuthCreateUserParams(result.UserName,
                                                                                                                 result.Provider,
                                                                                                                 result.ProviderUserId,
                                                                                                                 result.ExtraData));

            var temporaryUser = _openAuthMembershipServices.CreateTemporaryUser(userParams);

            // In what condition can GetAuthenticatedUser() not be null? To reach this code, _orchardOpenAuthWebSecurity.Login(params)
            // must have returned false. That happens if there was no record for the combination Provider/ProviderUserId, or if
            // GetAuthenticatedUser() returned null in it. In the latter case, it should still return null. The former case means
            // we are trying to login with an OAuth provider and it's the first time we are calling it for this user, but we are
            // also already authenticated in some other way. This only makes sense in a situation where, as authenticated users,
            // we are allowed to add information from OAuth providers to our account: Users/Account/LogOn, if the user is authenticated,
            // redirects to the homepage, and does not give an option to go and login again using OAuth.
            var masterUser = _authenticationService.GetAuthenticatedUser()
                             ?? _orchardOpenAuthWebSecurity.GetClosestMergeableKnownUser(temporaryUser);

            // The authenticated User or depending from settings the first created user with the same e-mail

            if (masterUser != null)
            {
                // If the current user is logged in or settings ask for a user merge and we found a User with the same email
                // create or merge accounts
                _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId,
                                                                  masterUser, result.ExtraData);

                _notifier.Information(T("Your {0} account has been attached to your local account.", result.Provider));

                if (_authenticationService.GetAuthenticatedUser() != null)   // if the user was already logged in
                // here masterUser == _authenticationService.GetAuthenticatedUser()
                {
                    return(this.RedirectLocal(returnUrl));
                }
            }

            if (_openAuthMembershipServices.CanRegister() && masterUser == null)
            {
                // User can register and there is not a user with the same email
                var createUserParams = new OpenAuthCreateUserParams(result.UserName,
                                                                    result.Provider,
                                                                    result.ProviderUserId,
                                                                    result.ExtraData);
                createUserParams = _openAuthClientProvider.NormalizeData(result.Provider, createUserParams);
                // Creating the user here calls the IMembershipService, that will take care of invoking the user events
                var newUser = _openAuthMembershipServices.CreateUser(createUserParams);
                // newUser may be null here, if creation of a new user fails.
                // TODO: we should elsewhere add an UserEventHandler that in the Creating event handles the case where
                // here we are trying to create a user with the same Username or Email as an existing one. That would simply
                // use IUserService.VerifyUnicity(username, email). However this may break things for our older tenants.
                if (newUser != null)
                {
                    // CreateOrUpdateAccount causes specific OpenAuth events to fire
                    _orchardOpenAuthWebSecurity.CreateOrUpdateAccount(result.Provider,
                                                                      result.ProviderUserId,
                                                                      newUser,
                                                                      result.ExtraData);
                    // The default implementation of IOpendAuthMembershipService creates an approved user.
                    // The events specific to open auth give points to attach handlers where the UserProviderRecord
                    // is populated correctly.

                    // We created the user and are going to sign them in, so we should fire off the related events.
                    // We cannot really invoke the LoggingIn event, because we do not have the password, but we can invoke
                    // the LoggedIn event later.
                    _authenticationService.SignIn(newUser, createPersistentCookie);

                    _notifier.Information(
                        T("You have been logged in using your {0} account. We have created a local account for you with the name '{1}'", result.Provider, newUser.UserName));
                    _userEventHandler.LoggedIn(newUser);
                }
                else
                {
                    _notifier.Error(T("Your authentication request failed."));
                }

                return(this.RedirectLocal(returnUrl));
            }
            else if (masterUser != null)
            {
                _authenticationService.SignIn(masterUser, createPersistentCookie);
                _userEventHandler.LoggedIn(masterUser);
                _notifier.Information(T("You have been logged in using your {0} account.", result.Provider));
                return(this.RedirectLocal(returnUrl));
            }

            // We are in the case which we cannot creates new accounts, we have no user to merge, the user is not logged in
            // so we ask to user to login to merge accounts
            string loginData = _orchardOpenAuthWebSecurity.SerializeProviderUserId(result.Provider,
                                                                                   result.ProviderUserId);

            ViewBag.ProviderDisplayName = _orchardOpenAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;

            // the LogOn Helper here is not doing any validaiton on the stuff it's putting in query string, so it
            // may end up having forbidden character sequences.
            return(new RedirectResult(Url.LogOn(returnUrl, result.UserName, loginData)));
        }
Esempio n. 15
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)));
        }