Inheritance: OAuth.Base, IWebConnection
示例#1
0
        private void GetConfigSettings(out Api.OAuth oauthConfig, out string serverPref)
        {
            serverPref = (string)
                         Preferences.Get(serverUrlPrefPath);

            oauthConfig = new Api.OAuth();
            oauthConfig.AccessTokenBaseUrl =
                Preferences.Get(accessTokenBaseUrlPrefPath) as string;
            oauthConfig.AuthorizeLocation =
                Preferences.Get(authorizeLocationPrefPath) as string;
            oauthConfig.ConsumerKey =
                Preferences.Get(consumerKeyPrefPath) as string;
            oauthConfig.ConsumerSecret =
                Preferences.Get(consumerSecretPrefPath) as string;
            oauthConfig.Realm =
                Preferences.Get(realmPrefPath) as string;
            oauthConfig.RequestTokenBaseUrl =
                Preferences.Get(requestTokenBaseUrlPrefPath) as string;
            oauthConfig.Token =
                Preferences.Get(tokenPrefPath) as string;
            oauthConfig.TokenSecret =
                Preferences.Get(tokenSecretPrefPath) as string;

            // The fact that the configuration was saved at all
            // implies that the token is an access token.
            // TODO: Any benefit in actually storing this bool, in
            //       case of weird circumstances?
            oauthConfig.IsAccessToken =
                !String.IsNullOrEmpty(oauthConfig.Token);
        }
		public WebSyncPreferencesWidget (Api.OAuth oauth, string server, EventHandler requiredPrefChanged) : base (false, 5)
		{
			this.oauth = oauth;
			
			Gtk.Table prefsTable = new Gtk.Table (1, 2, false);
			prefsTable.RowSpacing = 5;
			prefsTable.ColumnSpacing = 10;

			serverEntry = new Gtk.Entry ();
			serverEntry.Text = server;
			AddRow (prefsTable, serverEntry, Catalog.GetString ("Se_rver:"), 0);
			
			Add (prefsTable);

			authButton = new Gtk.Button ();
			// TODO: If Auth is valid, this text should change
			if (!Auth.IsAccessToken)
				authButton.Label = Catalog.GetString ("Connect to Server");
			else {
				authButton.Label = Catalog.GetString ("Connected");
				authButton.Sensitive = false;
			}
			authButton.Clicked += OnAuthButtonClicked;

			serverEntry.Changed += delegate {
				Auth = null;
			};
			serverEntry.Changed += requiredPrefChanged;

			Add (authButton);

			// TODO: Add a section that shows the user something to verify they put
			//       in the right URL...something that constructs their user URL, maybe?
			ShowAll ();
		}
        public WebSyncPreferencesWidget(Api.OAuth oauth, string server, EventHandler requiredPrefChanged) : base(false, 5)
        {
            this.oauth = oauth;

            Gtk.Table prefsTable = new Gtk.Table(1, 2, false);
            prefsTable.RowSpacing    = 5;
            prefsTable.ColumnSpacing = 10;

            serverEntry      = new Gtk.Entry();
            serverEntry.Text = server;
            AddRow(prefsTable, serverEntry, Catalog.GetString("Se_rver:"), 0);

            Add(prefsTable);

            authButton = new Gtk.Button();
            // TODO: If Auth is valid, this text should change
            if (!Auth.IsAccessToken)
            {
                authButton.Label = Catalog.GetString("Connect to Server");
            }
            else
            {
                authButton.Label     = Catalog.GetString("Connected");
                authButton.Sensitive = false;
            }
            authButton.Clicked += OnAuthButtonClicked;

            serverEntry.Changed += delegate {
                Auth = null;
            };
            serverEntry.Changed += requiredPrefChanged;

            Add(authButton);

            // TODO: Add a section that shows the user something to verify they put
            //       in the right URL...something that constructs their user URL, maybe?
            ShowAll();
        }
示例#4
0
 private void SaveConfigSettings(Api.OAuth oauthConfig, string serverPref)
 {
     Preferences.Set(serverUrlPrefPath, GetConfigString(serverPref));
     Preferences.Set(accessTokenBaseUrlPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.AccessTokenBaseUrl) :
                     String.Empty);
     Preferences.Set(authorizeLocationPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.AuthorizeLocation) :
                     String.Empty);
     Preferences.Set(consumerKeyPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.ConsumerKey) :
                     String.Empty);
     Preferences.Set(consumerSecretPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.ConsumerSecret) :
                     String.Empty);
     Preferences.Set(realmPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.Realm) :
                     String.Empty);
     Preferences.Set(requestTokenBaseUrlPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.RequestTokenBaseUrl) :
                     String.Empty);
     Preferences.Set(tokenPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.Token) :
                     String.Empty);
     Preferences.Set(tokenSecretPrefPath,
                     oauthConfig != null ?
                     GetConfigString(oauthConfig.TokenSecret) :
                     String.Empty);
 }
		private void OnAuthButtonClicked (object sender, EventArgs args)
		{
			if (listener != null && listener.IsListening) {
				listener.Stop ();
				listener.Close ();
			}

			// TODO: Move this
			if (Auth == null)
				Auth = new Api.OAuth ();

			string rootUri = Server.TrimEnd('/') + "/api/1.0";
			try {
				RootInfo root = RootInfo.GetRoot (rootUri, new Api.AnonymousConnection ());

				Auth.AuthorizeLocation = root.AuthorizeUrl;
				Auth.AccessTokenBaseUrl = root.AccessTokenUrl;
				Auth.RequestTokenBaseUrl = root.RequestTokenUrl;
				Auth.ConsumerKey = "anyone";
				Auth.ConsumerSecret = "anyone";
				Auth.Realm = "Snowy";
			} catch (Exception e) {
				Logger.Error ("Failed to get Root resource " + rootUri + ". Exception was: " + e.ToString());
				authButton.Label = Catalog.GetString ("Server not responding. Try again later.");
				oauth = null;
				return;
			}

			if (!Auth.IsAccessToken) {
				listener = new HL.HttpListener ();
				int portToTry = 8000;
				string callbackUrl = string.Empty;
				while (!listener.IsListening && portToTry < 9000) {
					callbackUrl = String.Format ("http://localhost:{0}/tomboy-web-sync/",
					                            portToTry);
					try {
						listener.Prefixes.Add (callbackUrl);
					} catch (Exception e) {
						Logger.Error ("Exception while trying to add {0} as an HttpListener Prefix",
							callbackUrl);
						Logger.Error (e.ToString ());
						break;
					}
					try {
						listener.Start ();
						Auth.CallbackUrl = callbackUrl;
					} catch {
						listener.Prefixes.Clear ();
						portToTry++;
					}
				}

				if (!listener.IsListening) {
					Logger.Error ("Unable to start HttpListener on any port between 8000-8999");
					authButton.Label = Catalog.GetString ("Server not responding. Try again later.");
					oauth = null;
					return;
				}

				Logger.Debug ("Listening on {0} for OAuth callback", callbackUrl);
				string authUrl = string.Empty;
				try {
					authUrl = Auth.GetAuthorizationUrl ();
				} catch (Exception e) {
					listener.Stop ();
					listener.Close ();
					Logger.Error ("Failed to get auth URL from " + Server + ". Exception was: " + e.ToString ());
					// Translators: The web service supporting Tomboy WebSync is not responding as expected
					authButton.Label = Catalog.GetString ("Server not responding. Try again later.");
					oauth = null;
					return;
				}

				IAsyncResult result = listener.BeginGetContext (delegate (IAsyncResult localResult) {
					HL.HttpListenerContext context;
					try {
						context = listener.EndGetContext (localResult);
					} catch (Exception e) {
						// TODO: Figure out why this error occurs
						Logger.Error ("Error processing OAuth callback. Could be a sign that you pressed the button to reset the connection. Exception details:");
						Logger.Error (e.ToString ());
						return;
					}
					// Assuming if we got here user clicked Allow
					Logger.Debug ("Context request uri query section: " + context.Request.Url.Query);
					// oauth_verifier is required in OAuth 1.0a, not 1.0
					var qs = HttpUtility.ParseQueryString (context.Request.Url.Query);
					if (!String.IsNullOrEmpty (qs ["oauth_verifier"]))
						Auth.Verifier = qs ["oauth_verifier"];
					try {
						if (!Auth.GetAccessAfterAuthorization ())
							throw new ApplicationException ("Unknown error getting access token");
						Logger.Debug ("Successfully authorized web sync");
					} catch (Exception e) {
						listener.Stop ();
						listener.Close ();
						Logger.Error ("Failed to authorize web sync, with exception:");
						Logger.Error (e.ToString ());
						Gtk.Application.Invoke (delegate {
							authButton.Label = Catalog.GetString ("Authorization Failed, Try Again");
							authButton.Sensitive = true;
						});
						oauth = null;
						return;
					}
					string htmlResponse =
						String.Format (callbackHtmlTemplate,
						               // Translators: Title of web page presented to user after they authorized Tomboy for sync
						               Catalog.GetString ("Tomboy Web Authorization Successful"),
						               // Translators: Body of web page presented to user after they authorized Tomboy for sync
						               Catalog.GetString ("Please return to the Tomboy Preferences window and press Save to start synchronizing."));
					using (var writer = new System.IO.StreamWriter (context.Response.OutputStream))
						writer.Write (htmlResponse);
					listener.Stop ();
					listener.Close ();

					if (Auth.IsAccessToken) {
						Gtk.Application.Invoke (delegate {
							authButton.Sensitive = false;
							authButton.Label = Catalog.GetString ("Connected. Press Save to start synchronizing");
						});
					}
				}, null);

				Logger.Debug ("Launching browser to authorize web sync: " + authUrl);
				authButton.Label = Catalog.GetString ("Authorizing in browser (Press to reset connection)");
				try {
					Services.NativeApplication.OpenUrl (authUrl, Screen);
				} catch (Exception e) {
					listener.Stop ();
					listener.Close ();
					Logger.Error ("Exception opening URL: " + e.Message);
					// Translators: Sometimes a user's default browser is not set, so we recommend setting it and trying again
					authButton.Label = Catalog.GetString ("Set the default browser and try again");
					return;
				}
				// Translators: The user must take action in their web browser to continue the authorization process
				authButton.Label = Catalog.GetString ("Authorizing in browser (Press to reset connection)");
			}
		}
        private void OnAuthButtonClicked(object sender, EventArgs args)
        {
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
                listener.Close();
            }

            // TODO: Move this
            if (Auth == null)
            {
                Auth = new Api.OAuth();
            }

            string rootUri = Server + "/api/1.0";

            try {
                RootInfo root = RootInfo.GetRoot(rootUri, new Api.AnonymousConnection());

                Auth.AuthorizeLocation   = root.AuthorizeUrl;
                Auth.AccessTokenBaseUrl  = root.AccessTokenUrl;
                Auth.RequestTokenBaseUrl = root.RequestTokenUrl;
                Auth.ConsumerKey         = "anyone";
                Auth.ConsumerSecret      = "anyone";
                Auth.Realm = "Snowy";
            } catch (Exception e) {
                Logger.Error("Failed to get Root resource " + rootUri + ". Exception was: " + e.ToString());
                authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                oauth            = null;
                return;
            }

            if (!Auth.IsAccessToken)
            {
                listener = new HL.HttpListener();
                int    portToTry   = 8000;
                string callbackUrl = string.Empty;
                while (!listener.IsListening && portToTry < 9000)
                {
                    callbackUrl = String.Format("http://localhost:{0}/tomboy-web-sync/",
                                                portToTry);
                    try {
                        listener.Prefixes.Add(callbackUrl);
                    } catch (Exception e) {
                        Logger.Error("Exception while trying to add {0} as an HttpListener Prefix",
                                     callbackUrl);
                        Logger.Error(e.ToString());
                        break;
                    }
                    try {
                        listener.Start();
                        Auth.CallbackUrl = callbackUrl;
                    } catch {
                        listener.Prefixes.Clear();
                        portToTry++;
                    }
                }

                if (!listener.IsListening)
                {
                    Logger.Error("Unable to start HttpListener on any port between 8000-8999");
                    authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                    oauth            = null;
                    return;
                }

                Logger.Debug("Listening on {0} for OAuth callback", callbackUrl);
                string authUrl = string.Empty;
                try {
                    authUrl = Auth.GetAuthorizationUrl();
                } catch (Exception e) {
                    listener.Stop();
                    listener.Close();
                    Logger.Error("Failed to get auth URL from " + Server + ". Exception was: " + e.ToString());
                    // Translators: The web service supporting Tomboy WebSync is not responding as expected
                    authButton.Label = Catalog.GetString("Server not responding. Try again later.");
                    oauth            = null;
                    return;
                }

                IAsyncResult result = listener.BeginGetContext(delegate(IAsyncResult localResult) {
                    HL.HttpListenerContext context;
                    try {
                        context = listener.EndGetContext(localResult);
                    } catch (Exception e) {
                        // TODO: Figure out why this error occurs
                        Logger.Error("Error processing OAuth callback. Could be a sign that you pressed the button to reset the connection. Exception details:");
                        Logger.Error(e.ToString());
                        return;
                    }
                    // Assuming if we got here user clicked Allow
                    Logger.Debug("Context request uri query section: " + context.Request.Url.Query);
                    // oauth_verifier is required in OAuth 1.0a, not 1.0
                    var qs = HttpUtility.ParseQueryString(context.Request.Url.Query);
                    if (!String.IsNullOrEmpty(qs ["oauth_verifier"]))
                    {
                        Auth.Verifier = qs ["oauth_verifier"];
                    }
                    try {
                        if (!Auth.GetAccessAfterAuthorization())
                        {
                            throw new ApplicationException("Unknown error getting access token");
                        }
                        Logger.Debug("Successfully authorized web sync");
                    } catch (Exception e) {
                        listener.Stop();
                        listener.Close();
                        Logger.Error("Failed to authorize web sync, with exception:");
                        Logger.Error(e.ToString());
                        Gtk.Application.Invoke(delegate {
                            authButton.Label     = Catalog.GetString("Authorization Failed, Try Again");
                            authButton.Sensitive = true;
                        });
                        oauth = null;
                        return;
                    }
                    string htmlResponse =
                        String.Format(callbackHtmlTemplate,
                                      // Translators: Title of web page presented to user after they authorized Tomboy for sync
                                      Catalog.GetString("Tomboy Web Authorization Successful"),
                                      // Translators: Body of web page presented to user after they authorized Tomboy for sync
                                      Catalog.GetString("Please return to the Tomboy Preferences window and press Save to start synchronizing."));
                    using (var writer = new System.IO.StreamWriter(context.Response.OutputStream))
                        writer.Write(htmlResponse);
                    listener.Stop();
                    listener.Close();

                    if (Auth.IsAccessToken)
                    {
                        Gtk.Application.Invoke(delegate {
                            authButton.Sensitive = false;
                            authButton.Label     = Catalog.GetString("Connected. Press Save to start synchronizing");
                        });
                    }
                }, null);

                Logger.Debug("Launching browser to authorize web sync: " + authUrl);
                authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)");
                try {
                    Services.NativeApplication.OpenUrl(authUrl, Screen);
                } catch (Exception e) {
                    listener.Stop();
                    listener.Close();
                    Logger.Error("Exception opening URL: " + e.Message);
                    // Translators: Sometimes a user's default browser is not set, so we recommend setting it and trying again
                    authButton.Label = Catalog.GetString("Set the default browser and try again");
                    return;
                }
                // Translators: The user must take action in their web browser to continue the authorization process
                authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)");
            }
        }
		private bool GetConfigSettings (out Api.OAuth oauthConfig, out string serverPref)
		{
			serverPref = (string)
				Preferences.Get (serverUrlPrefPath);

			oauthConfig = new Api.OAuth ();
			oauthConfig.AccessTokenBaseUrl =
				Preferences.Get (accessTokenBaseUrlPrefPath) as string;
			oauthConfig.AuthorizeLocation =
				Preferences.Get (authorizeLocationPrefPath) as string;
			oauthConfig.ConsumerKey =
				Preferences.Get (consumerKeyPrefPath) as string;
			oauthConfig.ConsumerSecret =
				Preferences.Get (consumerSecretPrefPath) as string;
			oauthConfig.Realm =
				Preferences.Get (realmPrefPath) as string;
			oauthConfig.RequestTokenBaseUrl =
				Preferences.Get (requestTokenBaseUrlPrefPath) as string;
			oauthConfig.Token =
				Preferences.Get (tokenPrefPath) as string;
			oauthConfig.TokenSecret =
				Preferences.Get (tokenSecretPrefPath) as string;

			// The fact that the configuration was saved at all
			// implies that the token is an access token.
			// TODO: Any benefit in actually storing this bool, in
			//       case of weird circumstances?
			oauthConfig.IsAccessToken =
				!String.IsNullOrEmpty (oauthConfig.Token);
			
			return !string.IsNullOrEmpty (serverPref)
				&& oauthConfig.IsAccessToken;
		}