public IHttpActionResult ExternalLoginCallback()
        {
            GoogleOAuth2Client.RewriteRequest();
            IHttpActionResult actionResult;

            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Settings.Url + "api/account/ExternalLoginCallback");

            if (!result.IsSuccessful)
            {
                actionResult = Redirect(Settings.Url + "api/Account/ExternalLoginFailure");
            }

            else if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                actionResult =
                    Redirect(Settings.Url + "api/Account/ExternalLoginFinal?provider=" + result.Provider + "&providerUserId=" +
                             result.ProviderUserId);
            }
            else
            {
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                var    model     = new AccountModels.RegisterExternalLoginModel
                {
                    UserName          = result.UserName,
                    ExternalLoginData = loginData
                };

                switch (result.Provider)
                {
                case "facebook":
                case "google":
                {
                    model.Email    = result.UserName;
                    model.UserName = result.UserName;
                    break;
                }

                case "twitter":
                {
                    model.Email    = result.UserName;
                    model.UserName = result.UserName;
                    break;
                }

                default:
                {
                    model.Email    = result.UserName;
                    model.UserName = result.UserName;
                    break;
                }
                }

                actionResult =
                    Redirect(Settings.Url + "api/Account/ExternalLoginConfirmation?username="******"&email=" +
                             model.Email + "&externallogindata=" + model.ExternalLoginData + "&provider=" +
                             result.Provider + "&providerUserId=" + result.ProviderUserId);
            }

            return(actionResult);
        }
Beispiel #2
0
        private void ProcessProviderResult()
        {
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();
            FedeFacebookClient.RewriteRequest();
            InstagramClient.RewriteRequest();
            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = "~/ExternalLogin.aspx";
            var returnUrl   = Request.QueryString["ReturnUrl"];

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


            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;
                ModelState.AddModelError("Provider", String.Format("External login {0} failed.", ProviderDisplayName));

                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderName), authResult.Error);
                return;
            }
            ProviderName       = authResult.Provider;
            ProviderUserId     = authResult.ProviderUserId;
            ProviderUserName   = authResult.UserName;
            Form.Action        = ResolveUrl(redirectUrl);
            imgSocial.ImageUrl = AuthHelper.GetSocialImage(authResult);
        }
Beispiel #3
0
        public static AuthenticationResult VerifyAuthentication()
        {
            var ms      = new GoogleOAuth2Client(Configuration.OauthClientId, Configuration.OauthClientSecret);
            var manager = new OpenAuthSecurityManager(new HttpContextWrapper(HttpContext.Current),
                                                      ms, OAuthDataProvider.Instance);

            GoogleOAuth2Client.RewriteRequest();
            return(manager.VerifyAuthentication(Configuration.OauthRedirect));
        }
Beispiel #4
0
        public ActionResult OpenId(LoginModel model)
        {
            Identifier id;

            if (Identifier.TryParse(model.OpenID_Identifier, out id))
            {
                try
                {
                    model.Config = _services.Config.Current;
                    var openId = new OpenIdRelyingParty();
                    returnToUrl = new Uri(Url.Action("OpenIdCallback", "Authentication", new { ReturnUrl = model.ReturnUrl }, Request.Url.Scheme), UriKind.Absolute);
                    // hack for google oauth2
                    if (model.OpenID_Identifier.Contains("google"))
                    {
                        client = new GoogleOAuth2Client(model.Config.ClientId, model.Config.ClientSecret);
                        client.RequestAuthentication(this.HttpContext, returnToUrl);
                        GoogleOAuth2Client.RewriteRequest();
                        return(Redirect(returnToUrl.ToString()));
                    }
                    else
                    {
                        var request = openId.CreateRequest(id, Realm.AutoDetect, returnToUrl);

                        // add request for name and email using sreg (OpenID Simple Registration
                        // Extension)
                        request.AddExtension(new ClaimsRequest
                        {
                            Email    = DemandLevel.Require,
                            FullName = DemandLevel.Require,
                            Nickname = DemandLevel.Require
                        });

                        // also add AX request
                        var axRequest = new FetchRequest();
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        request.AddExtension(axRequest);

                        var redirectingResponse = request.RedirectingResponse;

                        return(redirectingResponse.AsActionResult());
                    }
                }
                catch (ProtocolException ex)
                {
                    model.Message = ex.Message;
                    return(View("Login", model));
                }
            }
            else
            {
                model.Message = "Invalid identifier";
                return(View("Login", model));
            }
        }
        private AuthenticationResult VerifyAuthentication(string redirectUrl)
        {
            try
            {
                GoogleOAuth2Client.RewriteRequest();
                AuthenticationResult _authResult = OpenAuth.VerifyAuthentication(redirectUrl);

                ProviderName        = OpenAuth.GetProviderNameFromCurrentRequest();
                ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
                ProviderUserId      = _authResult.ProviderUserId;
                ProviderUserName    = _authResult.UserName;

                return(_authResult);
            }
            catch (ArgumentException ex)
            {
                Response.Redirect("~/Account/Login.aspx");
                return(null);
            }
        }
Beispiel #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("Login", "Login")));
            }

            ViewBag.authResultName           = authResult.UserName;
            ViewBag.authResultProvider       = authResult.Provider;
            ViewBag.authResultProviderUserId = authResult.ProviderUserId;
            ViewBag.authResultEmail          = authResult.ExtraData["email"];

            // tuleb lisada kasutaja andmebaasi kirjutamine

            return(View());
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            GoogleOAuth2Client.RewriteRequest();
            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (authResult.IsSuccessful)
            {
                var loggedEmailId = authResult.ExtraData["email"].ToString();
                if (loggedEmailId == "*****@*****.**" || loggedEmailId == "*****@*****.**")
                {
                    FormsAuthentication.SetAuthCookie(authResult.UserName, false);
                    return(Redirect(Url.Action("Index", "Home")));
                }
                else
                {
                    return(Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:53165/account/unauthorizedaccess"));
                }
            }
            else
            {
                return(Redirect(Url.Action("Login", "Account")));
            }
        }
Beispiel #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 authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

            if (!authResult.IsSuccessful)
            {
                ViewBag.Message = "User was not authenticated. Please try again";
                return(Redirect(Url.Action("Account", "Login")));
            }
            else
            {
                FormsAuthentication.SetAuthCookie(authResult.UserName, false);
                return(Redirect(Url.Action("Index", "Home")));
            }
        }
Beispiel #9
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);


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

            if (!authResult.IsSuccessful)
            {
                return(Redirect(Url.Action("Login", "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
            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());
        }
Beispiel #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)
            {
                return(Redirect(Url.Action("Index", "Home")));
            }

            // 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("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"];
            }

            var User = db.UserAccounts.FirstOrDefault(p => p.UserName == Email && p.UserID == ProviderUserId);

            if (User == null)
            {
                //its a new user
                UserAccount NewUser = new UserAccount
                {
                    UserID         = ProviderUserId,
                    UserName       = Email,
                    Password       = Setup.CryptoEngine.Encrypt("1234"),
                    IsActive       = true,
                    UserType       = "USER",
                    DateRegistered = DateTime.Now
                };
                db.UserAccounts.Add(NewUser);
                db.SaveChanges();
                Session["userid"] = ProviderUserId;

                return(RedirectToAction("index", "Home"));
            }
            else
            {
                Session["userid"] = ProviderUserId;
                return(RedirectToAction("index", "Home"));
            }

            //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"));
            //        }
            //    }
            //}
        }
Beispiel #11
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;
            }
        }
Beispiel #12
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"));
            }
        }
Beispiel #13
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());
        }
        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"));
            }
        }
        public ActionResult GoogleLoginCallback(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("GoogleLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl      = returnUrl;
            var authResult  = OpenAuth.VerifyAuthentication(redirectUrl);

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

            var username   = authResult.UserName;
            var providerId = authResult.ProviderUserId;

            string       sql = "SELECT * FROM user u WHERE u.mail = @mail AND u.password = @password;";
            MySqlCommand cmd = new MySqlCommand(sql, Database.Instance.Connection);

            cmd.Parameters.AddWithValue("@mail", username);
            cmd.Parameters.AddWithValue("@password", providerId);
            var reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                var userId = reader.GetInt32(0);
                reader.Close();
                MySession.SetUser(new User(userId));
            }
            else
            {
                reader.Close();

                string       sql2 = $"INSERT INTO `supfile`.`user` (`mail`, `password`, `stockage`, `stockagemax`) VALUES ('{username}', @password, 0, 30000000);";
                MySqlCommand cmd2 = new MySqlCommand(sql2, Database.Instance.Connection);
                cmd2.Parameters.AddWithValue("@password", providerId);
                var a = Database.Instance.SeePreparedQuery(cmd2);
                cmd2.ExecuteNonQuery();

                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    var userId = reader.GetInt32(0);
                    reader.Close();
                    MySession.SetUser(new User(userId));
                }
                else
                {
                    //Something appened, register failed
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #16
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)
            {
                //Зовнішня аутентифікація успішна, перевярємо чи юзер вже є в локальній БД
                //Якшо юзера немає додаємо
                if (!oAuthLogic.IsUserExists(authResult.ProviderUserId))
                {
                    UserOpenAuthModel user = new UserOpenAuthModel();
                    user.ProvideUserId    = authResult.ProviderUserId;
                    user.ProviderUserName = authResult.UserName;
                    user.ProviderName     = authResult.Provider;
                    string Email = null;
                    if (Email == null && authResult.ExtraData.ContainsKey("email"))
                    {
                        Email = authResult.ExtraData["email"];
                    }
                    user.MembershipUserrName = Email;
                    //Додаємо новго юзера, ставим кукі і повертаємо його на головну
                    if (oAuthLogic.AddNewUser(user))
                    {
                        FormsAuthentication.SetAuthCookie(authResult.UserName, true);
                        return(Redirect(Url.Action("Index", "Home")));
                    }
                }
                //Якшо юзер вже є, ставимо кукі і на головну
                else
                {
                    FormsAuthentication.SetAuthCookie(authResult.UserName, true);
                    return(Redirect(Url.Action("Index", "Home")));
                }
            }
            else
            {
                ViewBag.Message = "Помилка авторизації!";
                return(View("Error"));
            }

            return(View());
        }
        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")));
                    }
                }
            }
        }