Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="providerType"></param>
        /// <param name="map"></param>
        /// <returns></returns>
        public WebResponse ExecuteFeed(PROVIDER_TYPE providerType, string url)
        {
            var provider = ProviderFactory.GetProvider(providerType, socialAuthConfiguration) as Provider;

            //Token token = accessGrant[providerType];
            return(provider.ExecuteFeed(url, TRANSPORT_METHOD.GET));
        }
Exemple #2
0
 /// <summary>
 /// Allow user to remove an existing connection token.
 /// </summary>
 /// <param name="providerType"></param>
 public void RemoveConnection(PROVIDER_TYPE providerType)
 {
     if (IsConnectedWith(providerType))
     {
         accessGrant.Remove(providerType);
     }
 }
Exemple #3
0
 /// <summary>
 /// Facebook publish
 /// </summary>
 /// <param name="accessToken"></param>
 public FormOpenAuthPublish(CmWinServiceAPI db, PROVIDER_TYPE provider_type, SocialAuthManager manager)
 {
     this.db            = db;
     this.provider_type = provider_type;
     this.manager       = manager;
     InitializeComponent();
 }
    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());
    }
Exemple #5
0
        /// <summary>
        /// Returns contacts from current connection or specified provider
        /// </summary>
        /// <param name="providerType">Provider Type (Connection should exist else exception is thrown)</param>
        /// <returns></returns>
        public List <Contact> GetContacts(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
        {
            if (providerType != PROVIDER_TYPE.NOT_SPECIFIED)
            {
                if (SessionManager.IsConnectedWith(providerType))
                {
                    return(GetConnection(providerType).GetContacts());
                }
                else
                {
                    throw new InvalidSocialAuthConnectionException(providerType);
                }
            }
            else
            {
                if (SessionManager.IsConnected)
                {
                    return(CurrentConnection.GetContacts());
                }

                else
                {
                    throw new InvalidSocialAuthConnectionException();
                }
            }
        }
        public static string GetFriends()
        {
            PROVIDER_TYPE     provider = PROVIDER_TYPE.FACEBOOK;
            SocialAuthManager manager  = HttpContext.Current.Session["socialauth"] as SocialAuthManager;
            var response = manager.ExecuteFeed(PROVIDER_TYPE.FACEBOOK, "https://graph.facebook.com/me/friends");

            return(new StreamReader(response.GetResponseStream()).ReadToEnd());
        }
Exemple #7
0
 /// <summary>
 /// Logs user out of local application (User may still remain logged in at provider)
 /// </summary>
 /// <param name="loginUrl">Where should user be redirected after logout. (Only applicable when using custom authentication)</param>
 /// <param name="callback">Delegate invoked (if specified) just before redirecting user to login page</param>
 /// <param name="provider"> </param>
 public void Logout(string loginUrl = "", Action callback = null, PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     if (providerType != PROVIDER_TYPE.NOT_SPECIFIED && GetConnectedProviders().Count > 1)
     {
         SessionManager.RemoveConnectionToken(providerType);
         return;
     }
     Disconnect(loginUrl, callback);
 }
        //Returns a provider object for specified PROVIDER_TYPE
        public static IProvider GetProvider(PROVIDER_TYPE requestedProvider)
        {
            //Provider's list not initialized yet
            if (availableProviders == null)
                LoadProviders();

            return (IProvider)(availableProviders.Where
                        (p => ((Provider)p.Value).ProviderType == requestedProvider).Single().Value);
        }
Exemple #9
0
        //Returns a provider object for specified PROVIDER_TYPE
        public static IProvider GetProvider(PROVIDER_TYPE requestedProvider, SocialAuthConfiguration config)
        {
            //Provider's list not initialized yet
            //if (availableProviders == null)
            LoadProviders(config);


            return((IProvider)(availableProviders.Where
                                   (p => ((Provider)p.Value).ProviderType == requestedProvider).Single().Value));
        }
Exemple #10
0
        /// <summary>
        /// Provides URL for redirecting user to specified provider
        /// </summary>
        public string GetLoginRedirectUrl(PROVIDER_TYPE providerType, string returnUrl)
        {
            var provider = ProviderFactory.GetProvider(providerType);

            provider.ConnectionToken = new Token()
            {
                Domain  = "http://opensource.brickred.com/socialauthdemo/",
                Profile = new UserProfile(providerType)
            };
            return(provider.GetLoginRedirectUrl(returnUrl));
        }
Exemple #11
0
        /// <summary>
        /// Provides URL for redirecting user to specified provider
        /// </summary>
        public string GetLoginRedirectUrl(PROVIDER_TYPE providerType, string returnUrl)
        {
            var provider = ProviderFactory.GetProvider(providerType, socialAuthConfiguration);

            provider.ConnectionToken = new Token()
            {
                Domain  = "http://www.chojogakuin.com",
                Profile = new UserProfile(providerType)
            };
            return(provider.GetLoginRedirectUrl(returnUrl));
        }
Exemple #12
0
        //Returns a provider object for specified PROVIDER_TYPE
        public static IProvider GetProvider(PROVIDER_TYPE requestedProvider)
        {
            //Provider's list not initialized yet
            if (availableProviders == null)
            {
                LoadProviders();
            }


            return((IProvider)(availableProviders.Where
                                   (p => ((Provider)p.Value).ProviderType == requestedProvider).Single().Value));
        }
        /// <summary>
        /// Connects and retrieves access token from provider
        /// </summary>
        /// <param name="providerType"></param>
        /// <param name="redirectResponse"></param>
        /// <param name="overrideConnection"></param>
        /// <returns></returns>
        public bool Connect(PROVIDER_TYPE providerType, string redirectResponse, bool overrideConnection = false)
        {
            if (overrideConnection && IsConnectedWith(providerType)) return true;

            var provider = ProviderFactory.GetProvider(providerType) as Provider;
            Token token = new Token();
            token.Domain = "http://opensource.brickred.com/socialauthdemo/";
            accessGrant.Add(providerType, token);
            provider.ConnectionToken = token;
            provider.LoginCallback(Utility.GetQuerystringParameters(redirectResponse), (x,y) => { });
            return true;
        }
        protected void btn_Click(object sender, EventArgs e)
        {
            //We need to get user's selected provider enumerator.
            PROVIDER_TYPE selectedProvider = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), ((Button)sender).Text.ToUpper());

            //Initialize User
            SocialAuthUser objUser = new SocialAuthUser(selectedProvider);

            //Call Login
            objUser.Login(returnUrl: "ManualLogin.aspx");
            //Login method also accepts a parameter for URL to which user should be redirected after login. If not specified,
            //automatically defaultUrl as set in Web.Config will be picked for redirection.
        }
Exemple #15
0
 //--------- Authentication Methods
 /// <summary>
 ///
 /// </summary>
 /// <param name="returnUrl">URL where user should return after login.</param>
 /// <param name="callback">Delegate invoked just before redirecting user after successful login</param>
 public void Login(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED, string returnUrl = "", Action callback = null, string errorRedirectURL = "", bool skipRedirectionIfAlreadyConnected = false)
 {
     if (this.providerType == PROVIDER_TYPE.NOT_SPECIFIED && providerType == PROVIDER_TYPE.NOT_SPECIFIED)
     {
         throw new Exception("Provider not specified. Either pass provider as parameter to Login or pass it in constructor");
     }
     if (callback != null)
     {
         SessionManager.SetCallback(callback);
     }
     if (providerType == PROVIDER_TYPE.NOT_SPECIFIED && this.providerType != PROVIDER_TYPE.NOT_SPECIFIED)
     {
         providerType = this.providerType;
     }
     Connect(providerType, returnUrl, errorRedirectURL, skipRedirectionIfAlreadyConnected);
 }
        internal static IProvider GetConnection(PROVIDER_TYPE providerType)
        {
            IProvider provider = null;
            //There are no connections
            var lastConnection = userSession.connectedTokens.Find(x => x.Provider == providerType);

            if (lastConnection != null)
            {
                provider = ProviderFactory.GetProvider(lastConnection.Provider, null);
                return(provider);
            }
            else
            {
                return(null);
            }
        }
Exemple #17
0
        /// <summary>
        /// Connects to a provider (Same as Login())
        /// </summary>
        /// <param name="providerType">Provider to which connection has to be established</param>
        /// <param name="returnURL">Optional URL where user will be redirected after login (for this provider only)</param>
        internal static void Connect(PROVIDER_TYPE providerType, string returnURL = "", string errorURL = "", bool skipRedirectionIfAlreadyConnected = false)
        {
            returnURL = returnURL ?? "";
            if (!returnURL.ToLower().StartsWith("http") && returnURL.Length > 0)
            {
                returnURL = HttpContext.Current.Request.GetBaseURL() + returnURL;
            }

            try
            {
                //User is already connected. return or redirect
                if (IsConnectedWith(providerType))
                {
                    if (skipRedirectionIfAlreadyConnected)
                    {
                        return;
                    }
                    return;
                }

                SessionManager.InProgressToken = (new Token()
                {
                    Provider = providerType,
                    Domain = HttpContext.Current.Request.GetBaseURL(),
                    UserReturnURL = returnURL,
                    SessionGUID = SessionManager.GetUserSessionGUID(),
                    Profile = new UserProfile()
                    {
                        Provider = providerType
                    }
                });
                SessionManager.InProgressToken.Profile.Provider = providerType;
                if (!string.IsNullOrEmpty(errorURL))
                {
                    SessionManager.ErrorURL = HttpContext.Current.Request.GetBaseURL() + errorURL;
                }

                //CONNECT WITH PROVIDER
                var provider = ((IProviderConnect)ProviderFactory.GetProvider(providerType));
                provider.ConnectionToken = InProgressToken();
                provider.Connect();
            }
            catch
            {
                throw;
            }
        }
Exemple #18
0
        /// <summary>
        /// Connects and retrieves access token from provider
        /// </summary>
        /// <param name="providerType"></param>
        /// <param name="redirectResponse"></param>
        /// <param name="overrideConnection"></param>
        /// <returns></returns>
        public bool Connect(PROVIDER_TYPE providerType, string redirectResponse, bool overrideConnection = false)
        {
            if (overrideConnection && IsConnectedWith(providerType))
            {
                return(true);
            }


            var   provider = ProviderFactory.GetProvider(providerType, socialAuthConfiguration) as Provider;
            Token token    = new Token();

            token.Domain = "http://www.chojogakuin.com";
            accessGrant.Add(providerType, token);
            provider.ConnectionToken = token;
            provider.LoginCallback(Utility.GetQuerystringParameters(redirectResponse), (x, y) => { });
            return(true);
        }
Exemple #19
0
 /// <summary>
 /// Get Access Token for Current or specified provider
 /// </summary>
 /// <param name="providerType"></param>
 /// <returns></returns>
 public string GetAccessToken(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     if (providerType == PROVIDER_TYPE.NOT_SPECIFIED)
     {
         return(SessionManager.GetConnectionToken(SessionManager.GetCurrentConnection().ProviderType).AccessToken);
     }
     else
     {
         if (IsConnectedWith(providerType))
         {
             return(SessionManager.GetConnectionToken(providerType).AccessToken);
         }
         else
         {
             throw new InvalidSocialAuthConnectionException(providerType);
         }
     }
 }
Exemple #20
0
        //------------ Data Retrieval Methods
        /// <summary>
        /// Returns Profile from current connection or specified provider
        /// </summary>
        /// <param name="providerType">Provider Type (Connection should exist else exception is thrown)</param>
        /// <returns></returns>
        public UserProfile GetProfile(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
        {
            if (providerType != PROVIDER_TYPE.NOT_SPECIFIED)
            {
                if (SessionManager.IsConnectedWith(providerType))
                {
                    if (GetConnection(providerType).GetConnectionToken().Profile.IsSet)
                    {
                        return(GetConnection(providerType).GetConnectionToken().Profile);
                    }
                    else
                    {
                        return(SessionManager.GetConnection(providerType).GetProfile());
                    }
                }
                else
                {
                    throw new InvalidSocialAuthConnectionException(providerType);
                }
            }
            else
            {
                if (SessionManager.IsConnected)
                {
                    if (GetCurrentConnectionToken().Profile.IsSet)
                    {
                        return(GetCurrentConnectionToken().Profile);
                    }
                    else
                    {
                        return(SessionManager.GetCurrentConnection().GetProfile());
                    }
                }

                else
                {
                    throw new InvalidSocialAuthConnectionException();
                }
            }
        }
 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);
     }
 }
 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>");
     }
 }
        internal static bool IsConnectedWith(PROVIDER_TYPE providerType)
        {
            return (userSession.connectedTokens.Exists(x => x.Provider == providerType));

        }
Exemple #24
0
 //--------- Authentication Methods
 /// <summary>
 /// 
 /// </summary>
 /// <param name="returnUrl">URL where user should return after login.</param>
 /// <param name="callback">Delegate invoked just before redirecting user after successful login</param>
 public void Login(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED, string returnUrl = "", Action callback = null, string errorRedirectURL = "", bool skipRedirectionIfAlreadyConnected=false)
 {
     if (this.providerType == PROVIDER_TYPE.NOT_SPECIFIED && providerType == PROVIDER_TYPE.NOT_SPECIFIED)
         throw new Exception("Provider not specified. Either pass provider as parameter to Login or pass it in constructor");
     if (callback != null)
         SessionManager.SetCallback(callback);
     if (providerType == PROVIDER_TYPE.NOT_SPECIFIED && this.providerType != PROVIDER_TYPE.NOT_SPECIFIED)
         providerType = this.providerType;
     Connect(providerType, returnUrl, errorRedirectURL,skipRedirectionIfAlreadyConnected);
 }
 public UserProfile(PROVIDER_TYPE provider)
 {
     this.Provider = provider;
 }
 public InvalidSocialAuthConnectionException(PROVIDER_TYPE providertype = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     this.providertype = providertype;
 }
Exemple #27
0
 public InvalidSocialAuthConnectionException(PROVIDER_TYPE providertype = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     this.providertype = providertype;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="providerType"></param>
 /// <param name="map"></param>
 /// <returns></returns>
 public WebResponse ExecuteFeed(PROVIDER_TYPE providerType, string url)
 {
     var provider = ProviderFactory.GetProvider(providerType) as Provider;
     Token token = accessGrant[providerType];
     return provider.ExecuteFeed(url, TRANSPORT_METHOD.GET);
 }
        /// <summary>
        /// 媒体连接测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs ex)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                string mediaType   = cmbMediaType.Text;
                string mediaUrl    = txtMediaURL.Text;
                string appKey      = txtAppKey.Text;
                string appPassword = txtAppPassword.Text;
                string user        = txtUserName.Text;
                string password    = txtPassword.Text;
                string content     = txtOther.Text;
                string pic         = txtTestImage.Text;
                if (File.Exists(pic))
                {
                    switch (mediaType)
                    {
                    case "TENCENT":
                        FormQWeiboLogin LoginDlg = new FormQWeiboLogin(appKey, appPassword, user, password);
                        LoginDlg.ShowDialog();
                        if (LoginDlg.Comfirm)
                        {
                            OauthKey oauthKey = new OauthKey();
                            oauthKey.customKey    = LoginDlg.AppKey;
                            oauthKey.customSecret = LoginDlg.AppSecret;
                            oauthKey.tokenKey     = LoginDlg.AccessKey;
                            oauthKey.tokenSecret  = LoginDlg.AccessSecret;

                            ///发送带图片微博
                            t            twit = new t(oauthKey, "json");
                            UTF8Encoding utf8 = new UTF8Encoding();

                            string ret = twit.add_pic(utf8.GetString(utf8.GetBytes(content)),
                                                      utf8.GetString(utf8.GetBytes("127.0.0.1")),
                                                      utf8.GetString(utf8.GetBytes("")),
                                                      utf8.GetString(utf8.GetBytes("")),
                                                      utf8.GetString(utf8.GetBytes(pic))
                                                      );

                            string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language);
                            MessageBox.Show(msg);
                        }
                        break;

                    case "WORDPRESS":
                        IMetaWeblog          metaWeblog     = (IMetaWeblog)XmlRpcProxyGen.Create(typeof(IMetaWeblog));
                        XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)metaWeblog;
                        clientProtocol.Url = mediaUrl;
                        string picURL   = null;
                        string filename = pic;
                        if (File.Exists(filename))
                        {
                            FileData fileData = default(FileData);
                            fileData.name = Path.GetFileName(filename);
                            fileData.type = Path.GetExtension(filename);
                            try
                            {
                                FileInfo fi = new FileInfo(filename);
                                using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
                                {
                                    fileData.bits = br.ReadBytes((int)fi.Length);
                                }
                                UrlData urlData = metaWeblog.newMediaObject("6", user, password, fileData);
                                picURL = urlData.url;
                            }
                            catch (Exception exc)
                            {
                                NCLogger.GetInstance().WriteExceptionLog(exc);
                            }
                        }

                        Post newBlogPost = default(Post);
                        newBlogPost.title         = content;
                        newBlogPost.description   = "";
                        newBlogPost.categories    = new string[1];
                        newBlogPost.categories[0] = cmbCategry.Text;
                        newBlogPost.dateCreated   = System.DateTime.Now;
                        if (picURL != null)
                        {
                            newBlogPost.description += "<br><img src='" + picURL + "'/>";
                        }

                        try
                        {
                            string result = metaWeblog.newPost("6", user,
                                                               password, newBlogPost, true);
                        }
                        catch (Exception ex2)
                        {
                            NCLogger.GetInstance().WriteExceptionLog(ex2);
                        }

                        break;

                    case "FACEBOOK":
                        var fbLoginDlg = new FormFacebookLogin(appKey, user, password);
                        fbLoginDlg.ShowDialog();
                        if (fbLoginDlg.FacebookOAuthResult != null && fbLoginDlg.FacebookOAuthResult.IsSuccess)
                        {
                            string _accessToken = fbLoginDlg.FacebookOAuthResult.AccessToken;
                            var    fb           = new FacebookClient(_accessToken);

                            // make sure to add event handler for PostCompleted.
                            fb.PostCompleted += (o, e) =>
                            {
                                // incase you support cancellation, make sure to check
                                // e.Cancelled property first even before checking (e.Error!=null).
                                if (e.Cancelled)
                                {
                                    // for this example, we can ignore as we don't allow this
                                    // example to be cancelled.

                                    // you can check e.Error for reasons behind the cancellation.
                                    var cancellationError = e.Error;
                                }
                                else if (e.Error != null)
                                {
                                    // error occurred
                                    this.BeginInvoke(new MethodInvoker(
                                                         () =>
                                    {
                                        MessageBox.Show(e.Error.Message);
                                    }));
                                }
                                else
                                {
                                    // the request was completed successfully

                                    // make sure to be on the right thread when working with ui.
                                    this.BeginInvoke(new MethodInvoker(
                                                         () =>
                                    {
                                        //MessageBox.Show("Picture uploaded successfully");

                                        Application.DoEvents();
                                    }));
                                }
                            };

                            dynamic parameters = new ExpandoObject();
                            parameters.message = content;
                            parameters.source  = new FacebookMediaObject
                            {
                                ContentType = "image/jpeg",
                                FileName    = Path.GetFileName(pic)
                            }.SetValue(File.ReadAllBytes(pic));

                            fb.PostAsync("me/photos", parameters);
                        }

                        break;

                    case "TWITTER":
                        TwitterService   service = new TwitterService(appKey, appPassword);
                        FormTwitterLogin form    = new FormTwitterLogin(db, service);
                        if (form.ShowDialog() == DialogResult.OK)
                        {
                            SendTweetWithMediaOptions sendOptions = new SendTweetWithMediaOptions();
                            sendOptions.Images = new Dictionary <string, Stream>();
                            sendOptions.Images.Add(Path.GetFileName(pic),
                                                   new FileStream(pic, FileMode.Open, FileAccess.Read));
                            if (content.Length > 70)
                            {
                                content = content.Substring(0, 70);
                            }
                            sendOptions.Status = content;

                            if (service.SendTweetWithMedia(sendOptions) != null)
                            {
                                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0057I", db.Language);
                                MessageBox.Show(msg);
                            }
                        }
                        break;

                    case "LINKEDIN":
                        OAuth1 _OAuthLinkedin = new OAuth1(db);
                        _OAuthLinkedin.Settings_Provider              = "Linkedin";
                        _OAuthLinkedin.Settings_ConsumerKey           = appKey;
                        _OAuthLinkedin.Settings_ConsumerSecret        = appPassword;
                        _OAuthLinkedin.Settings_AccessToken_page      = "https://api.linkedin.com/uas/oauth/accessToken";
                        _OAuthLinkedin.Settings_Authorize_page        = "https://api.linkedin.com/uas/oauth/authorize";
                        _OAuthLinkedin.Settings_RequestToken_page     = "https://api.linkedin.com/uas/oauth/requestToken";
                        _OAuthLinkedin.Settings_Redirect_URL          = "http://www.chojo.co.jp/";
                        _OAuthLinkedin.Settings_User_agent            = "CJW";
                        _OAuthLinkedin.Settings_OAuth_Realm_page      = "https://api.linkedin.com/";
                        _OAuthLinkedin.Settings_GetProfile_API_page   = "https://api.linkedin.com/v1/people/~/";
                        _OAuthLinkedin.Settings_StatusUpdate_API_page = "https://api.linkedin.com/v1/people/~/current-status";
                        _OAuthLinkedin.getRequestToken();
                        _OAuthLinkedin.authorizeToken();
                        String accessToken = _OAuthLinkedin.getAccessToken();
                        try
                        {
                            string ret = _OAuthLinkedin.APIWebRequest("POST", _OAuthLinkedin.Settings_StatusUpdate_API_page, pic);
                            string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                            xml += "<current-status>" + txtOther.Text + "<img src =" + ret + "/>" + "</current-status>";
                            _OAuthLinkedin.APIWebRequest("PUT", _OAuthLinkedin.Settings_StatusUpdate_API_page, xml);
                        }
                        catch (Exception exp)
                        {
                            MessageBox.Show(exp.Message);
                        }

                        break;

                    case "MSN":
                    case "GOOGLE":
                    case "YAHOO":
                        PROVIDER_TYPE provider_type = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), mediaType);
                        setConfigure(user, password, mediaType);
                        FormAuthSocialLogin loginForm = new FormAuthSocialLogin(db, provider_type, socialAuthManager);
                        if (loginForm.ShowDialog() == DialogResult.OK)
                        {
                            string msgs     = HttpUtility.UrlEncode(content);
                            string endpoint = mediaUrl + msgs;

                            string body = String.Empty;
                            //byte[] reqbytes = new ASCIIEncoding().GetBytes(body);
                            byte[] reqbytes = File.ReadAllBytes(pic);
                            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(pic));
                            var response = socialAuthManager.ExecuteFeed(
                                endpoint,
                                TRANSPORT_METHOD.POST,
                                provider_type,
                                reqbytes,
                                headers
                                );
                        }
                        break;
                    }
                }
                else
                {
                    string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0058I", db.Language);
                    MessageBox.Show(msg);
                }
            }
            else
            {
                string msg = NCMessage.GetInstance(db.Language).GetMessageById("CM0050I", db.Language);
                MessageBox.Show(msg);
            }
        }
 public static string UserDeniedAccess(PROVIDER_TYPE providerType, QueryParameters collection)
 {
     return "User denied access to share his details with this application";
 }
 private void Inicializa()
 {
     m_oConnection = null;
     m_oCommand = null;
     m_oTransaction = null;
     m_sConnectionString = null;
     m_nroTransaction = 0;
     m_nCommandTimeout = 0;
     m_nRetryConnect = 3;
     m_bDisposed = false;
     m_bConnected = false;
     m_sProviderAssembly = null;
     m_sProviderConnectionClass = null;
     m_sProviderCommandBuilderClass = null;
     m_eProvider = PROVIDER_TYPE.PROVIDER_NONE;
     m_idConexion = 0;
     m_oDataReader = null;
 }
Exemple #32
0
 /// <summary>
 /// Get Access Token for Current or specified provider
 /// </summary>
 /// <param name="providerType"></param>
 /// <returns></returns>
 public string GetAccessToken(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     if (providerType == PROVIDER_TYPE.NOT_SPECIFIED)
     {
         return SessionManager.GetConnectionToken(SessionManager.GetCurrentConnection().ProviderType).AccessToken;
     }
     else
     {
         if (IsConnectedWith(providerType))
             return SessionManager.GetConnectionToken(providerType).AccessToken;
         else
             throw new InvalidSocialAuthConnectionException(providerType);
     }
 }
 internal static Token GetConnectionToken(PROVIDER_TYPE providerType)
 {
     var connectionToken = userSession.connectedTokens.Find(x => x.Provider == providerType);
     return connectionToken;
 }
Exemple #34
0
 //--------- Constructor (Optional and is for backward compatibility)
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="providerType">Provider Type for this connection</param>
 public SocialAuthUser(PROVIDER_TYPE providerType)
 {
     this.providerType = providerType;
 }
Exemple #35
0
        /// <summary>
        /// Connects to a provider (Same as Login())
        /// </summary>
        /// <param name="providerType">Provider to which connection has to be established</param>
        /// <param name="returnURL">Optional URL where user will be redirected after login (for this provider only)</param>
        internal static void Connect(PROVIDER_TYPE providerType, string returnURL = "", string errorURL = "", bool skipRedirectionIfAlreadyConnected=false)
        {
            returnURL = returnURL ?? "";
            if (!returnURL.ToLower().StartsWith("http") && returnURL.Length > 0)
                returnURL = HttpContext.Current.Request.GetBaseURL() + returnURL;

            try
            {

                //User is already connected. return or redirect
                if (IsConnectedWith(providerType))
                {
                    if (skipRedirectionIfAlreadyConnected)
                        return;
                    return;
                }

                SessionManager.InProgressToken = (new Token()
                {
                    Provider = providerType,
                    Domain = HttpContext.Current.Request.GetBaseURL(),
                    UserReturnURL = returnURL,
                    SessionGUID = SessionManager.GetUserSessionGUID(),
                    Profile = new UserProfile() { Provider = providerType }

                });
                SessionManager.InProgressToken.Profile.Provider = providerType;
                if (!string.IsNullOrEmpty(errorURL))
                    SessionManager.ErrorURL = HttpContext.Current.Request.GetBaseURL() + errorURL;

                //CONNECT WITH PROVIDER
                var provider = ((IProviderConnect)ProviderFactory.GetProvider(providerType));
                provider.ConnectionToken = InProgressToken();
                provider.Connect();
            }
            catch
            {
                throw;
            }
        }
Exemple #36
0
 /// <summary>
 /// Logs user out of local application (User may still remain logged in at provider)
 /// </summary>
 /// <param name="loginUrl">Where should user be redirected after logout. (Only applicable when using custom authentication)</param>
 /// <param name="callback">Delegate invoked (if specified) just before redirecting user to login page</param>
 /// <param name="provider"> </param>
 public void Logout(string loginUrl = "", Action callback = null, PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     if(providerType != PROVIDER_TYPE.NOT_SPECIFIED && GetConnectedProviders().Count>1)
     {
         SessionManager.RemoveConnectionToken(providerType);
         return;
     }
     Disconnect(loginUrl, callback);
 }
Exemple #37
0
        /// <summary>
        /// Returns contacts from current connection or specified provider
        /// </summary>
        /// <param name="providerType">Provider Type (Connection should exist else exception is thrown)</param>
        /// <returns></returns>
        public List<Contact> GetContacts(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
        {
            if (providerType != PROVIDER_TYPE.NOT_SPECIFIED)
            {

                if (SessionManager.IsConnectedWith(providerType))
                {
                    return GetConnection(providerType).GetContacts();
                }
                else
                {
                    throw new InvalidSocialAuthConnectionException(providerType);
                }
            }
            else
            {
                if (SessionManager.IsConnected)
                {

                    return CurrentConnection.GetContacts();
                }

                else
                {
                    throw new InvalidSocialAuthConnectionException();
                }
            }
        }
Exemple #38
0
        ///// <summary>
        ///// Execute data feed with current or specified provider
        ///// </summary>
        ///// <param name="feedUrl"></param>
        ///// <param name="transportMethod"></param>
        ///// <returns></returns>
        public WebResponse ExecuteFeed(string feedUrl, TRANSPORT_METHOD transportMethod, PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED, byte[] content = null, Dictionary<string, string> headers = null)
        {
            IProvider provider = null;
            //provider is not specified explicitly. Pick connected provider.
            if (providerType == PROVIDER_TYPE.NOT_SPECIFIED)
            {
                if (SessionManager.IsConnected)
                    provider = SessionManager.GetCurrentConnection();
            }
            else //provider explicitly specified
            {
                if (SessionManager.IsConnectedWith(providerType))
                    provider = ProviderFactory.GetProvider(providerType);

            }

            if (provider == null)
                throw new InvalidSocialAuthConnectionException(providerType);

            //Call ExecuteFeed
            WebResponse response;
            if (headers == null && content == null)
                response = provider.ExecuteFeed(feedUrl, transportMethod);
            else
                response = provider.ExecuteFeed(feedUrl, transportMethod, content, headers);
            return response;
        }
 /// <summary>
 /// (Optional) If user wants AccessToken (may be for their own persistance)
 /// </summary>
 /// <param name="providerType"></param>
 /// <returns></returns>
 public Token GetAccessGrant(PROVIDER_TYPE providerType)
 {
     return accessGrant[providerType];
 }
Exemple #40
0
        ///// <summary>
        ///// Execute data feed with current or specified provider
        ///// </summary>
        ///// <param name="feedUrl"></param>
        ///// <param name="transportMethod"></param>
        ///// <returns></returns>
        public WebResponse ExecuteFeed(string feedUrl, TRANSPORT_METHOD transportMethod, PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED, byte[] content = null, Dictionary <string, string> headers = null)
        {
            IProvider provider = null;

            //provider is not specified explicitly. Pick connected provider.
            if (providerType == PROVIDER_TYPE.NOT_SPECIFIED)
            {
                if (SessionManager.IsConnected)
                {
                    provider = SessionManager.GetCurrentConnection();
                }
            }
            else //provider explicitly specified
            {
                if (SessionManager.IsConnectedWith(providerType))
                {
                    provider = ProviderFactory.GetProvider(providerType);
                }
            }

            if (provider == null)
            {
                throw new InvalidSocialAuthConnectionException(providerType);
            }


            //Call ExecuteFeed
            WebResponse response;

            if (headers == null && content == null)
            {
                response = provider.ExecuteFeed(feedUrl, transportMethod);
            }
            else
            {
                response = provider.ExecuteFeed(feedUrl, transportMethod, content, headers);
            }
            return(response);
        }
 /// <summary>
 /// Allow user to remove an existing connection token.
 /// </summary>
 /// <param name="providerType"></param>
 public void RemoveConnection(PROVIDER_TYPE providerType)
 {
     if (IsConnectedWith(providerType))
         accessGrant.Remove(providerType);
 }
Exemple #42
0
 /// <summary>
 /// specifies whether user is connected with specified provider
 /// </summary>
 /// <param name="providerType">Provider Type</param>
 /// <returns></returns>
 public static bool IsConnectedWith(PROVIDER_TYPE providerType)
 {
     return SessionManager.IsConnectedWith(providerType);
 }
 public UserDeniedPermissionException(PROVIDER_TYPE providertype = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     this.providertype = providertype;
 }
 internal static void RemoveConnectionToken(PROVIDER_TYPE providerType)
 {
     userSession.connectedTokens.RemoveAll(x => x.Provider == providerType);
 }
Exemple #45
0
 public UserDeniedPermissionException(PROVIDER_TYPE providertype = PROVIDER_TYPE.NOT_SPECIFIED)
 {
     this.providertype = providertype;
 }
 /// <summary>
 /// Is there an established connection with specified provider
 /// </summary>
 /// <param name="providerType">Provider Type</param>
 /// <returns></returns>
 public bool IsConnectedWith(PROVIDER_TYPE providerType)
 {
     return accessGrant.ContainsKey(providerType);
 }
Exemple #47
0
 //--------- Constructor (Optional and is for backward compatibility)
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="providerType">Provider Type for this connection</param>
 public SocialAuthUser(PROVIDER_TYPE providerType)
 {
     this.providerType = providerType;
 }
Exemple #48
0
        //------------ Data Retrieval Methods
        /// <summary>
        /// Returns Profile from current connection or specified provider
        /// </summary>
        /// <param name="providerType">Provider Type (Connection should exist else exception is thrown)</param>
        /// <returns></returns>
        public UserProfile GetProfile(PROVIDER_TYPE providerType = PROVIDER_TYPE.NOT_SPECIFIED)
        {
            if (providerType != PROVIDER_TYPE.NOT_SPECIFIED)
            {

                if (SessionManager.IsConnectedWith(providerType))
                {
                    if (GetConnection(providerType).GetConnectionToken().Profile.IsSet)
                        return GetConnection(providerType).GetConnectionToken().Profile;
                    else
                        return SessionManager.GetConnection(providerType).GetProfile();
                }
                else
                {
                    throw new InvalidSocialAuthConnectionException(providerType);
                }
            }
            else
            {
                if (SessionManager.IsConnected)
                {
                    if (GetCurrentConnectionToken().Profile.IsSet)
                        return GetCurrentConnectionToken().Profile;
                    else
                        return SessionManager.GetCurrentConnection().GetProfile();
                }

                else
                {
                    throw new InvalidSocialAuthConnectionException();
                }
            }
        }
 internal static bool IsConnectedWith(PROVIDER_TYPE providerType)
 {
     return(userSession.connectedTokens.Exists(x => x.Provider == providerType));
 }
 /// <summary>
 /// Provides URL for redirecting user to specified provider
 /// </summary>
 public string GetLoginRedirectUrl(PROVIDER_TYPE providerType, string returnUrl)
 {
     var provider = ProviderFactory.GetProvider(providerType);
     provider.ConnectionToken = new Token()
     {
         Domain = "http://opensource.brickred.com/socialauthdemo/",
         Profile = new UserProfile(providerType)
     };
     return provider.GetLoginRedirectUrl(returnUrl);
 }
        internal static Token GetConnectionToken(PROVIDER_TYPE providerType)
        {
            var connectionToken = userSession.connectedTokens.Find(x => x.Provider == providerType);

            return(connectionToken);
        }
Exemple #52
0
        public static void Login(string providername)
        {
            PROVIDER_TYPE providerType = (PROVIDER_TYPE)Enum.Parse(typeof(PROVIDER_TYPE), providername);

            SocialAuthUser.GetCurrentUser().Login(providerType);
        }
        internal static void RemoveConnectionToken(PROVIDER_TYPE providerType)
        {
            userSession.connectedTokens.RemoveAll(x => x.Provider == providerType);

        }
 /// <summary>
 /// Returns connection Token of specified provider
 /// </summary>
 /// <param name="providerType">Provider Type</param>
 /// <returns></returns>
 public Token GetConnectionToken(PROVIDER_TYPE providerType)
 {
     return accessGrant[providerType];
 }
        internal static IProvider GetConnection(PROVIDER_TYPE providerType)
        {
            IProvider provider = null;
            //There are no connections
            var lastConnection = userSession.connectedTokens.Find(x => x.Provider == providerType);
            if (lastConnection != null)
            {
                provider = ProviderFactory.GetProvider(lastConnection.Provider);
                return provider;
            }
            else
                return null;

        }
Exemple #56
0
 /// <summary>
 /// Returns connection for specified provider. (throws exception is not connected)
 /// </summary>
 /// <param name="provider">Provider Type</param>
 /// <returns></returns>
 public IProvider GetConnection(PROVIDER_TYPE provider)
 {
     return ProviderFactory.GetProvider(provider);
 }
 public static string UserLoginResponseError(PROVIDER_TYPE providerType, QueryParameters collection)
 {
     return "An error occurred in user login." + Environment.NewLine + "Provider returned: " + ((collection == null) ? "" : collection.ToString());
 }
Exemple #58
0
 /// <summary>
 /// Returns connection for specified provider. (throws exception is not connected)
 /// </summary>
 /// <param name="provider">Provider Type</param>
 /// <returns></returns>
 public IProvider GetConnection(PROVIDER_TYPE provider)
 {
     return(ProviderFactory.GetProvider(provider));
 }
 public static string InvalidConnectionUsed(PROVIDER_TYPE providerType)
 {
     return "There is no active connection with " + providerType.ToString();
 }
        /// <summary>
        /// Connects to a provider (Same as Login())
        /// </summary>
        /// <param name="providerType">Provider to which connection has to be established</param>
        /// <param name="returnURL">Optional URL where user will be redirected after login (for this provider only)</param>
        internal static void Connect(PROVIDER_TYPE providerType, string returnURL = "", string errorURL = "")
        {
            returnURL = returnURL ?? "";
            if (!returnURL.ToLower().StartsWith("http") && returnURL.Length > 0)
                returnURL = HttpContext.Current.Request.GetBaseURL() + returnURL;

            try
            {

                //User is already connected. return or redirect
                if (IsConnectedWith(providerType))
                {
                    if (!string.IsNullOrEmpty(returnURL))
                        SocialAuthUser.Redirect(returnURL);
                    else
                    {
                        if (Utility.GetAuthenticationMode() == System.Web.Configuration.AuthenticationMode.Forms)
                        {
                            returnURL = FormsAuthentication.DefaultUrl;
                            SocialAuthUser.Redirect(returnURL);
                        }

                    }
                    return;
                }

                AUTHENTICATION_OPTION option = Utility.GetAuthenticationOption();

                //Set where user should be redirected after successful login
                if (Utility.GetAuthenticationOption() == AUTHENTICATION_OPTION.CUSTOM_SECURITY_CUSTOM_SCREEN
                     && string.IsNullOrEmpty(returnURL))
                    throw new Exception("Please specify return URL");
                else if (option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_CUSTOM_SCREEN || option == AUTHENTICATION_OPTION.SOCIALAUTH_SECURITY_SOCIALAUTH_SCREEN)
                {   //User has not specified and explicit return url. redirect to url from configuration
                    if (string.IsNullOrEmpty(returnURL))
                        returnURL = HttpContext.Current.Request.GetBaseURL() + Utility.GetSocialAuthConfiguration().Authentication.DefaultUrl;
                }

                //ReturnURL in request takes all priority
                if (HttpContext.Current.Request["ReturnUrl"] != null)
                {
                    string ret = HttpContext.Current.Request["ReturnUrl"];
                    if (Utility.GetAuthenticationOption() == AUTHENTICATION_OPTION.FORMS_AUTHENTICATION)
                    {
                        if (ret.ToLower().StartsWith(HttpContext.Current.Request.ApplicationPath.ToLower() + "/"))
                        {
                            ret = ret.Substring(ret.IndexOf("/", 1));
                            if (ret.StartsWith("/"))
                                ret = ret.Substring(1);
                        }
                    }
                    if (ret.ToLower().Contains("wa=wsignin"))
                        returnURL = HttpContext.Current.Request.GetBaseURL() + ret;
                    else if (!ret.ToLower().StartsWith("http"))
                        returnURL = HttpContext.Current.Request.GetBaseURL() + ret;
                    else
                        returnURL = ret;
                }

                SessionManager.InProgressToken = (new Token()
                {
                    Provider = providerType,
                    Domain = HttpContext.Current.Request.GetBaseURL(),
                    UserReturnURL = returnURL,
                    SessionGUID = SessionManager.GetUserSessionGUID(),
                    Profile = new UserProfile() { Provider = providerType }

                });
                SessionManager.InProgressToken.Profile.Provider = providerType;
                if (!string.IsNullOrEmpty(errorURL))
                    SessionManager.ErrorURL = HttpContext.Current.Request.GetBaseURL() + errorURL;

                ((IProviderConnect)ProviderFactory.GetProvider(providerType)).Connect();
            }
            catch
            {
                throw;
            }
        }