Ejemplo n.º 1
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }
            GoogleOAuth2Client.RewriteRequest();
            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Index", "Login")));
            }

            // Check if user is already registered locally
            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }
            using (AreaEntities db = new AreaEntities())
            {
                if (db.users.Any(m => m.Email == Email))
                {
                    var tmp = await db.users.Where(m => m.Email == Email).FirstOrDefaultAsync();

                    Session["Username"] = tmp.Name;
                    Session["Email"]    = tmp.Email;
                    FormsAuthentication.SetAuthCookie(Email, false);
                    return(Redirect(Url.Action("Index", "Home")));
                }
            }


            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }
            if (User.Identity.IsAuthenticated)
            {
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                using (AreaEntities db = new AreaEntities())
                {
                    user elem = new user()
                    {
                        Name     = ProviderUserName,
                        Email    = Email,
                        Password = ""
                    };
                    if (db.users.Any(m => m.Email == Email))
                    {
                        ViewBag.Message = "User cannot be created";
                        ModelState.AddModelError("", "This Email is already taken.");
                        return(Redirect("/login/"));
                    }
                    else
                    {
                        db.users.Add(elem);
                        await db.SaveChangesAsync();

                        var tmp = await db.users.Where(m => m.Email == Email).FirstOrDefaultAsync();

                        Session["Email"]    = tmp.Email;
                        Session["Username"] = tmp.Name;
                        FormsAuthentication.SetAuthCookie(Email, false);
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
        }
        private void ProcessProviderResult()
        {
            // Procesar el resultado de un proveedor de autenticación en la solicitud
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Crear la dirección URL de redirección para la comprobación de OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Comprobar la carga de OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Error de inicio de sesión externo";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("Error de inicio de sesión externo {0},", ProviderDisplayName);

                // Para ver este error, habilite el seguimiento de página en web.config (<system.web><trace enabled="true"/></system.web>) y visite ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Error al comprobar la autenticación con {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // El usuario ha iniciado sesión con el proveedor correctamente
            // Comprobar si el usuario ya está registrado localmente
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Almacenar los detalles del proveedor en ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Seccionar la cadena de consulta desde la acción
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // El usuario ya se ha autenticado, agregue el inicio de sesión externo y redirija para volver a la dirección URL
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // El usuario es nuevo, solicitar nombres de pertenencia deseados
                userName.Text = authResult.UserName;
            }
        }
Ejemplo n.º 3
0
    private void ProcessProviderResult()
    {
        // Обработка результата от поставщика проверки подлинности в запросе
        ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

        if (String.IsNullOrEmpty(ProviderName))
        {
            Response.Redirect(FormsAuthentication.LoginUrl);
        }

        ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

        // Построение URL-адреса перенаправления для проверки OpenAuth
        var redirectUrl = "~/Account/RegisterExternalLogin";
        var returnUrl   = Request.QueryString["ReturnUrl"];

        if (!String.IsNullOrEmpty(returnUrl))
        {
            redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
        }

        // Проверка данных OpenAuth
        var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

        if (!authResult.IsSuccessful)
        {
            Title = "Ошибка внешней учетной записи";
            userNameForm.Visible = false;
            $if$($targetframeworkversion$ >= 4.5)
            ModelState.AddModelError("Provider", String.Format("Ошибка внешней учетной записи {0}.", ProviderDisplayName));
            $else$
            providerMessage.Text = String.Format("Ошибка внешней учетной записи {0},", ProviderDisplayName);
            $endif$
            // Чтобы просмотреть ошибку, включите трассировку страниц в файле web.config (<system.web><trace enabled="true"/></system.web>) и откройте адрес ~/Trace.axd
            Trace.Warn("OpenAuth", String.Format("Ошибка при проверке подлинности через {0})", ProviderDisplayName), authResult.Error);

            return;
        }

        // Пользователь успешно вошел через поставщика
        // Проверка того, не зарегистрирован ли пользователь локально
        if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
        {
            RedirectToReturnUrl();
        }

        // Сохранение сведений о поставщике в ViewState
        ProviderName     = authResult.Provider;
        ProviderUserId   = authResult.ProviderUserId;
        ProviderUserName = authResult.UserName;

        // Извлечь строку запроса из действия
        Form.Action = ResolveUrl(redirectUrl);

        if (User.Identity.IsAuthenticated)
        {
            // Пользователь проверен, добавляем внешнюю учетную запись и переходим на URL-адрес возврата
            OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
            RedirectToReturnUrl();
        }
        else
        {
            // Новый пользователь, запрашиваем желаемое имя участника
            userName.Text = authResult.UserName;
        }
    }
Ejemplo n.º 4
0
    private void ProcessProviderResult()
    {
        // Przetwórz wynik od dostawcy uwierzytelniania w żądaniu
        ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

        if (String.IsNullOrEmpty(ProviderName))
        {
            Response.Redirect(FormsAuthentication.LoginUrl);
        }

        ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

        // Utwórz adres URL przekierowania na potrzeby weryfikacji OpenAuth
        var redirectUrl = "~/Account/RegisterExternalLogin";
        var returnUrl   = Request.QueryString["ReturnUrl"];

        if (!String.IsNullOrEmpty(returnUrl))
        {
            redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
        }

        // Zweryfikuj ładunek OpenAuth
        var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

        if (!authResult.IsSuccessful)
        {
            Title = "Logowanie zewnętrzne nie powiodło się";
            userNameForm.Visible = false;

            providerMessage.Text = String.Format("Logowanie zewnętrzne {0} nie powiodło się,", ProviderDisplayName);

            // Aby wyświetlić ten błąd, włącz śledzenie stron w pliku web.config (<system.web><trace enabled="true"/></system.web>) i przejdź do pliku ~/Trace.axd
            Trace.Warn("OpenAuth", String.Format("Wystąpił błąd podczas weryfikowania uwierzytelniania za pomocą {0})", ProviderDisplayName), authResult.Error);
            return;
        }

        // Użytkownik pomyślnie zalogował się za pomocą dostawcy
        // Sprawdź, czy użytkownik jest już zarejestrowany lokalnie
        if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
        {
            RedirectToReturnUrl();
        }

        // Przechowuj szczegóły dostawcy we właściwości ViewState
        ProviderName     = authResult.Provider;
        ProviderUserId   = authResult.ProviderUserId;
        ProviderUserName = authResult.UserName;

        // Usuń akcję z ciągu zapytania
        Form.Action = ResolveUrl(redirectUrl);

        if (User.Identity.IsAuthenticated)
        {
            // Użytkownik jest już uwierzytelniony, dodaj logowanie zewnętrzne i przekieruj do zwrotnego adresu URL
            OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
            RedirectToReturnUrl();
        }
        else
        {
            // Użytkownik jest nowy, zapytaj, jaką chce mieć nazwę członkowską
            userName.Text = authResult.UserName;
        }
    }
        private void ProcessProviderResult()
        {
            // 處理要求中驗證提供者所提供的結果
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // 建立重新導向 URL 以便進行 OpenAuth 驗證
            var redirectUrl = "~/Account/RegisterExternalLogin.aspx";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            //驗證 OpenAuth 裝載
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部登入失敗";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("外部登入 {0} 失敗。", ProviderDisplayName));

                // 若要檢視此錯誤,請在 web.config (<system.web><trace enabled="true"/></system.web>) 中啟用頁面追蹤並造訪 ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("使用 {0}) 確認驗證時發生錯誤", ProviderDisplayName), authResult.Error);
                return;
            }

            // 使用者已成功透過提供者登入
            // 檢查使用者是否已在本機註冊
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // 在 ViewState 中儲存提供者詳細資料
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // 使查詢字串脫離動作
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // 使用者已經過驗證,新增外部登入並重新導向以傳回 url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // 使用者是新的,詢問其所需的成員資格名稱
                userName.Text = authResult.UserName;
            }
        }
Ejemplo n.º 6
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Account", "Login")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            //You can call you user data access method to check and create users based on your model

            var    id      = authResult.ExtraData["id"];
            string email   = authResult.ExtraData["email"];
            var    name    = authResult.ExtraData["name"];
            var    picture = authResult.ExtraData["picture"];

            SocialLogin socialLogin = new SocialLogin();

            socialLogin.EmailAddress              = email;
            socialLogin.FullName                  = name;
            socialLogin.IsGoogleLogin             = true;
            socialLogin.GoogleProviderUserId      = id;
            socialLogin.GoogleUserProfileImageUrl = picture;
            UserDomainLogic userDomainLogic = new UserDomainLogic();
            var             message         = userDomainLogic.RegisterUserthroughSociallogin(socialLogin);

            if (message.MessageType == Domain.Enums.MessageType.Success)
            {
                return(RedirectAfterLogin(returnUrl));
            }
            else if (message.MessageType == Domain.Enums.MessageType.NewUser)
            {
                TempData["isFromSocialMedia"] = true;
                return(RedirectToAction("NewRegistrationfromSocialPage", "User", new { sm = true }));
            }
            else
            {
                ErrorBlock(message.MessageText);
                return(View("Login"));
            }
        }
Ejemplo n.º 7
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("ConsumerSummary", "Enrollment")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            //You can call you user data access method to check and create users based on your model
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                //return Redirect(Url.Action("Contact", "Home"));
                return(Redirect(Url.Action("ConsumerSummary", "Enrollment")));
            }

            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                //return Redirect(Url.Action("Contact", "Home"));
                return(Redirect(Url.Action("ConsumerSummary", "Enrollment")));
                //return Redirect(Url.Action("Index", "Home"));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        //return Redirect(Url.Action("Contact", "Home"));
                        return(Redirect(Url.Action("ConsumerSummary", "Enrollment")));
                    }
                }
            }

            return(View());
        }
Ejemplo n.º 8
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }
            GoogleOAuth2Client.RewriteRequest();
            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Home", "Login")));
            }

            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }

            RegisterModel mod = new RegisterModel();

            mod.UserName = Email;
            mod.DPName   = ProviderUserName;
            UserModel     usermodel = IService.ToFBregisterModel(mod);
            Locationmodel city      = IService.GetUserCountryByIp();

            UserSession.UserCountry   = city.CountryCode;
            UserSession.UserName      = usermodel.UserName;
            UserSession.HasSession    = true;
            UserSession.UserId        = usermodel.Id;
            UserSession.LastLoginDate = usermodel.LastLoginTime != null ? usermodel.LastLoginTime.Value : DateTime.Now;
            if (usermodel.IsAdmin)
            {
                UserSession.UserRole   = RolesEnum.Admin;
                UserSession.UserRoleId = RolesEnum.Admin.GetHashCode().ToString();
                return(RedirectToAction("Index", "Admin"));
            }
            else
            {
                UserSession.UserRole   = RolesEnum.User;
                UserSession.UserRoleId = RolesEnum.User.GetHashCode().ToString();
                return(RedirectToAction("Index", "User"));
            }
        }
Ejemplo n.º 9
0
        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }


            if (ProviderName == "Google")
            {
                GoogleOAuth2Client.RewriteRequest();
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("External login {0} failed,", ProviderDisplayName);

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Strip the query string from action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // Check if user registration is enabled
                if (Convert.ToInt32(HostSettingManager.Get(HostSettingNames.UserRegistration)) == (int)UserRegistration.None)
                {
                    Response.Redirect("~/AccessDenied.aspx", true);
                }

                // Try to get the email from the provider
                string emailResult = null;
                authResult.ExtraData.TryGetValue("email", out emailResult);

                // User is new, ask for their desired membership name and email
                userName.Text = authResult.UserName;
                email.Text    = emailResult;
            }
        }
Ejemplo n.º 10
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);


            if (!authResult.IsSuccessful)
            {
                ViewBag.Message = "Not A Valid EmailID";
                return(Redirect(Url.Action("Account", "Login")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            //You can call you user data access method to check and create users based on your model
            VC_LMSEntities d     = new VC_LMSEntities();
            string         email = authResult.ExtraData["email"];
            var            row   = d.UsersTables.Where(x => x.EMAIL == email).FirstOrDefault();

            if (row == null)
            {
                ViewBag.Message = "Email not in Database";
                return(RedirectToAction("Index"));
            }
            else
            {
                var id = row.EMPLOYEE_ID;
                //var manager = d.managers.Where(x => x.manager_emp_id == id).FirstOrDefault();
                //if ( manager!= null&&row.Status=="Active")
                //{

                //    Session["userID"] = row.EMPLOYEE_ID;
                //    Session["userName"] = row.FIRST_NAME;
                //    Session["Name"] = row.EMAIL;
                //    return RedirectToAction("Index", "manager");
                //}
                //else
                {
                    var row1 = d.approvers.Where(x => x.approver_id == row.EMPLOYEE_ID).FirstOrDefault();
                    if (row1 != null && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Approver"));
                    }
                    else if (row.ROLES == "HR" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "HR"));
                    }
                    else if (row.ROLES == "Employee" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Employee"));
                    }
                    else if (row.ROLES == "Admin" && row.Status == "Active")
                    {
                        Session["userID"]   = row.EMPLOYEE_ID;
                        Session["userName"] = row.FIRST_NAME;
                        Session["Name"]     = row.EMAIL;
                        return(RedirectToAction("Index", "Admin"));
                    }
                }
            }
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                return(Redirect(Url.Action("Index", "Home")));
            }

            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;

            string Email = null;

            if (Email == null && authResult.ExtraData.ContainsKey("email"))
            {
                Email = authResult.ExtraData["email"];
            }

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
            return(View());
        }
        private void ProcessProviderResult()
        {
            // 要求の認証プロバイダーからの結果を処理します
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // OpenAuth 検証のリダイレクト URL をバインドします
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // OpenAuth ペイロードを検証します
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部ログインが失敗しました";
                userNameForm.Visible = false;

                providerMessage.Text = String.Format("外部ログイン {0} が失敗しました、", ProviderDisplayName);

                // このエラーを表示するには、web.config (<system.web><trace enabled="true"/></system.web>) でページ トレースを有効にし、~/Trace.axd にアクセスします
                Trace.Warn("OpenAuth", String.Format("{0} での認証の検証でエラーが発生しました)", ProviderDisplayName), authResult.Error);
                return;
            }

            // ユーザーはプロバイダーを使用して正常にログインしました
            // ユーザーが既にローカルで登録されているかどうかを確認します
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // プロバイダーの詳細情報を ViewState に格納します
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // アクションからクエリ文字列を削除します
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // ユーザーは既に認証されています、戻り先 URL に外部ログインとリダイレクトを追加します
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // ユーザーは新規ユーザーです、ユーザーが希望するメンバーシップ名をたずねます
                userName.Text = authResult.UserName;
            }
        }
Ejemplo n.º 12
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            var    ID           = "";
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                System.Collections.Specialized.NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            DotNetOpenAuth.GoogleOAuth2.GoogleOAuth2Client.RewriteRequest();
            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);


            //string ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("login", "Account")));
            }

            else
            {
                qendidateList gmailUser     = new qendidateList();
                string        ProviderUser  = authResult.ProviderUserId;
                string        ProviderUName = authResult.UserName;
                string        UEmail        = null;
                if (UEmail == null && authResult.ExtraData.ContainsKey("email"))
                {
                    UEmail = authResult.ExtraData["email"];
                }
                try
                {
                    var result = BaseUtil.checkSocialProfile(UEmail);
                    if (result == "NotExists")
                    {
                        gmailUser.qenName          = ProviderUName;
                        gmailUser.qenEmail         = UEmail;
                        gmailUser.qenLinkdInUrl    = "www.someurl.com";
                        gmailUser.dataIsCreated    = BaseUtil.GetCurrentDateTime();
                        gmailUser.dataIsUpdated    = BaseUtil.GetCurrentDateTime();
                        gmailUser.roleID           = 5;
                        gmailUser.isDelete         = false;
                        gmailUser.isActive         = true;
                        gmailUser.isMobileVerified = false;
                        gmailUser.isEmalVerified   = true;
                        gmailUser.password         = baseClass.GetRandomPasswordString(10);
                        //gmailUser.qenImage = linkedINResVM.pictureurl;
                        gmailUser.qenPhone       = "9999999999";
                        gmailUser.qenAddress     = "some address";
                        gmailUser.qenAddress     = null;
                        gmailUser.registeredFrom = "Google";
                        db.qendidateLists.Add(gmailUser);
                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            BaseUtil.CaptureErrorValues(ex);
                        }
                        //----------------------------use below code to send emailer------------------------------------------------------------

                        StreamReader sr        = new StreamReader(Server.MapPath("/Emailer/toCandidateRegistrationSuccess.html"));
                        string       HTML_Body = sr.ReadToEnd();
                        string       newString = HTML_Body.Replace("#name", gmailUser.qenName).Replace("#password", gmailUser.password);
                        sr.Close();
                        string            To                   = gmailUser.qenEmail.ToString();
                        string            mail_Subject         = "Candidate Registration Confirmation ";
                        profileController objprofileController = new profileController();
                        BaseUtil.sendEmailer(To, mail_Subject, newString, "");
                        //----------------------------end to send emailer------------------------------------------------------------

                        BaseUtil.SetSessionValue(AdminInfo.UserID.ToString(), Convert.ToString(gmailUser.qenID));
                        //BaseUtil.SetSessionValue(AdminInfo.Mobile.ToString(), Convert.ToString(user.qenPhone));
                        BaseUtil.SetSessionValue(AdminInfo.role_id.ToString(), Convert.ToString(gmailUser.roleID));
                        BaseUtil.SetSessionValue(AdminInfo.FullName.ToString(), Convert.ToString(gmailUser.qenName));
                        ID = BaseUtil.GetSessionValue(AdminInfo.UserID.ToString());
                        BaseUtil.SetSessionValue(AdminInfo.logo.ToString(), Convert.ToString(gmailUser.qenImage));
                        BaseUtil.SetSessionValue(AdminInfo.mobileVerified.ToString(), Convert.ToString(gmailUser.isMobileVerified));
                        BaseUtil.SetSessionValue(AdminInfo.emailVerified.ToString(), Convert.ToString(gmailUser.isEmalVerified));
                    }
                    else if (result == "Exists")
                    {
                        var user = db.qendidateLists.Where(u => u.qenEmail == UEmail).FirstOrDefault();

                        BaseUtil.SetSessionValue(AdminInfo.UserID.ToString(), Convert.ToString(user.qenID));
                        //BaseUtil.SetSessionValue(AdminInfo.Mobile.ToString(), Convert.ToString(user.qenPhone));
                        BaseUtil.SetSessionValue(AdminInfo.role_id.ToString(), Convert.ToString(user.roleID));
                        BaseUtil.SetSessionValue(AdminInfo.FullName.ToString(), Convert.ToString(user.qenName));
                        ID = BaseUtil.GetSessionValue(AdminInfo.UserID.ToString());
                        BaseUtil.SetSessionValue(AdminInfo.logo.ToString(), Convert.ToString(user.qenImage));
                        BaseUtil.SetSessionValue(AdminInfo.mobileVerified.ToString(), Convert.ToString(user.isMobileVerified));
                        BaseUtil.SetSessionValue(AdminInfo.emailVerified.ToString(), Convert.ToString(user.isEmalVerified));
                    }
                }
                catch (Exception ex)
                {
                    BaseUtil.CaptureErrorValues(ex);
                }
            }
            return(RedirectToAction("jobs", "jobDetails", new { ID = ID }));
        }
Ejemplo n.º 13
0
        private void ProcessProviderResult()
        {
            // Traiter le résultat à partir d'un fournisseur d'authentification de la demande
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Générer l'URL de redirection pour la vérification OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Vérifier la charge utile OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Échec de la connexion externe";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("Échec de la connexion externe {0}.", ProviderDisplayName));

                // Pour afficher cette erreur, activer le traçage des pages dans web.config (<system.web><trace enabled="true"/></system.web>) et consulter ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Une erreur est survenue lors de la vérification de l'authentification avec {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // L'utilisateur s'est bien connecté au fournisseur
            // Vérifier si l'utilisateur est déjà inscrit localement
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Stocker les détails du fournisseur dans ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Enlever la chaîne de requête de l'action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // L'utilisateur est déjà authentifié, ajouter la connexion externe et rediriger vers l'URL de renvoi
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // Il s'agit d'un nouvel utilisateur, demander quel est le nom de membre souhaité
                userName.Text = authResult.UserName;
            }
        }
        public IHttpActionResult ExternalLoginCallback(string code, string state)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            string username  = "";
            string returnURI = "";

            // For future user when we integrate with other oauth2 applications
            if (ProviderName == null || ProviderName == "")
            {
                var    nvs        = Request.GetQueryNameValuePairs();
                string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value;
                if (state != null)
                {
                    // We need some variables from our state parameter.
                    NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam);
                    if (provideritem["__provider__"] != null)
                    {
                        ProviderName = provideritem["__provider__"];
                    }

                    if (provideritem["username"] != null)
                    {
                        username = provideritem["username"];
                        // Check to make sure username exists in database.
                        if (!_accountRepository.Exists(d => d.UserName == username))
                        {
                            return(Unauthorized());
                        }
                    }
                    // No username was provided.
                    else
                    {
                        return(Unauthorized());
                    }

                    if (provideritem["returnURI"] != null)
                    {
                        returnURI = provideritem["returnURI"];
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }
            else
            {
                var    nvs        = Request.GetQueryNameValuePairs();
                string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value;
                if (state != null)
                {
                    // We need some variables from our state parameter.
                    NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam);

                    if (provideritem["username"] != null)
                    {
                        username = provideritem["username"];
                        // Check to make sure username exists in database.
                        if (!_accountRepository.Exists(d => d.UserName == username))
                        {
                            return(Unauthorized());
                        }
                    }
                    // No username was provided.
                    else
                    {
                        return(Unauthorized());
                    }

                    if (provideritem["returnURI"] != null)
                    {
                        returnURI = provideritem["returnURI"];
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }

            // Rewrite the request to include the requested headers and info for exchanging
            // the authorization code for a LinkedIn access token
            LinkedInOAuth2Client.RewriteRequest();

            // Now that the request has been rewritten, make the call and include the same callback uri provided earlier
            var authResult = OpenAuth.VerifyAuthentication(_externalCallBack);

            // For future user when we integrate with other oauth2 applications
            string providerDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

            //If the verification process failed
            if (!authResult.IsSuccessful)
            {
                return(Unauthorized());
            }
            else
            {
                //Get provider user details
                string providerUserId   = authResult.ProviderUserId;
                string providerUserName = authResult.UserName;
                string firstName        = null;
                string lastName         = null;
                string accessToken      = null;
                string email            = null;

                if (email == null && authResult.ExtraData.ContainsKey("email-address"))
                {
                    email = authResult.ExtraData["email-address"];
                }
                if (firstName == null && authResult.ExtraData.ContainsKey("first-name"))
                {
                    firstName = authResult.ExtraData["first-name"];
                }
                if (lastName == null && authResult.ExtraData.ContainsKey("last-name"))
                {
                    lastName = authResult.ExtraData["last-name"];
                }
                if (accessToken == null && authResult.ExtraData.ContainsKey("accesstoken"))
                {
                    accessToken = authResult.ExtraData["accesstoken"];
                }
                var userInfo = new List <object>();
                userInfo.Add(new
                {
                    ProviderDisplayName = providerDisplayName,
                    ProviderUserId      = providerUserId,
                    FirstName           = firstName,
                    LastName            = lastName,
                    Email       = email,
                    AccessToken = accessToken
                });

                try
                {
                    // If the given user already has a LinkedIn access token
                    if (_linkedInAccessTokenRepository.Exists(d => d.UserName == username, d => d.Account))
                    {
                        LinkedInAccessToken token = _linkedInAccessTokenRepository.GetSingle(d => d.UserName == username, d => d.Account);
                        token.Expired       = false;
                        token.TokenCreation = DateTime.UtcNow;
                        token.Value         = accessToken;
                        _linkedInAccessTokenRepository.Update(token);
                    }
                    else
                    {
                        LinkedInAccessToken token = new LinkedInAccessToken()
                        {
                            UserName      = username,
                            TokenCreation = DateTime.UtcNow,
                            Value         = accessToken
                        };
                        _linkedInAccessTokenRepository.Insert(token);
                    }
                } catch (Exception)
                {
                    return(InternalServerError());
                }

                if (returnURI != "null")
                {
                    // Try the given redirectUri
                    try
                    {
                        return(Redirect(returnURI + "?linkedin=success"));
                    }
                    // If it fails, go with the default
                    catch (Exception)
                    {
                        return(Redirect("http://localhost:8080/Home?linkedin=success"));
                    }
                }

                return(Redirect("http://localhost:8080/Home?linkedin=success"));
            }
        }
        private void ProcessProviderResult()
        {
            // 处理请求中的身份验证提供程序返回的结果
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // 生成重定向 URL 以进行 OpenAuth 验证
            var redirectUrl = "~/Account/RegisterExternalLogin.aspx";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // 验证 OpenAuth 负载
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "外部登录失败";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("外部登录 {0} 失败。", ProviderDisplayName));

                // 若要查看此错误,请在 web.config 中启用页跟踪(<system.web><trace enabled="true"/></system.web>),然后访问 ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("使用 {0}) 验证身份验证时出错", ProviderDisplayName), authResult.Error);
                return;
            }

            // 用户已成功地使用提供程序登录
            // 检查用户是否已在本地注册
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // 在 ViewState 中存储提供程序详细信息
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // 从操作中去除查询字符串
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // 用户已进行身份验证,请添加外部登录并重定向到返回 URL
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // 这是新用户,请要求该用户提供所需的成员名称
                userName.Text = authResult.UserName;
            }
        }
Ejemplo n.º 16
0
        private void ProcessProviderResult()
        {
            // Elaborare il risultato fornito da un provider di autenticazione nella richiesta
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Generare l'URL di reindirizzamento per la verifica OpenAuth
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verificare il payload OpenAuth
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "Accesso esterno non riuscito";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("Accesso esterno {0} non riuscito.", ProviderDisplayName));

                // Per visualizzare questo errore, abilitare la traccia delle pagine in web.config (<system.web><trace enabled="true"/></system.web>) e visitare ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("Si è verificato un errore durante la verifica dell'autenticazione con {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // L'utente ha eseguito l'accesso con il provider
            // Verificare se l'utente è già registrato nel computer locale
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Archiviare i dati del provider in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Rimuovere la stringa di query dall'azione
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // L'utente è già autenticato, aggiungere l'account di accesso esterno ed eseguire il reindirizzamento all'URL restituito
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // L'utente è nuovo, chiedere di specificare il nome di appartenenza desiderato
                userName.Text = authResult.UserName;
            }
        }
        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("External login {0} failed.", ProviderDisplayName));

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Strip the query string from action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // User is new, ask for their desired membership name
                userName.Text = authResult.UserName;
            }
        }
Ejemplo n.º 18
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["microsoft"] != null)
                        {
                            ProviderName = provideritem["microsoft"];
                        }
                    }
                }
            }

            var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }, this.Request.Url.Scheme);

            if (ProviderName == null)
            {
                ProviderName = "microsoft";
            }

            MicrosoftClient msClient   = OpenAuth.AuthenticationClients.GetByProviderName(ProviderName) as MicrosoftClient;
            var             authResult = msClient.VerifyAuthentication(new HttpContextWrapper(HttpContext.ApplicationInstance.Context), new Uri(redirectUrl));

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Login", "Account")));
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                return(Redirect(Url.Action("Index", "Home")));
            }
            //Get provider user details
            string ProviderUserId   = authResult.ProviderUserId;
            string ProviderUserName = authResult.UserName;
            string FirstName        = null;
            string LastName         = null;

            string Email = null;

            if (FirstName == null && authResult.ExtraData.ContainsKey("firstname"))
            {
                FirstName = authResult.ExtraData["firstname"];
            }
            if (LastName == null && authResult.ExtraData.ContainsKey("lastname"))
            {
                LastName = authResult.ExtraData["lastname"];
            }
            // call extension method to get email
            ExtendedMicrosoftClientUserData data = msClient.GetExtraData(authResult.ExtraData["accesstoken"]);

            Email = data.Emails.Preferred;

            if (User.Identity.IsAuthenticated)
            {
                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                return(Redirect(Url.Action("Index", "Home")));
            }
            else
            {
                // User is new, save email as username
                string membershipUserName = Email ?? ProviderUserId;
                var    createResult       = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, membershipUserName);

                if (!createResult.IsSuccessful)
                {
                    ViewBag.Message = "User cannot be created";
                    return(View());
                }
                else
                {
                    // User created
                    if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                    {
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
            }
            return(View());
        }