コード例 #1
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
                return(View(nameof(Login)));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);

            if (user != null)
            {
                await _signInManager.SignInAsync(user, isPersistent : false, authenticationMethod : info.LoginProvider);

                if (!User.IsInRole("inactive"))
                {
                    return(RedirectToAction("Index", "Home"));
                }
                await _signInManager.SignOutAsync();

                return(View("InActiveAccount"));
            }

            // if no external login login, but email is already existed, create an external login
            var email    = info.Principal.FindFirstValue(ClaimTypes.Email);
            var userInfo = await _userInfoManager.FindUserByEmailAsync(email);

            if (userInfo != null)
            {
                var addLoginResult = await _userManager.AddLoginAsync(userInfo, info);

                if (addLoginResult.Succeeded)
                {
                    var claimResult = await _userManager.AddClaimsAsync(userInfo,
                                                                        new Claim[]
                    {
                        new Claim(ClaimTypes.Email, userInfo.Email), new Claim(ClaimTypes.Name, userInfo.UserName)
                    });

                    if (claimResult.Succeeded)
                    {
                        if (await _userManager.IsInRoleAsync(userInfo, "inactive"))
                        {
                            await _signInManager.SignOutAsync();

                            return(View("InActiveAccount", userInfo));
                        }
                        await _signInManager.SignInAsync(userInfo, isPersistent : false,
                                                         authenticationMethod : info.LoginProvider);

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                return(RedirectToAction(nameof(Login)));
            }
            return(View("NoAccount", email));
        }