Exemple #1
0
        public async Task <ActionResult> SignInCallback(string returnUrl)
        {
            // Extracts login info out of the external identity provided by the service
            ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            // If the external authentication fails, displays a view with appropriate information
            if (loginInfo == null)
            {
                return(View("ExternalAuthenticationFailure"));
            }

            // Attempts to sign in the user using the external login info
            SignInStatus result = await KenticoSignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            // Success occurs if the user already exists in the Xperience database and has signed in using the given external service
            case SignInStatus.Success:
                // Redirects to the original return URL
                return(RedirectToLocal(returnUrl));

            // The 'LockedOut' status occurs if the user exists in Xperience, but is not enabled
            case SignInStatus.LockedOut:
                // Returns a view informing the user about the locked account
                return(View("Lockout"));

            case SignInStatus.Failure:
            default:
                // Attempts to create a new user in Xperience if the authentication failed
                IdentityResult userCreation = await CreateExternalUser(loginInfo);

                // Attempts to sign in again with the new user created based on the external authentication data
                result = await KenticoSignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

                // Verifies that the user was created successfully and was able to sign in
                if (userCreation.Succeeded && result == SignInStatus.Success)
                {
                    // Redirects to the original return URL
                    return(RedirectToLocal(returnUrl));
                }

                // If the user creation was not successful, displays corresponding error messages
                foreach (string error in userCreation.Errors)
                {
                    ModelState.AddModelError(String.Empty, error);
                }
                return(View());

                // Optional extension:
                // Send the loginInfo data as a view model and create a form that allows adjustments of the user data.
                // Allows visitors to resolve errors such as conflicts with existing usernames in Xperience.
                // Then post the data to another action and attempt to create the user account again.
                // The action can access the original loginInfo using the AuthenticationManager.GetExternalLoginInfoAsync() method.
            }
        }
Exemple #2
0
        public async Task <ActionResult> Register(RegisterWithConsentViewModel model)
        {
            // Validates the received user data based on the view model
            if (!ModelState.IsValid)
            {
                model.ConsentShortText = consent.GetConsentText("en-US").ShortText;
                return(View("RegisterWithConsent", model));
            }

            // Prepares a new user entity using the posted registration data
            Kentico.Membership.User user = new User
            {
                UserName  = model.UserName,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Enabled   = true // Enables the new user directly
            };

            // Attempts to create the user in the Kentico database
            IdentityResult registerResult = IdentityResult.Failed();

            try
            {
                registerResult = await KenticoUserManager.CreateAsync(user, model.Password);
            }
            catch (Exception ex)
            {
                // Logs an error into the Kentico event log if the creation of the user fails
                eventLogService.LogException("MvcApplication", "UserRegistration", ex);
                ModelState.AddModelError(String.Empty, "Registration failed");
            }

            // If the registration was not successful, displays the registration form with an error message
            if (!registerResult.Succeeded)
            {
                foreach (string error in registerResult.Errors)
                {
                    ModelState.AddModelError(String.Empty, error);
                }

                model.ConsentShortText = consent.GetConsentText("en-US").ShortText;

                return(View("RegisterWithConsent", model));
            }

            // Creates a consent agreement if the consent checkbox was selected in the registration form
            if (model.ConsentIsAgreed)
            {
                // Gets the current contact
                var currentContact = ContactManagementContext.GetCurrentContact();

                // Creates an agreement for the specified consent and contact
                // Passes the UserInfo object of the new user as a parameter, which is used to map the user's values
                // to a new contact in cases where the contact parameter is null,
                // e.g. for visitors who have not given an agreement with the site's tracking consent.
                formConsentAgreementService.Agree(currentContact, consent, userInfoProvider.Get(user.Id));
            }

            // If the registration was successful, signs in the user and redirects to a different action
            await KenticoSignInManager.SignInAsync(user, true, false);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            // Validates the received user data based on the view model
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Prepares a new user entity using the posted registration data
            Kentico.Membership.User user = new User
            {
                UserName  = model.UserName,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Enabled   = true // Enables the new user directly
            };

            // Attempts to create the user in the Xperience database
            IdentityResult registerResult = IdentityResult.Failed();

            try
            {
                registerResult = await KenticoUserManager.CreateAsync(user, model.Password);
            }
            catch (Exception ex)
            {
                // Logs an error into the Xperience event log if the creation of the user fails
                eventLogService.LogException("MvcApplication", "UserRegistration", ex);
                ModelState.AddModelError(String.Empty, "Registration failed");
            }

            // If the registration was successful, signs in the user and redirects to a different action
            if (registerResult.Succeeded)
            {
                var signInResult = await KenticoSignInManager.PasswordSignInAsync(model.UserName, model.Password, true, false);

                if (signInResult == SignInStatus.LockedOut)
                {
                    // Checks if the 'Registration requires administrator's approval' settings is enabled
                    if (user.WaitingForApproval)
                    {
                        // Notifies the user that their account is pending administrator approval
                        var message = new IdentityMessage()
                        {
                            Destination = model.Email,
                            Subject     = "Account approval pending",
                            Body        = "You account is pending administrator approval"
                        };

                        await KenticoUserManager.EmailService.SendAsync(message);
                    }

                    return(RedirectToAction("RequireConfirmedAccount"));
                }

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

            // If the registration was not successful, displays the registration form with an error message
            foreach (string error in registerResult.Errors)
            {
                ModelState.AddModelError(String.Empty, error);
            }
            return(View(model));
        }