Ejemplo n.º 1
0
        public async Task <IActionResult> ExternalLoginCallback(ExternalLoginCallbackViewModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new ValidationException(ModelState.GetValidationString());
            }

            if (model.RemoteError != null)
            {
                string error = $"Error from external login: {model.RemoteError}";
                logger.LogError(error);
                return(Redirect($"{model.ErrorUrl}?error=external-login&message={WebUtility.UrlEncode(error)}&returnUrl={model.ReturnUrl}"));
            }

            ExternalLoginInfo?info = await signInManager.GetExternalLoginInfoAsync().ConfigureAwait(false);

            if (info == null)
            {
                string error = $"Error from external login: unable to retrieve user data";
                logger.LogError(error);
                return(Redirect($"{model.ErrorUrl}?error=external-userdata&message={WebUtility.UrlEncode(error)}&returnUrl={model.ReturnUrl}"));
            }

            // Sign in the user with this external login provider if the user already has a login.
            SignInResult result = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false).ConfigureAwait(false);

            if (result.Succeeded)
            {
                logger.LogInformation("User logged in with {0} provider.", info.LoginProvider);
                return(Redirect(model.ReturnUrl));
            }
            else if (result.IsLockedOut)
            {
                logger.LogInformation("User is locked out");
                return(Redirect($"{model.ErrorUrl}?error=lockout&message={WebUtility.UrlEncode("User is locked out")}&returnUrl={model.ReturnUrl}"));
            }

            // If the user can't login with the external login, create a new account or link one
            string             email         = info.Principal.FindFirstValue(ClaimTypes.Email);
            ExternalUserResult newUserResult = await userService.CreateOrAddExternalToUser(email, info).ConfigureAwait(false);

            if (newUserResult.Result.Succeeded)
            {
                if (newUserResult.AddedUser)
                {
                    return(Redirect(model.FinishRegistrationUrl));
                }
                else
                {
                    return(Redirect(model.ReturnUrl));
                }
            }
            else
            {
                string error = string.Join(", ", newUserResult.Result.Errors.Select(e => e.Description));
                logger.LogError(error);
                return(Redirect($"{model.ErrorUrl}?error=external-login-create&message={WebUtility.UrlEncode(error)}&returnUrl={model.ReturnUrl}"));
            }
        }
Ejemplo n.º 2
0
 public static CustomerRegisterCommand ToCommand(this ExternalLoginCallbackViewModel model, string registerIp, long systemNumericalOrder)
 {
     if (model == null)
     {
         return(null);
     }
     return(new CustomerRegisterCommand(SystemDefine.DefaultVersion)
     {
         Email = model.Email,
         FullName = model.FullName,
         Password = string.Empty,
         Birthday = model.BirthdayValue.GetValueOrDefault(),
         Gender = model.Gender,
         Mobile = model.Mobile,
         RegisterIp = registerIp,
         SystemNumericalOrder = systemNumericalOrder
     });
 }
Ejemplo n.º 3
0
        public async Task <ExternalLoginCallbackViewModel> ExternalLoginCallback()
        {
            try
            {
                var page = await base.InitPage();

                ExternalLoginCallbackViewModel model = new ExternalLoginCallbackViewModel(page);
                var user = _currentContext.HttpContext.User;
                if (user == null || !user.Identities.Any(identity => identity.IsAuthenticated))
                {
                    model.AddMessage(ResourceKey.Account_ExternalLoginCallback_Fail);
                    model.Status = EnumDefine.CustomerExternalLoginCallbackStatusEnum.LoginFail;
                    return(model);
                }
                string name       = user.Identity.Name.Trim();
                var    identifier = user.FindFirst(p => p.Type == ClaimTypes.NameIdentifier)?.Value.Trim();
                var    email      = user.FindFirst(p => p.Type == ClaimTypes.Email)?.Value.Trim();
                model.FullName      = name;
                model.EmailOrMobile = email;
                model.Identifier    = identifier;
                var res = (EnumDefine.CutomerExternalLoginProviderEnum)Enum.Parse(typeof(EnumDefine.CutomerExternalLoginProviderEnum), user.Identity.AuthenticationType);
                model.LoginProvider = res;
                var customer = await _customerService.GetFromDbByEmailOrMobile(email);

                if (customer == null)
                {
                    model.Status = EnumDefine.CustomerExternalLoginCallbackStatusEnum.AccountNotExist;
                    long systemNumericalOrder = await _commonService.GetNextId(typeof(Customer));

                    var command = model.ToCommand(_currentContext.Ip, systemNumericalOrder);
                    var result  = await _customerService.SendCommand(command);

                    if (!result.IsSucess)
                    {
                        model.AddMessage(result.Message);
                    }
                    else
                    {
                        customer = await _customerService.GetFromDbByEmailOrMobile(email);

                        await _commonService.SetFlagRegisterSuccessAsync(result.ObjectId);
                        await Login(model.EmailOrMobile, false, customer);
                    }
                    return(model);
                }
                if (customer.CustomerExternalLogins != null && customer.CustomerExternalLogins.Any(p => p.LoginProvider == res && p.ProviderKey == model.Identifier))
                {
                    await Login(model.EmailOrMobile, false, customer);

                    model.Status = EnumDefine.CustomerExternalLoginCallbackStatusEnum.LoginSuccess;
                    return(model);
                }
                else
                {
                    await Logout();

                    model.Status = EnumDefine.CustomerExternalLoginCallbackStatusEnum.AccountIsExist;
                    await SendActiveCodeWhenAccountIsExist();

                    return(model);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                throw e;
            }
        }