Exemplo n.º 1
0
        protected void btnCustomFeed_Click(object sender, EventArgs e)
        {
            if (SocialAuthUser.IsConnectedWith(PROVIDER_TYPE.FACEBOOK))
            {
                WebResponse  wr         = SocialAuthUser.GetCurrentUser().ExecuteFeed("https://graph.facebook.com/me/albums", TRANSPORT_METHOD.GET, PROVIDER_TYPE.FACEBOOK);
                StreamReader reader     = new StreamReader(wr.GetResponseStream());
                string       albumJson  = reader.ReadToEnd();
                JObject      jsonObject = JObject.Parse(albumJson);
                List <Album> albums     = new List <Album>();

                jsonObject["data"].Children().ToList().ForEach(x =>
                {
                    albums.Add(new Album()
                    {
                        ID         = (string)x["id"],
                        PhotoCount = x["count"] == null ? 0 : Convert.ToInt32(x["count"].ToString().Replace("\"", "")),
                        Name       = (string)x["name"].ToString().Replace("\"", ""),
                        Location   = (string)x["location"] == null ? "" : x["location"].ToString().Replace("\"", ""),
                        CoverPhoto = (string)x["cover_photo"] == null ? "" : x["cover_photo"].ToString().Replace("\"", "")
                    });
                });

                foreach (var item in albums)
                {
                    Label lbl = new Label();
                    lbl.Text     = "<h3>" + item.Name + "</h3>(" + item.PhotoCount + ") : " + "<img src='https://graph.facebook.com/" + item.CoverPhoto + "/picture?type=album&access_token=" + SocialAuthUser.GetCurrentUser().GetAccessToken() + "'>";
                    lbl.CssClass = "album";
                    lblAlbum.Controls.Add(lbl);
                }

                lblJson.Text = "Executed custom feed: <b>https://graph.facebook.com/me/albums</b><br>Result:<br>" + albumJson;
            }
        }
Exemplo n.º 2
0
    protected void btnIndividualLogout_Click(object sender, CommandEventArgs e)
    {
        PROVIDER_TYPE provider = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), e.CommandArgument.ToString());

        SocialAuthUser.GetCurrentUser().Logout(providerType: provider);
        Response.Redirect(HttpContext.Current.Request.Url.ToString());
    }
Exemplo n.º 3
0
        protected void btnDownload_Click(object sender, EventArgs e)
        {
            if (ddlConnectedProviders.Items.Count == 0)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "noprovider", "alert('You are not connected with any provider')", true);
                return;
            }

            var        token     = SocialAuthUser.GetCurrentUser().GetConnection((PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), ddlConnectedProviders.SelectedItem.Value)).GetConnectionToken();
            IFormatter formatter = new BinaryFormatter();
            Stream     stream    = new FileStream(Server.MapPath("~/temptokens/MyFile.token"),
                                                  FileMode.Create,
                                                  FileAccess.Write, FileShare.Write);

            formatter.Serialize(stream, token);
            stream.Close();
            stream.Dispose();


            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", "MyFile.token"));
            Response.WriteFile("~/temptokens/MyFile.token");
            Response.End();
        }
Exemplo n.º 4
0
 public static List <Brickred.SocialAuth.NET.Core.BusinessObjects.Contact> GetContacts(this IIdentity identity)
 {
     if (SocialAuthUser.IsLoggedIn() && Brickred.SocialAuth.NET.Core.Utility.GetSocialAuthConfiguration().Authentication.AllowModificationToUserIdentity)
     {
         return(SocialAuthUser.GetCurrentUser().GetContacts());
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntPost_Click(object sender, EventArgs args)
        {
            pgbPost.Value   = 0;
            pgbPost.Maximum = ds_media.Tables[0].Rows.Count;
            for (int idx = 0; idx < ds_media.Tables[0].Rows.Count; idx++)
            {
                String mediaPublishId = ds_media.Tables[0].Rows[idx]["发布编号"].ToString();
                setMediaPublishStatus(mediaPublishId, "发行中");
                string content = ds_media.Tables[0].Rows[CurrentIndex - 1]["名称"].ToString()
                                 + ds_media.Tables[0].Rows[CurrentIndex - 1]["发行期号"].ToString()
                                 + "[" + ds_media.Tables[0].Rows[CurrentIndex - 1]["发行日期"].ToString() + "]\r\n"
                                 + ds_media.Tables[0].Rows[CurrentIndex - 1]["文本内容"].ToString();
                string picpath = ds_media.Tables[0].Rows[CurrentIndex - 1]["本地图片"].ToString();

                try
                {
                    string msg      = HttpUtility.UrlEncode(content);
                    string endpoint = null;
                    switch (provider_type)
                    {
                    case PROVIDER_TYPE.FACEBOOK:
                        endpoint = "https://graph.facebook.com/me/feed?message=" + msg + "&access_token="
                                   + SocialAuthUser.GetCurrentUser().GetConnection(PROVIDER_TYPE.FACEBOOK).GetConnectionToken().AccessToken;
                        break;

                    case PROVIDER_TYPE.TWITTER:
                        endpoint = "http://api.twitter.com/1.1/statuses/update.json?status=" + msg;
                        break;
                    }

                    string body = String.Empty;
                    //byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
                    byte[] reqbytes = File.ReadAllBytes(ds_media.Tables[0].Rows[idx]["本地图片"].ToString());
                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    //headers.Add("contentType", "application/x-www-form-urlencoded");
                    headers.Add("contentType", "image/jpeg");
                    headers.Add("FileName", Path.GetFileName(ds_media.Tables[0].Rows[idx]["本地图片"].ToString()));
                    var response = manager.ExecuteFeed(
                        endpoint,
                        TRANSPORT_METHOD.POST,
                        provider_type,
                        reqbytes,
                        headers
                        );
                    setMediaPublishStatus(mediaPublishId, "发行完");
                }
                catch (Exception ex)
                {
                    setMediaPublishStatus(mediaPublishId, "未发行");
                    NCLogger.GetInstance().WriteExceptionLog(ex);
                }
            }
        }
Exemplo n.º 6
0
        //****** OPERATIONS
        public override UserProfile GetProfile()
        {
            Token       token    = SocialAuthUser.GetCurrentUser().GetConnection(this.ProviderType).GetConnectionToken();
            UserProfile profile  = new UserProfile(ProviderType);
            string      response = "";

            //If token already has profile for this provider, we can return it to avoid a call
            if (token.Profile.IsSet)
            {
                logger.Debug("Profile successfully returned from session");
                return(token.Profile);
            }

            try
            {
                logger.Debug("Executing Profile feed");
                string profileUrl     = ProfileEndpoint + "?user_id=" + token.Profile.ID;
                Stream responseStream = AuthenticationStrategy.ExecuteFeed(profileUrl, this, token, TRANSPORT_METHOD.GET).GetResponseStream();
                response = new StreamReader(responseStream).ReadToEnd();
            }
            catch
            {
                throw;
            }

            try
            {
                JObject profileJson = JObject.Parse(response);
                profile.ID          = profileJson.Get("id_str");
                profile.FirstName   = profileJson.Get("name");
                profile.Country     = profileJson.Get("location");
                profile.DisplayName = profileJson.Get("screen_name");
                //profile.Email =  not provided
                profile.Language          = profileJson.Get("lang");
                profile.ProfilePictureURL = profileJson.Get("profile_image_url");
                profile.IsSet             = true;
                token.Profile             = profile;
                logger.Info("Profile successfully received");
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.ProfileParsingError(response), ex);
                throw new DataParsingException(ErrorMessages.ProfileParsingError(response), ex);
            }
            return(profile);
        }
Exemplo n.º 7
0
        protected void btnPOST_Click(object sender, EventArgs e)
        {
            string msg      = HttpUtility.UrlEncode(txtTweet.Text);
            string endpoint = "http://api.twitter.com/1.1/statuses/update.json?status=" + msg;

            string body = String.Empty;

            byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("contentType", "application/x-www-form-urlencoded");
            var response = SocialAuthUser.GetCurrentUser().ExecuteFeed(
                endpoint,
                TRANSPORT_METHOD.POST,
                PROVIDER_TYPE.TWITTER,
                reqbytes,
                headers
                );

            errLabel.ForeColor = System.Drawing.Color.Purple;
            errLabel.Text      = "Post successfully posted! Please refresh tweets list to confirm or check on Twitter!!";
        }
        protected void btnPOST_Click(object sender, EventArgs e)
        {
            string msg      = HttpUtility.UrlEncode(txtStatus.Text);
            string endpoint = "https://graph.facebook.com/me/feed?message=" + msg + "&access_token=" + SocialAuthUser.GetCurrentUser().GetConnection(PROVIDER_TYPE.FACEBOOK).GetConnectionToken().AccessToken;

            string body = String.Empty;

            byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("contentType", "application/x-www-form-urlencoded");
            var response = SocialAuthUser.GetCurrentUser().ExecuteFeed(
                endpoint,
                TRANSPORT_METHOD.POST,
                PROVIDER_TYPE.FACEBOOK,
                reqbytes,
                headers
                );

            errLabel.ForeColor = System.Drawing.Color.Purple;
            errLabel.Text      = "Post successfully posted! Please refresh updates list to confirm or check on Facebook!!";
        }
    /// <summary>
    /// This method returns the claims to be issued in the token.
    /// </summary>
    /// <param name="principal">The caller's principal.</param>
    /// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
    /// <param name="scope">The scope information corresponding to this request.</param>
    /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
    /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
    protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal,
                                                               RequestSecurityToken request, Scope scope)
    {
        if (null == principal)
        {
            throw new ArgumentNullException("principal");
        }

        ClaimsIdentity outputIdentity = new ClaimsIdentity();

        // Issue custom claims.
        // TODO: Change the claims below to issue custom claims
        // that are required by your application.
        // Update the application's configuration file to reflect
        // the new claims requirements.

        // outputIdentity.Claims.Add( new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ) );
        // outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Manager" ) );

        // The Wingtip implementation.
        string       username = principal.Identity.Name;
        List <Claim> claims   = new List <Claim>();

        if (SocialAuthUser.IsLoggedIn())
        {
            claims = UserInfo.GetClaimsForSocialAuthUser(SocialAuthUser.GetCurrentUser().GetProfile());
        }
        else
        {
            claims = UserInfo.GetClaimsForUser(username);
        }
        foreach (Claim claim in claims)
        {
            outputIdentity.Claims.Add(claim);
        }

        return(outputIdentity);
    }
Exemplo n.º 10
0
        private void GetTweets()
        {
            var response   = SocialAuthUser.GetCurrentUser().ExecuteFeed("https://api.twitter.com/1.1/statuses/home_timeline.json?include_entities=true", TRANSPORT_METHOD.GET, PROVIDER_TYPE.TWITTER);
            var tweetsJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var tweets     = JArray.Parse(tweetsJson);
            var i          = 0;

            foreach (var tweet in tweets)
            {
                HtmlGenericControl newdiv = new HtmlGenericControl("div");
                newdiv.Style.Add("clear", "both");
                newdiv.Style.Add("margin-top", "5px;");
                newdiv.Style.Add("background-color", i % 2 == 0 ? "#CCFF66" : "#FFF999");
                newdiv.Style.Add("height", "100%");
                newdiv.InnerHtml  = "<span style='float:left'><img src=" + tweet.SelectToken("user.profile_image_url_https") + " /></span>";
                newdiv.InnerHtml += "<span><b>" + tweet.SelectToken("user.name") + "</b> says:<br>" + tweet.SelectToken("text") + "</span>";
                divTweets.Controls.Add(newdiv);
                if (++i == 10)
                {
                    break;
                }
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Request.QueryString["provider"] != null)
         {
             PROVIDER_TYPE providerType = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), Request.QueryString["provider"].ToUpper());
             SocialAuthUser.GetCurrentUser().Login(providerType, "popupprocess.aspx", errorRedirectURL: "popupprocess.aspx");
             ClientScript.RegisterClientScriptBlock(this.GetType(), "closeWin", "<script>window.close()</script>");
         }
         else if (Request.QueryString["error_message"] != null)
         {
             ClientScript.RegisterStartupScript(this.GetType(), "closeWin", "<script>alert('" + Request.QueryString["error_message"] + "'); window.close()</script>");
         }
         else
         {
             ClientScript.RegisterClientScriptBlock(this.GetType(), "closeWin", "<script>window.close()</script>");
         }
     }
     catch (Exception ex)
     {
         ClientScript.RegisterStartupScript(this.GetType(), "closeWin", "<script>window.close()</script>");
     }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Request.QueryString["provider"] != null)
         {
             PROVIDER_TYPE providerType = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), Request.QueryString["provider"].ToUpper());
             SocialAuthUser.GetCurrentUser().Login(providerType, "Pages/ProcessPopup.aspx", errorRedirectURL: "Pages/ProcessPopup.aspx");
             ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "closeWindow", "closeWindow();", true);
         }
         else if (Request.QueryString["error_message"] != null)
         {
             ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "closeWindow", "showErrorMsg('An error has occured');", true);
         }
         else
         {
             ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "closeWindow", "closeWindow();", true);
         }
     }
     catch (Exception ex)
     {
         ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "closeWindow", "closeWindow();", true);
     }
 }
        private void GetUpdates()
        {
            var response    = SocialAuthUser.GetCurrentUser().ExecuteFeed("https://graph.facebook.com/me/feed?access_token=" + SocialAuthUser.GetCurrentUser().GetAccessToken(), TRANSPORT_METHOD.GET, PROVIDER_TYPE.FACEBOOK);
            var updatesJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
            var data        = JObject.Parse(updatesJson);
            var updates     = JArray.Parse(data.SelectToken("data").ToString());
            var i           = 0;

            foreach (var tweet in updates)
            {
                HtmlGenericControl newdiv = new HtmlGenericControl("div");
                newdiv.Style.Add("clear", "both");
                newdiv.Style.Add("margin-top", "5px;");
                newdiv.Style.Add("background-color", i % 2 == 0 ? "#CCFF66" : "#FFF999");
                newdiv.Style.Add("height", "100%");
                //newdiv.InnerHtml = "<span style='float:left'><img src=" + tweet.SelectToken("user.profile_image_url_https") + " /></span>";
                newdiv.InnerHtml += "<span><b>" + tweet.SelectToken("from.name") + "</b> says:<br>" + tweet.SelectToken("message") + "</span>";
                divUpdates.Controls.Add(newdiv);
                if (++i == 10)
                {
                    break;
                }
            }
        }
 protected void lbtnLogout_Click(object sender, EventArgs e)
 {
     SocialAuthUser.GetCurrentUser().Logout("Default.aspx");
     lbtnLogout.Visible = false;
 }
Exemplo n.º 15
0
    /// <summary>
    /// Performs WS-Federation Passive Protocol processing.
    /// </summary>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        string action = Request.QueryString[WSFederationConstants.Parameters.Action];

        try
        {
            if (action == WSFederationConstants.Actions.SignIn)
            {
                // Process signin request.
                SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
                if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
                {
                    SecurityTokenService  sts             = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
                    SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts);
                    FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response);
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            else if (action == WSFederationConstants.Actions.SignOut)
            {
                // Process signout request.
                SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, User, requestMessage.Reply, Response);
            }
            else if (action == null && SocialAuthUser.IsLoggedIn())
            {
                string originalUrl = SocialAuthUser.GetCurrentUser().GetConnection(SocialAuthUser.CurrentProvider).GetConnectionToken().UserReturnURL;

                //replace ru value
                int    wctxBeginsFrom = originalUrl.IndexOf("wctx=");
                int    wctxEndsAt     = originalUrl.IndexOf("&wct=");
                string wctxContent    = originalUrl.Substring(wctxBeginsFrom + 5, wctxEndsAt - (wctxBeginsFrom + 5));
                originalUrl = originalUrl.Replace(wctxContent, Server.UrlEncode(wctxContent));

                //replace wtrealm value
                int    wtrealmBeginsFrom = originalUrl.IndexOf("wtrealm=");
                int    wtrealmEndsAt     = originalUrl.IndexOf("&", wtrealmBeginsFrom);
                string wtrealmContent    = originalUrl.Substring(wtrealmBeginsFrom + 8, wtrealmEndsAt - (wtrealmBeginsFrom + 8));
                originalUrl = originalUrl.Replace(wtrealmContent, Server.UrlEncode(wtrealmContent));

                SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(originalUrl));
                if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
                {
                    SecurityTokenService  sts             = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
                    SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts);
                    FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response);
                }
            }
            else
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.InvariantCulture,
                                        "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.",
                                        String.IsNullOrEmpty(action) ? "<EMPTY>" : action,
                                        WSFederationConstants.Parameters.Action,
                                        WSFederationConstants.Actions.SignIn,
                                        WSFederationConstants.Actions.SignOut));
            }
        }
        catch (Exception exception)
        {
            throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception);
        }
    }
Exemplo n.º 16
0
        public override List <BusinessObjects.Contact> GetContacts()
        {
            List <Contact> contacts = new List <Contact>();
            string         response = "";
            List <string>  sets     = new List <string>();

            Token  token      = SocialAuthUser.GetCurrentUser().GetConnection(this.ProviderType).GetConnectionToken();
            string friendsUrl = string.Format(ContactsEndpoint, token.Profile.Email);

            try
            {
                logger.Debug("Executing contacts feed");
                Stream responseStream = AuthenticationStrategy.ExecuteFeed(friendsUrl, this, token, TRANSPORT_METHOD.GET).GetResponseStream();
                response = new StreamReader(responseStream).ReadToEnd();
            }
            catch { throw; }
            try
            {
                string friendIDs = "";
                var    friends   = JObject.Parse(response).SelectToken("ids").Children().ToList();
                friendIDs = "";
                foreach (var s in friends)
                {
                    friendIDs += (s.ToString() + ",");
                }

                char[] arr         = friendIDs.ToArray <char>();
                var    iEnumerator = arr.GetEnumerator();
                int    counter     = 0;
                string temp        = "";
                while (iEnumerator.MoveNext())
                {
                    if (iEnumerator.Current.ToString() == ",")
                    {
                        counter += 1;
                    }
                    if (counter == 100)
                    {
                        sets.Add(temp);
                        temp    = "";
                        counter = 0;
                        continue;
                    }
                    temp += iEnumerator.Current;
                }
                if (temp != "")
                {
                    sets.Add(temp);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ErrorMessages.ContactsParsingError(response), ex);
                throw new DataParsingException(ErrorMessages.ContactsParsingError(response), ex);
            }
            foreach (string set in sets)
            {
                contacts.AddRange(Friends(set, token));
            }
            logger.Info("Contacts successfully received");
            return(contacts);
        }
        protected void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            /*************************
             * If Request is of type .sauth OR any type as specified in Config, allow and skip.
             * If Request is of LoginURL, skip
             * OTHERWISE:::::::::::::::::::::
             * <<<<IF USER IS NOT LOGGED IN>>>
             * If AuthenticationOption = SocialAuth
             *          Redirect in Priority - ConfigurationLoginURL,  "LoginForm.sauth"
             * If AuthenticationOption = FormsAuthentication
             *          Don't do anything. Let .NET handle it as per user's setting in Web.Config
             * If AuthenticationOption = Everything Custom
             *          Don't do anything. User will put checking code on every page himself.
             * **********************/

            AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();


            if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
            {
                //block any .aspx page. Rest all is allowed.
                //TODO: Better Implementation of this
                string requestUrlExtension  = VirtualPathUtility.GetExtension(HttpContext.Current.Request.RawUrl);
                string urlWithoutParameters = (new Uri(HttpContext.Current.Request.Url.ToString()).GetLeftPart(UriPartial.Path)).ToLower();
                string host = (new Uri(HttpContext.Current.Request.GetBaseURL())).ToString().ToLower();
                if (requestUrlExtension != ".aspx" && !string.IsNullOrEmpty(requestUrlExtension))
                {
                    return;
                }
                //Check for excludes
                //Allowed Folders
                if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Folders))
                {
                    string[] foldersToExclude = Utility.GetSocialAuthConfiguration().Allow.Folders.Split(new char[] { '|' });
                    foreach (string folderName in foldersToExclude)
                    {
                        if (urlWithoutParameters.Contains(host + (host.EndsWith("/") ? "" : "/") + folderName))
                        {
                            return;
                        }
                    }
                }

                //Allowed Files
                if (!string.IsNullOrEmpty(Utility.GetSocialAuthConfiguration().Allow.Files))
                {
                    string[] filesToExclude = Utility.GetSocialAuthConfiguration().Allow.Files.Split(new char[] { '|' });
                    foreach (string fileName in filesToExclude)
                    {
                        if (Regex.IsMatch(urlWithoutParameters, "/" + fileName.ToLower() + "$"))
                        {
                            return;
                        }
                    }
                }



                //If requested page is login URL only, allow it
                string currentUrl = HttpContext.Current.Request.Url.AbsolutePath;
                string loginurl   = Utility.GetSocialAuthConfiguration().Authentication.LoginUrl;
                loginurl = string.IsNullOrEmpty(loginurl) ? "socialauth/loginform.sauth" : loginurl;
                if (currentUrl.ToLower().EndsWith(loginurl.ToLower()))
                {
                    return;
                }

                //If Url is pointing to a .aspx page, authorize it!
                HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                if (cookie != null)
                {
                    HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(FormsAuthentication.Decrypt(cookie.Value)), null);
                }
                else
                {
                    //User is not logged in
                    SocialAuthUser.RedirectToLoginPage();
                }

                if (HttpContext.Current.Session != null)
                {
                    if (SocialAuthUser.IsLoggedIn() && HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] == null)
                    {
                        FormsAuthenticationTicket ticket =
                            new FormsAuthenticationTicket(SessionManager.GetUserSessionGUID().ToString(), false, HttpContext.Current.Session.Timeout);

                        string EncryptedTicket = FormsAuthentication.Encrypt(ticket);
                        cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket);
                        HttpContext.Current.Response.Cookies.Add(cookie);
                    }
                }
            }

            //Often, Forms Cookie persist even where there is no connection. To avoid that!!
            if (HttpContext.Current.Session != null)
            {
                if (SessionManager.ConnectionsCount == 0)
                {
                    if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null && Utility.GetAuthenticationOption() != AUTHENTICATION_OPTION.FORMS_AUTHENTICATION)
                    {
                        if (SessionManager.GetUserSessionGUID().ToString() != FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name)
                        {
                            SocialAuthUser.Disconnect();
                        }
                    }
                }
            }

            if (HttpContext.Current.ApplicationInstance.IsSTSaware())
            {
                if (HttpContext.Current.Session != null)
                {
                    if (SocialAuthUser.IsLoggedIn())
                    {
                        if (SocialAuthUser.GetCurrentUser().GetProfile() != null)
                        {
                            SocialAuthUser.SetClaims();
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
 public override WebResponse ExecuteFeed(string feedUrl, TRANSPORT_METHOD transportMethod)
 {
     return(AuthenticationStrategy.ExecuteFeed(feedUrl, this, SocialAuthUser.GetCurrentUser().GetConnection(ProviderType).GetConnectionToken(), transportMethod));
 }
Exemplo n.º 19
0
        public static void Login(string providername)
        {
            PROVIDER_TYPE providerType = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), providername);

            SocialAuthUser.GetCurrentUser().Login(providerType);
        }
        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            SocialAuthUser.GetCurrentUser().Logout();
            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 21
0
 protected void btnLogout_Click(object sender, EventArgs e)
 {
     SocialAuthUser.GetCurrentUser().Logout("ManualLogin.aspx");
 }
 public void SocialAuthLogin(FormCollection frm)
 {
     SocialAuthUser.GetCurrentUser().Login(PROVIDER_TYPE.FACEBOOK);
 }
Exemplo n.º 23
0
        void UpdateTableByColumns()
        {
            List <PROVIDER_TYPE> providers = SocialAuthUser.GetConnectedProviders();


            foreach (var provider in providers)
            {
                profiles.Add(SocialAuthUser.GetCurrentUser().GetProfile(provider));
            }

            Table tbl = new Table()
            {
                CellSpacing = 0
            };
            //Header Row
            TableHeaderRow trHeader = new TableHeaderRow();

            trHeader.Cells.Add(new TableHeaderCell()
            {
                Text = "Provider/Feature"
            });
            providers.ForEach(x => trHeader.Cells.Add(new TableCell()
            {
                Text = x.ToString()
            }));
            tbl.Rows.Add(trHeader);



            //Start adding Values
            TableRow tr = new TableRow();

            //Provider
            tr.Cells.Add(new TableCell()
            {
                Text = "Provider"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Provider.ToString()
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //Best Possible Identifier
            tr.Cells.Add(new TableCell()
            {
                Text = "Best Possible Identifier", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.GetIdentifier()
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //ID
            tr.Cells.Add(new TableCell()
            {
                Text = "ID"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.ID
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();


            //FirstName
            tr.Cells.Add(new TableCell()
            {
                Text = "FirstName", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.FirstName
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //LastName
            tr.Cells.Add(new TableCell()
            {
                Text = "LastName"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.LastName
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //FullName
            tr.Cells.Add(new TableCell()
            {
                Text = "FullName", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.FullName
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //DisplayName
            tr.Cells.Add(new TableCell()
            {
                Text = "DisplayName"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.DisplayName
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //Email
            tr.Cells.Add(new TableCell()
            {
                Text = "Email", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Email
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();

            //Gender
            tr.Cells.Add(new TableCell()
            {
                Text = "Gender"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Gender
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();


            //ProfileURL
            tr.Cells.Add(new TableCell()
            {
                Text = "ProfileURL", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.ProfileURL
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();


            //ProfilePictureURL
            tr.Cells.Add(new TableCell()
            {
                Text = "ProfilePictureURL"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.ProfilePictureURL
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();


            //Country
            tr.Cells.Add(new TableCell()
            {
                Text = "Country", CssClass = "altTr"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Country
                });
            }

            tbl.Rows.Add(tr);
            tr = new TableRow();


            //Language
            tr.Cells.Add(new TableCell()
            {
                Text = "Language"
            });
            foreach (var p in profiles)
            {
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Language
                });
            }

            tbl.Rows.Add(tr);

            //StringBuilder sb = new StringBuilder();
            //StringWriter sw = new StringWriter(sb);
            //HtmlTextWriter hw = new HtmlTextWriter(sw);
            //tbl.RenderControl(hw);
            //this.profileTable.InnerHtml = sb.ToString();
        }
Exemplo n.º 24
0
        public static ProfileData Getprofile()
        {
            UserProfile profile = SocialAuthUser.GetCurrentUser().GetProfile();

            SessionWrapper.LinkedinData     = null;
            SessionWrapper.ResumeParserData = null;

            ProfileData userProfile = new ProfileData();

            userProfile.Country = profile.Country;
            // userProfile.DateOfBirth = profile.DateOfBirth;
            userProfile.DisplayName       = profile.DisplayName;
            userProfile.Email             = profile.Email;
            userProfile.FirstName         = profile.FirstName;
            userProfile.LastName          = profile.LastName;
            userProfile.ProfilePictureURL = profile.ProfilePictureURL;
            userProfile.ProfileURL        = profile.ProfileURL;
            userProfile.Provider          = profile.Provider;
            userProfile.Username          = profile.Username;


            string format = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;

            string[] formats = { "MM/dd/yyyy", "dd/MM/yyyy", "dd/M/yyyy", format };
            DateTime dt;

            bool success = DateTime.TryParseExact(profile.DateOfBirth, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);

            if (success)
            {
                userProfile.DateOfBirth = dt.ToString("MM/dd/yyyy");
            }

            try
            {
                if (SocialAuthUser.CurrentProvider == PROVIDER_TYPE.LINKEDIN)
                {
                    var result = SocialAuthUser.GetCurrentUser().ExecuteFeed(
                        "https://api.linkedin.com/v1/people/~:(headline,first-name,last-name,educations,positions,phone-numbers,main-address)",
                        TRANSPORT_METHOD.GET, PROVIDER_TYPE.LINKEDIN);

                    string xml = new StreamReader(result.GetResponseStream()).ReadToEnd();

                    string[] Titles  = { "first-name", "last-name", "relation-to-viewer", "num-recommenders", "current-status", "current-status-timestamp", "start-date", "is-current", "school-name", "end-date", "member-url-resources", "member-url", "api-standard-profile-request", "http-header", "site-standard-profile-request", "picture-url", "field-of-study", "phone-numbers", "phone-type", "main-address" };
                    string[] Titles1 = { "FirstName", "LastName", "RelationToViewer", "NumRecommenders", "CurrentStatus", "CurrentStatusTimestamp", "StartDate", "IsCurrent", "SchoolName", "EndDate", "MemberUrlResources", "MemberUrl", "ApiStandardProfileRequest", "HttpHeader", "SiteStandardProfileRequest", "PictureUrl", "FieldOfStudy", "phonenumbers", "phonetype", "MainAddress" };
                    for (int loopCount = 0; loopCount < Titles.Count(); loopCount++)
                    {
                        xml = xml.Replace(Titles[loopCount], Titles1[loopCount]);
                    }

                    int index = xml.IndexOf("<phonenumbers total=");

                    string xmlsubstring = xml.Substring(index + 20);

                    index = xmlsubstring.IndexOf(">");
                    string total = xmlsubstring.Substring(0, index).Replace("\"", "");

                    if (total.Contains("/"))
                    {
                        total = total.Replace("/", "");
                    }

                    try
                    {
                        for (int i = 0; i < Convert.ToInt32(total.Trim()); i++)
                        {
                            var regex = new Regex("phone-number");
                            xml = regex.Replace(xml, "phonenumber", i + 1);
                            xml = regex.Replace(xml, "phoneNumber", i + 2);
                            xml = regex.Replace(xml, "phonenumber", i + 1);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }

                    person person = (person)SerializationHelper.XmlDeserializeFromString(xml, typeof(person));

                    if (person.MainAddress != null)
                    {
                        userProfile.Address = person.MainAddress;
                    }

                    if (person.phonenumbers != null)
                    {
                        if (person.phonenumbers.phonenumber != null)
                        {
                            userProfile.PhoneNumber = person.phonenumbers.phonenumber.phoneNumber;
                        }
                    }
                    FillSessionValues(person);
                }
            }
            catch (Exception e)
            {
            }
            return(userProfile);
        }
Exemplo n.º 25
0
        void UpdateTableByRows()
        {
            List <PROVIDER_TYPE> providers = SocialAuthUser.GetConnectedProviders();

            //var result = SocialAuthUser.GetCurrentUser().ExecuteFeed(
            //    "http://api.linkedin.com/v1/people/~/connections:(headline,first-name,last-name,educations)",
            //    TRANSPORT_METHOD.GET, PROVIDER_TYPE.LINKEDIN);

            foreach (var provider in providers)
            {
                profiles.Add(SocialAuthUser.GetCurrentUser().GetProfile(provider));
            }

            foreach (UserProfile p in profiles)
            {
                HtmlGenericControl tableContainer = new HtmlGenericControl("div");
                tableContainer.Attributes.Add("style", "float:left;padding:10px 10px 10px 10px;width:400px;height:210px;");

                Table tbl = new Table()
                {
                    CellSpacing = 0
                };
                tbl.Attributes.Add("style", "width:100%");
                //Header Row
                TableHeaderRow trHeader = new TableHeaderRow();
                TableCell      tc       = new TableHeaderCell()
                {
                    Text = p.Provider.ToString()
                };
                tc.ColumnSpan = 2;
                trHeader.Cells.Add(tc);
                tbl.Rows.Add(trHeader);



                //Start adding Values
                TableRow tr = new TableRow();

                ////Provider
                //tr.Cells.Add(new TableCell() { Text = "Provider" });
                //tr.Cells.Add(new TableCell() { Text = p.Provider.ToString() });

                //tbl.Rows.Add(tr);
                //tr = new TableRow();

                //Best Possible Identifier
                tr.Cells.Add(new TableCell()
                {
                    Text = "Best Possible Identifier", CssClass = "altTr"
                });
                tr.Cells.Add(new TableCell()
                {
                    Text = p.GetIdentifier()
                });

                tbl.Rows.Add(tr);
                tr = new TableRow();

                //ID
                tr.Cells.Add(new TableCell()
                {
                    Text = "ID"
                });
                tr.Cells.Add(new TableCell()
                {
                    Text = p.ID
                });

                tbl.Rows.Add(tr);
                tr = new TableRow();

                ////FirstName
                //tr.Cells.Add(new TableCell() { Text = "FirstName", CssClass = "altTr" });
                //tr.Cells.Add(new TableCell() { Text = p.FirstName });
                //tbl.Rows.Add(tr);
                //tr = new TableRow();

                ////LastName
                //tr.Cells.Add(new TableCell() { Text = "LastName" });
                //tr.Cells.Add(new TableCell() { Text = p.LastName });
                //tbl.Rows.Add(tr);
                //tr = new TableRow();

                //FullName
                tr.Cells.Add(new TableCell()
                {
                    Text = "FullName", CssClass = "altTr"
                });
                tr.Cells.Add(new TableCell()
                {
                    Text = p.FullName
                });
                tbl.Rows.Add(tr);
                tr = new TableRow();

                ////DisplayName
                //tr.Cells.Add(new TableCell() { Text = "DisplayName" });
                //tr.Cells.Add(new TableCell() { Text = p.DisplayName });
                //tbl.Rows.Add(tr);
                //tr = new TableRow();

                //Email
                tr.Cells.Add(new TableCell()
                {
                    Text = "Email"
                });
                tr.Cells.Add(new TableCell()
                {
                    Text = p.Email
                });

                tbl.Rows.Add(tr);
                tr = new TableRow();

                ////Gender
                //tr.Cells.Add(new TableCell() { Text = "Gender" });
                //tr.Cells.Add(new TableCell() { Text = p.Gender });

                //tbl.Rows.Add(tr);
                //tr = new TableRow();


                ////ProfileURL
                //tr.Cells.Add(new TableCell() { Text = "ProfileURL", CssClass = "altTr" });
                //tr.Cells.Add(new TableCell() { Text = p.ProfileURL });

                //tbl.Rows.Add(tr);
                //tr = new TableRow();


                //ProfilePictureURL

                tr.Cells.Add(new TableCell()
                {
                    Text = "ProfilePictureURL", CssClass = "altTr"
                });
                TableCell profilePicCell = new TableCell();
                if (!string.IsNullOrEmpty(p.ProfilePictureURL))
                {
                    profilePicCell.Text = "<img src=\"" + p.ProfilePictureURL + "\" height=\"100\" width=\"100\">";
                }
                else
                {
                    profilePicCell.Text = "<img src=\"images/notavailable.png\" />";
                }
                tr.Cells.Add(profilePicCell);

                tbl.Rows.Add(tr);
                //tr = new TableRow();


                ////Country
                //tr.Cells.Add(new TableCell() { Text = "Country", CssClass = "altTr" });
                //tr.Cells.Add(new TableCell() { Text = p.Country });

                //tbl.Rows.Add(tr);
                //tr = new TableRow();


                ////Language
                //tr.Cells.Add(new TableCell() { Text = "Language" });
                //tr.Cells.Add(new TableCell() { Text = p.Language });

                //tbl.Rows.Add(tr);
                tableContainer.Controls.Add(tbl);
                divContent.Controls.Add(tableContainer);
            }



            //StringBuilder sb = new StringBuilder();
            //StringWriter sw = new StringWriter(sb);
            //HtmlTextWriter hw = new HtmlTextWriter(sw);
            //tbl.RenderControl(hw);
            //this.profileTable.InnerHtml = sb.ToString();
        }
Exemplo n.º 26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Required to be done when using custom mode
        //if (!SocialAuthUser.IsLoggedIn())
        //    SocialAuthUser.RedirectToLoginPage("ManualLogin.aspx");


        foreach (PROVIDER_TYPE p in SocialAuthUser.GetConnectedProviders())
        {
            divConnections.Controls.Add(new Literal()
            {
                Text = "<br>Connected to: <b>" + p.ToString() + "</b> with identifier <b>" +
                       SocialAuthUser.GetCurrentUser().GetProfile(p).GetIdentifier() + "</b>"
            });
            LinkButton logoutBtn = new LinkButton()
            {
                Text = "[Logout from " + p.ToString() + "]", CommandArgument = p.ToString()
            };
            logoutBtn.Command += new CommandEventHandler(btnIndividualLogout_Click);
            divConnections.Controls.Add(logoutBtn);
        }

        if (SocialAuthUser.IsLoggedIn())
        {
            IsSTSaware     = HttpContext.Current.ApplicationInstance.IsSTSaware();
            Provider       = User.Identity.GetProvider();
            Pid            = User.Identity.GetProfile().ID;
            Identifier     = User.Identity.GetProfile().GetIdentifier();
            Username       = User.Identity.GetProfile().Username;
            Displayname    = User.Identity.GetProfile().DisplayName;
            Email          = User.Identity.GetProfile().Email;
            Fullname       = User.Identity.GetProfile().FullName;
            FirstName      = User.Identity.GetProfile().FirstName;
            LastName       = User.Identity.GetProfile().LastName;
            DateOfBirth    = User.Identity.GetProfile().DateOfBirth;
            Gender         = User.Identity.GetProfile().Gender.ToString();
            ProfileURL     = User.Identity.GetProfile().ProfileURL;
            ProfilePicture = User.Identity.GetProfile().ProfilePictureURL;
            Country        = User.Identity.GetProfile().Country;
            Language       = User.Identity.GetProfile().Language;
            AccessToken    = SocialAuthUser.GetCurrentUser().GetAccessToken();
            bool IsAlternate = false;

            try
            {
                User.Identity.GetContacts().ForEach(
                    x =>
                {
                    HtmlTableRow tr = new HtmlTableRow();
                    tr.Attributes.Add("class", (IsAlternate) ? "dark" : "light");
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.Name
                    });
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.Email
                    });
                    tr.Cells.Add(new HtmlTableCell()
                    {
                        InnerText = x.ProfileURL
                    });
                    tblContacts.Rows.Add(tr);
                    IsAlternate = !IsAlternate;
                }

                    );
                ContactsCount = (tblContacts.Rows.Count - 1).ToString();
            }
            catch (Exception ex)
            {
                contacts.InnerHtml = "<error>" + ex.Message + "</error>";
            }
        }
        else
        {
            Response.Write("You are not logged in..");
        }
    }
 private void imgB_Command(object sender, EventArgs e)
 {
     SocialAuthUser.GetCurrentUser().Login((PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), ((CommandEventArgs)e).CommandArgument.ToString()), DefaultURL);
 }
Exemplo n.º 28
0
        public static string GetFriends()
        {
            var friends = SocialAuthUser.GetCurrentUser().GetContacts();

            return(new JavaScriptSerializer().Serialize(friends));
        }