Пример #1
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Выполнение входа пользователя посредством данного внешнего поставщика входа, если у пользователя уже есть имя входа
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // Если у пользователя нет учетной записи, то ему предлагается создать ее
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #2
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #3
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // 若使用者已經有登入資料,請使用此外部登入提供者登入使用者
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // 若使用者沒有帳戶,請提示使用者建立帳戶
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #4
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Si el usuario ya tiene un inicio de sesión, iniciar sesión del usuario con este proveedor de inicio de sesión externo
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // Si el usuario no tiene ninguna cuenta, solicitar que cree una
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #5
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // ユーザーが既にログインを持っている場合、この外部ログイン プロバイダーを使用してユーザーをサインインします
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // ユーザーがアカウントを持っていない場合、ユーザーにアカウントを作成するよう求めます
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #6
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Benutzer mit diesem externen Anmeldeanbieter anmelden, wenn der Benutzer bereits eine Anmeldung besitzt
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // Benutzer auffordern, ein Konto zu erstellen, wenn er kein Konto besitzt
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #7
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            //var user = await UserManager.FindAsync(loginInfo.Login);
            //if (user == null)
            //{
            //    // Register the user. The user must be added to two tables using the built-in methods.
            //    //var email = loginInfo.DefaultUserName.ToLower().Replace("mydomain\\", "") + "@mydomain.org";  // The email was null on loginInfo, so using the DefaultUserName to build one
            //    var email = loginInfo.Email;
            //    var appUser = new AppUser { UserName = email, Email = email };
            //    var identityResult = await UserManager.CreateAsync(appUser);  // Adds user to AspNetUsers table
            //    if (identityResult.Succeeded)
            //    {
            //        identityResult = await UserManager.AddLoginAsync(appUser.Id, loginInfo.Login);    // Adds user to AspNetUserLogins
            //        if (!identityResult.Succeeded)
            //        {
            //            //await SignInManager.SignInAsync(appUser, isPersistent: false, rememberBrowser: false);
            //            return RedirectToLocal(returnUrl);
            //        }
            //    }
            //    else
            //    {

            //    }
            //}

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            //case SignInStatus.Failure:
            //    return View("ExternalLoginFailure");
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #8
0
        public async Task <ActionResult> ExternalLoginCallback(string ReturnUrl)
        {
            String Name;
            var    loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }
            Name = String.IsNullOrEmpty(loginInfo.DefaultUserName) ? loginInfo.Email : loginInfo.DefaultUserName;
            if (loginInfo.Login.LoginProvider == "Google")
            {
                var externalIdentity = AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                var lastNameClaim    = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
                var givenNameClaim   = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);

                Name = givenNameClaim.Value + " " + lastNameClaim.Value;
            }

            // Выполнение входа пользователя посредством данного внешнего поставщика входа, если у пользователя уже есть имя входа
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                Data.Save_log.Log("Выполнен вход пользователем посредством данного " + loginInfo.Email + " логина в " + loginInfo.Login.LoginProvider, "Login");
                return(RedirectToLocal(ReturnUrl));

            case SignInStatus.LockedOut:
                Data.Save_log.Log("Вход пользователем " + loginInfo.Email + " невозможен. Пользователь заблокировани в " + loginInfo.Login.LoginProvider, "Login");
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                Data.Save_log.Log("Запрос верификации " + loginInfo.Email + " " + loginInfo.Login.LoginProvider, "Login");
                return(RedirectToAction("SendCode", new { ReturnUrl = ReturnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // Если у пользователя нет учетной записи, то ему предлагается создать ее
                ViewBag.ReturnUrl     = ReturnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation",
                            new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email,
                    UserName = String.IsNullOrEmpty(loginInfo.DefaultUserName) ? loginInfo.Email : loginInfo.DefaultUserName,
                    Name = Name
                }
                            ));
            }
        }
Пример #9
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

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

            var user = await userManager.FindAsync(loginInfo.Login);

            // Creates a log entry if an external login exists and the user is already logged on this login provider
            var result = await signInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                var userext = userManager.FindByEmailAsync(user.Email);
                await SignInAsync(userext.Result, false);

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account request that an account is created

                var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(
                    DefaultAuthenticationTypes.ExternalCookie);
                var email = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:email")
                            .Value;
                var firstName = externalIdentity.Result.Claims
                                .FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value;
                var lastName = externalIdentity.Result.Claims
                               .FirstOrDefault(c => c.Type == "urn:facebook:last_name").Value;

                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View(nameof(ExternalLoginConfirmation),
                            new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email, LastName = lastName,
                    Name = firstName
                }));
            }
        }
Пример #10
0
        public async Task <RedirectActionResult> SigninCallback([FromUri] SigninCallbackRequestParams requestParams)
        {
            /**
             * Could create a session in SamlOwin.Identity.ApplicationSignInManager.CreateUserIdentityAsync
             * and have it checked and deleted on soap logout
             */

            var returnUrl       = requestParams?.ReturnUrl ?? $"{BaseUrl}/en/";
            var errorUrl        = requestParams?.ErrorUrl ?? $"{BaseUrl}/en/bad-request";
            var unauthorizedUrl = requestParams?.UnauthorizedUrl ?? $"{BaseUrl}/en/unauthorized";
            var samlError       = requestParams?.Error;

            if (samlError != null)
            {
                return(new RedirectActionResult($"{errorUrl}?error=SamlSignInError"));
            }

            try
            {
                // refreshing url will be null
                var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (loginInfo == null)
                {
                    return(new RedirectActionResult($"{errorUrl}?error=ExternalLoginInfo"));
                }

                // If IsPersistent property of AuthenticationProperties is set to false, then the cookie expiration time is set to Session.
                var signInStatus = await _signInManager.ExternalSignInAsync(loginInfo, true);

                if (signInStatus != SignInStatus.Success)
                {
                    return(new RedirectActionResult($"{unauthorizedUrl}?error={signInStatus:G}"));
                }

                // required for saml2 single sign out
                AuthenticationManager.User.AddIdentity(loginInfo.ExternalIdentity);

                GccfAuthorizationFilter.RegisterSession(loginInfo.ExternalIdentity);
            }
            catch (Exception e)
            {
                Log.Logger.Error(e, "");

                return(new RedirectActionResult($"{errorUrl}?error=Exception"));
            }

            return(new RedirectActionResult($"{returnUrl}#SignIn"));
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // grab the facebook token
                ViewBag.FaceBookAccessToken = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "FacebookAccessToken").Value;
                foreach (Claim claim in loginInfo.ExternalIdentity.Claims)
                {
                    // can iterate over claims;
                }
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation",
                            new ExternalLoginConfirmationViewModel
                {
                    Email = loginInfo.Email,
                    FaceBookName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:name").Value,
                    id = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:id").Value,
                    AccessToken = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "FacebookAccessToken").Value,
                }));

                // If the user does not have an account, then prompt the user to create an account
                //ViewBag.ReturnUrl = returnUrl;
                //ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                //return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            }
        }
Пример #12
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl, string invitationCode)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, false, (bool)ViewBag.Settings.TriggerLockoutOnFailedPassword);

            switch (result)
            {
            case SignInStatus.Success:
                return(await RedirectOnPostAuthenticate(returnUrl, invitationCode));

            case SignInStatus.LockedOut:
                AddErrors(ViewBag.IdentityErrors.UserLocked());
                return(View("Login", GetLoginViewModel(null, null, returnUrl, invitationCode)));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl      = returnUrl;
                ViewBag.InvitationCode = invitationCode;
                var contactId = ToContactId(await FindInvitationByCodeAsync(invitationCode));
                var email     = (contactId != null ? contactId.Name : null) ?? loginInfo.Email;
                var username  = loginInfo.Login.ProviderKey;

                return(await ExternalLoginConfirmation(username, email, returnUrl, invitationCode, loginInfo));
            }
        }
Пример #13
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var info = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            var claims = "";

            foreach (var claim in info.Identity.Claims)
            {
                claims += claim.ToString() + "\n";
            }

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View(
                           "ExternalLoginConfirmation",
                           new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email,
                    FirstName = loginInfo.DefaultUserName,
                    LastName = loginInfo.DefaultUserName,
                    Claims = claims
                }));
            }
        }
Пример #14
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            var user = await UserManager.FindAsync(loginInfo.Login);

            // Logar caso haja um login externo e já esteja logado neste provedor de login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                var userext = UserManager.FindByEmailAsync(user.Email);
                await SignInAsync(userext.Result, false);

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                // Se ele nao tem uma conta solicite que crie uma

                var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                var email            = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:email").Value;
                var firstName        = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value;
                var lastName         = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:last_name").Value;

                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email, LastName = lastName, Name = firstName
                }));
            }
        }
Пример #15
0
        public async Task <ActionResult> Index()
        {
            var info = await _authenticationManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction("Index", "SignIn"));
            }

            var status = await _signInManager.ExternalSignInAsync(info, true);

            if (status == SignInStatus.Success)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var user = new ApplicationUser
            {
                UserName = info.Email,
                Email    = info.Email
            };

            var createResult = await _userManager.CreateAsync(user);

            if (!createResult.Succeeded)
            {
                return(RedirectToAction("Index", "SignIn"));
            }

            var loginResult = await _userManager.AddLoginAsync(user.Id, info.Login);

            if (!loginResult.Succeeded)
            {
                return(RedirectToAction("Index", "SignIn"));
            }

            await _signInManager.SignInAsync(user, true, true);

            return(RedirectToAction("Index", "Home"));
        }
Пример #16
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await GetExternalLoginInfoWorkaroundAsync();

            if (loginInfo == null)
            {
                Log.Error("External login information is null, returning to Login page.", String.Empty);

                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                var user = await UserManager.FindAsync(loginInfo.Login);

                await UserService.SetUserLastLoginByIdAsync(user.Id);

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #17
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            //External login info
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            //Try login local
            var loginResult = await SignInManager.ExternalSignInAsync(loginInfo, true);

            if (loginResult == SignInStatus.Success)
            {
                return(RedirectToLocal(returnUrl));
            }

            //No associate but authenticated - add login
            if (Request.IsAuthenticated)
            {
                await UserManager.AddLoginAsync(UserIdS, loginInfo.Login);

                return(RedirectToLocal(returnUrl));
            }

            //It`s registration
            string extUser = loginInfo.Email;

            if (extUser == null)
            {
                //Not registre without email
                return(RedirectToAction("Login", new { error = String.Format("{0} - {1}", loginInfo.Login.LoginProvider, S.LoginProviderNoEmail) }));
            }

            var user = await UserManager.FindAsync(loginInfo.Login);

            if (user != null)
            {
                if (user.LockoutEnabled)
                {
                    return(View("LockoutEnabled"));
                }

                SignInAsync(user, isPersistent: false);

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                //Member
                Member member = null;
                //Seek member
                var eMember = db.Members.FirstOrDefault(x => x.Email == loginInfo.Email & x.Id == x.MainMemberId & x.Id == x.UserId);
                //Create if exits
                member = eMember ?? Member.NewMember(loginInfo.Email);
                //Seek user by email
                user = UserManager.FindByName(extUser);
                //Create user
                if (user == null)
                {
                    user = new ApplicationUser()
                    {
                        UserName = extUser, Id = member.Id.ToString(), Email = loginInfo.Email
                    };
                    var result = await UserManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                        //Add member if exits
                        if (eMember == null)
                        {
                            db.Members.Add(member);
                            db.SaveChanges();
                        }
                    }
                }

                SignInAsync(user, isPersistent: false);
                return(RedirectToLocal("~/Project#/Currencies"));
            }
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }
            var user = UserManager.Users.Where(x => x.Logins.Any(s => s.LoginProvider == loginInfo.Login.LoginProvider && s.ProviderKey == loginInfo.Login.ProviderKey)).SingleOrDefault();

            // Require the user to have a confirmed email before they can log on.
            if (user != null)
            {
                if (!user.EmailConfirmed)
                {
                    ViewBag.errorMessage = AppResource.ConfirmEmailError;
                    return(View("Error"));
                }
            }

            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                string firstName        = string.Empty;
                string lastName         = string.Empty;
                var    externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

                switch (loginInfo.Login.LoginProvider)
                {
                case "Facebook":
                    var claim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type.Equals("FacebookAccessToken"));
                    try
                    {
                        var     client = new FacebookClient(claim.Value);
                        dynamic res    = client.Get("me");
                        firstName = res["first_name"];
                        lastName  = res["last_name"];
                    }
                    catch (FacebookOAuthException)
                    {
                        // Our access token is invalid or expired
                        // Here we need to do something to handle this.
                    }
                    break;

                case "Google":
                    var givenNameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.GivenName));
                    firstName = givenNameClaim.Value;
                    var SurnameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Surname));
                    lastName = SurnameClaim.Value;
                    break;
                }

                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email, FirstName = firstName, LastName = lastName
                }));
            }
        }
Пример #19
0
 public async Task <SignInStatus> ExternalSignInAsync(ExternalLoginInfo loginInfo, bool isPersistent)
 {
     return(await ApplicationSignInManager.ExternalSignInAsync(loginInfo, isPersistent));
 }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            GreenProDbEntities db = new GreenProDbEntities();

            ViewBag.StateId = new SelectList(db.States, "Id", "StateName");
            ViewBag.CityId  = new SelectList(db.Cities, "Id", "CityName");
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            string firstname = string.Empty, lastname = string.Empty, emailid = string.Empty, userid = string.Empty, username = string.Empty;

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                var returnURL = GetCookie("returnURL");
                if (returnURL != null)
                {
                    RedirectToLocal(returnURL.Value);
                }
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                //Get Provider
                if (loginInfo.Login.LoginProvider == "Facebook")
                {
                    firstname = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name").Value;
                    lastname  = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:last_name").Value;
                }
                else if (loginInfo.Login.LoginProvider == "Google")
                {
                    var externalIdentity = AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                    var emailClaim       = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
                    var lastNameClaim    = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
                    var givenNameClaim   = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);

                    emailid   = emailClaim.Value;
                    firstname = givenNameClaim.Value;
                    lastname  = lastNameClaim.Value;
                }

                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    UserName = loginInfo.Email, FirstName = firstname, LastName = lastname
                }));
            }
        }
Пример #21
0
 public async Task <SignInStatus> ExternalSignInAsync(ExternalLoginInfo loginInfo)
 {
     return(await _signInManager.ExternalSignInAsync(loginInfo, isPersistent : false));
 }
Пример #22
0
        public async Task <SignInStatus> ExternalSignInAsync(ApplicationSignInManager signInManager, ExternalLoginInfo loginInfo, bool isPersistent)
        {
            var result = await signInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            return(result);
        }
Пример #23
0
 public async Task <SignInStatus> EfetuarLoginExterno(ExternalLoginInfo login, bool rememberMe)
 {
     return(await _signInManager.ExternalSignInAsync(login, rememberMe));
 }
Пример #24
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                if (returnUrl != null && returnUrl.ToLowerInvariant().StartsWith("/account/logoff"))
                {
                    return(RedirectToLocal("/Account"));    // Redirect to your default account page
                }
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                //check if user with same email already exists
                var user = await UserManager.FindByEmailAsync(loginInfo.Email);

                if (user == null)
                {
                    user = new ApplicationUser {
                        UserName = loginInfo.Email, Email = loginInfo.Email, EmailConfirmed = true
                    };
                    var randomPassword = System.Web.Security.Membership.GeneratePassword(10, 5);
                    var result3        = await UserManager.CreateAsync(user, randomPassword);

                    if (!result3.Succeeded)
                    {
                        AddErrors(result3);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                var result2 = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                if (result2.Succeeded)
                {
                    using (var dbTransaction = db.Database.BeginTransaction())
                    {
                        if (!user.EmailConfirmed)
                        {
                            var user2 = db.Users.Where(b => (b.Email.Equals(user.Email))).SingleOrDefault();
                            //make email confirmed
                            user2.EmailConfirmed = true;
                            db.SaveChanges();
                            dbTransaction.Commit();
                        }
                    }

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToLocal(returnUrl));
                }
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
Пример #25
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            //Retain external username and email values for later reference
            var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
            var email      = emailClaim.Value;

            var nameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
            var userName  = nameClaim.Value;             //Same as: externalIdentity.Result.GetUserName(); ??

            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            var authResult = await SignInManager.AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);

            switch (result)
            {
            case SignInStatus.Success:
                //set external login values for session
                setSessionExternalLogin(userName, email);

                //Set return URL for later reference...
                ViewBag.ReturnUrl = returnUrl;

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then write a new entry into user database
                ViewBag.ReturnUrl = returnUrl;
                //ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                //return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });

                //var user = UserManager.FindByName(email);
                var user = UserManager.FindByEmail(email);

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, false, false);

                    //set external login values for session
                    setSessionExternalLogin(userName, email);

                    //Set return URL for later reference...
                    ViewBag.ReturnUrl = returnUrl;

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                    if (info == null)
                    {
                        return(View("ExternalLoginFailure"));
                    }

                    //BCC - 30-Nov-2015 - Set email field to avoid error: 'Email cannot be null or empty...
                    //BCC - TEST - 03-Dec-2015 - r: UserName = email w: UserName = userName
                    var newUser = new ApplicationUser()
                    {
                        UserName = userName, Email = email, UserEmail = email
                    };

                    var rst = await UserManager.CreateAsync(newUser);

                    if (rst.Succeeded)
                    {
                        var r = await UserManager.AddLoginAsync(newUser.Id, info.Login);

                        if (r.Succeeded)
                        {
                            await SignInManager.SignInAsync(newUser, false, false);

                            //set external login values for session
                            setSessionExternalLogin(userName, email);

                            //Set return URL for later reference...
                            ViewBag.ReturnUrl = returnUrl;

                            return(RedirectToLocal(returnUrl));
                        }
                    }
                    //AddErrors(result);
                    return(View("ExternalLoginFailure"));
                }
            }
        }