Exemple #1
0
        /// <summary>
        /// Authenticate user by passed parameters
        /// </summary>
        /// <param name="parameters">External authentication parameters</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        public virtual async Task <IActionResult> Authenticate(ExternalAuthParam parameters, string returnUrl = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (!AuthenticationProviderIsAvailable(parameters.ProviderSystemName))
            {
                return(Error(new[] { "External authentication method cannot be loaded" }));
            }

            //get current logged-in user
            var currentLoggedInUser = await _groupService.IsRegistered(_workContext.CurrentCustomer) ? _workContext.CurrentCustomer : null;

            //authenticate associated user if already exists
            var associatedUser = await GetCustomer(parameters);

            if (associatedUser != null)
            {
                return(await AuthenticateExistingUser(associatedUser, currentLoggedInUser, returnUrl));
            }

            //or associate and authenticate new user
            return(await AuthenticateNewUser(currentLoggedInUser, parameters, returnUrl));
        }
 public RegisteredByExternalMethodEventHandler(
     Customer customer,
     ExternalAuthParam parameters,
     RegistrationResult registrationResult)
 {
     Customer = customer;
     AuthenticationParameters = parameters;
     RegistrationResult       = registrationResult;
 }
Exemple #3
0
        /// <summary>
        /// Get the particular user with specified parameters
        /// </summary>
        /// <param name="parameters">External authentication parameters</param>
        /// <returns>Customer</returns>
        public virtual async Task <Customer> GetCustomer(ExternalAuthParam parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            var associationRecord = await _externalAuthenticationRecordRepository.Table.FirstOrDefaultAsync(record =>
                                                                                                            record.ExternalIdentifier.Equals(parameters.Identifier) && record.ProviderSystemName.Equals(parameters.ProviderSystemName));

            if (associationRecord == null)
            {
                return(null);
            }

            return(await _customerService.GetCustomerById(associationRecord.CustomerId));
        }
Exemple #4
0
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual async Task <IActionResult> RegisterNewUser(ExternalAuthParam parameters, string returnUrl)
        {
            var approved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                           _customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation;

            //create registration request
            var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,
                                                              parameters.Email, parameters.Email,
                                                              CommonHelper.GenerateRandomDigitCode(20),
                                                              PasswordFormat.Hashed,
                                                              _workContext.CurrentStore.Id,
                                                              approved);

            //whether registration request has been completed successfully
            var registrationResult = await _customerManagerService.RegisterCustomer(registrationRequest);

            if (!registrationResult.Success)
            {
                return(Error(registrationResult.Errors));
            }

            //allow to save other customer values by consuming this event
            await _mediator.Publish(new RegisteredByExternalMethodEventHandler(_workContext.CurrentCustomer, parameters, registrationResult));

            //raise vustomer registered event
            await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));

            //associate external account with registered user
            await AssociateCustomer(_workContext.CurrentCustomer, parameters);

            //authenticate
            if (approved)
            {
                await _authenticationService.SignIn(_workContext.CurrentCustomer, false);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            return(Error(new[] { "Error on registration" }));
        }
Exemple #5
0
        /// <summary>
        /// Accociate external account with customer
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="parameters">External authentication parameters</param>
        public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam parameters)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var externalAuthenticationRecord = new ExternalAuthentication
            {
                CustomerId                = customer.Id,
                Email                     = parameters.Email,
                ExternalIdentifier        = parameters.Identifier,
                ExternalDisplayIdentifier = parameters.Name,
                OAuthAccessToken          = parameters.AccessToken,
                ProviderSystemName        = parameters.ProviderSystemName,
            };

            await _externalAuthenticationRecordRepository.InsertAsync(externalAuthenticationRecord);
        }
        public async Task <IActionResult> FacebookLoginCallback(string returnUrl)
        {
            //authenticate Facebook user
            var authenticateResult = await HttpContext.AuthenticateAsync(FacebookDefaults.AuthenticationScheme);

            if (!authenticateResult.Succeeded || !authenticateResult.Principal.Claims.Any())
            {
                return(RedirectToRoute("Login"));
            }

            //create external authentication parameters
            var authenticationParameters = new ExternalAuthParam {
                ProviderSystemName = FacebookAuthenticationDefaults.ProviderSystemName,
                AccessToken        = await HttpContext.GetTokenAsync(FacebookDefaults.AuthenticationScheme, "access_token"),
                Email      = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Email)?.Value,
                Identifier = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value,
                Name       = authenticateResult.Principal.FindFirst(claim => claim.Type == ClaimTypes.Name)?.Value,
                Claims     = authenticateResult.Principal.Claims.ToList()
            };

            //authenticate Grand user
            return(await _externalAuthenticationService.Authenticate(authenticationParameters, returnUrl));
        }
Exemple #7
0
        /// <summary>
        /// Authenticate current user and associate new external account with user
        /// </summary>
        /// <param name="currentLoggedInUser">Current logged-in user</param>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>Result of an authentication</returns>
        protected virtual async Task <IActionResult> AuthenticateNewUser(Customer currentLoggedInUser, ExternalAuthParam parameters, string returnUrl)
        {
            //associate external account with logged-in user
            if (currentLoggedInUser != null)
            {
                await AssociateCustomer(currentLoggedInUser, parameters);

                if (string.IsNullOrEmpty(returnUrl))
                {
                    return(new RedirectToRouteResult("HomePage", new { area = "" }));
                }
                return(new RedirectResult(returnUrl));
            }

            //or try to register new user
            if (_customerSettings.UserRegistrationType != UserRegistrationType.Disabled)
            {
                return(await RegisterNewUser(parameters, returnUrl));
            }

            //registration is disabled
            return(Error(new[] { "Registration is disabled" }));
        }