Example #1
0
	def __init__(self):
		"""
		Read and set up config, set up authentication
		"""
		atexit.register(self.cleanup)

		self.config = ConfigParser.RawConfigParser()
		self.config.read([self.OAUTH_CONFIG_FILENAME])
		self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')
		
		if not self.config.has_section('Credentials'):
			self.config.add_section('Credentials')

		self.client_token = self.config.get_quiet('Credentials', 'client_token')
		self.client_id = self.config.get_quiet('Credentials', 'client_id')
		self.client_secret = self.config.get_quiet('Credentials', 'client_secret')

		self.auth = GitHubAuth(app_name="python-gist", app_url="http://github.com/amitsaha/python-gist", \
					       client_id=self.client_id, client_secret=self.client_secret)

		if (self.client_token is None or self.client_id is None) and sys.stdin.isatty():
			self.choose_authmethod()

		elif not sys.stdin.isatty() and self.client_id is None:
			# In case a pipe is trying to write to us
			print "Sorry, can't accept anything on stdin until I have some GitHub credentials to work with"
			sys.exit(1)

		else:
			print "Loaded saved access token, I'm good to go." 
Example #2
0
    def __init__(self):
        """
        Read and set up config, set up authentication
        """
        atexit.register(self.save_configuration)
        self.client_secret = None #allow cleanup to run even if we don't finish __init__

        self.config = ConfigParser.RawConfigParser()
        self.config.read([self.OAUTH_CONFIG_FILENAME])
        self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')

        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')

        self.client_token = self.config.get_quiet('Credentials', 'client_token')
        self.auth = GitHubAuth(app_name="python-gist", app_url="http://github.com/voltagex/python-gist")

        #todo, this logic sucks.
        if (self.client_token is None) and sys.stdin.isatty():
            self.authorise_password()
        elif not sys.stdin.isatty() and self.client_token is None:
            # In case a pipe is trying to write to us
            print "Sorry, can't accept anything on stdin until I have some GitHub credentials to work with"
            sys.exit(1)
        else:
            print "Loaded saved access token, I'm good to go."
Example #3
0
    def __init__(self):
        """
        Read and set up config, set up authentication
        """
        atexit.register(self.save_configuration)
        self.client_secret = None  #allow cleanup to run even if we don't finish __init__

        self.config = ConfigParser.RawConfigParser()
        self.config.read([self.OAUTH_CONFIG_FILENAME])
        self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')

        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')

        self.client_token = self.config.get_quiet('Credentials',
                                                  'client_token')
        self.auth = GitHubAuth(
            app_name="python-gist",
            app_url="http://github.com/voltagex/python-gist")
Example #4
0
    def __init__(self):
        """
        Read and set up config, set up authentication
        """
        atexit.register(self.save_configuration)
        self.client_secret = None #allow cleanup to run even if we don't finish __init__

        self.config = ConfigParser.RawConfigParser()
        self.config.read([self.OAUTH_CONFIG_FILENAME])
        self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')

        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')

        self.client_token = self.config.get_quiet('Credentials', 'client_token')
        self.auth = GitHubAuth(app_name="python-gist", app_url="http://github.com/voltagex/python-gist")
Example #5
0
class Gist(object):
    """
    Methods for working with GitHub Gists
    """
    OAUTH_CONFIG_FILENAME = configpaths.get_config_path(
        'python-gist', 'oauth.cfg')

    def __init__(self):
        """
        Read and set up config, set up authentication
        """
        atexit.register(self.save_configuration)
        self.client_secret = None  #allow cleanup to run even if we don't finish __init__

        self.config = ConfigParser.RawConfigParser()
        self.config.read([self.OAUTH_CONFIG_FILENAME])
        self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')

        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')

        self.client_token = self.config.get_quiet('Credentials',
                                                  'client_token')
        self.auth = GitHubAuth(
            app_name="python-gist",
            app_url="http://github.com/voltagex/python-gist")

        #todo, this logic sucks.
    def authorise(self, use_personal_access_token):
        if (self.client_token is None) and sys.stdin.isatty():
            self.authorise_password(use_personal_access_token)
        elif not sys.stdin.isatty() and self.client_token is None:
            # In case a pipe is trying to write to us
            print "Sorry, can't accept anything on stdin until I have some GitHub credentials to work with"
            sys.exit(1)
        else:
            print "Loaded saved access token, I'm good to go."

    def authorise_password(self, use_personal_access_token=False):
        """
        Authorise this script via GitHub username and password
        """
        try:
            username = raw_input("Please enter your username: "******"Please enter your password: "******"Please enter your personal access token: ")
                if not self.auth.check_personal_access_token(token):
                    raise (Exception("Incorrect token"))

            self.client_token = token
            print "Saved your token, start this script again to post gists"
            sys.exit(0)
        except Exception as ex:
            print ex.message
        sys.exit(1)

    def twofactor(self, code_type):
        return raw_input('Enter your 2FA code: ')

    def patch_gist(self, description, public, gist_files, gist_id, content):
        """
        Patch a gist, either single text string or a dictionary of files in the form of
        {"filename.ext": {"content": "some text"}}

        :param description: Gist description
        :type: str.

        :param public: Post a public or private Gist
        :type: bool.

        :param gist_files: dictionary of files for Gist
        :type: dict.

        :param content: string content for Gist
        :type: str.
        """
        if gist_files is not None:
            files = gist_files
        elif content is not None:
            files = {"gist.txt": {"content": str(content)}}
        else:
            raise ("Either content or gist_files must be set")
        payload = {
            "description": description,
            "public": public,
            "files": files,
        }

        authorised_client = self.auth.get_session(self.client_token)
        response = authorised_client.patch("https://api.github.com/gists/" +
                                           gist_id,
                                           data=json.dumps(payload))

        if response.ok:
            return response.json()['html_url']
        else:
            print "Error " + response.text
            return

    def post_gist(self, description, public, gist_files, content):
        """
        Post a gist, either single text string or a dictionary of files in the form of
        {"filename.ext": {"content": "some text"}}

        :param description: Gist description
        :type: str.

        :param public: Post a public or private Gist
        :type: bool.

        :param gist_files: dictionary of files for Gist
        :type: dict.

        :param content: string content for Gist
        :type: str.
        """
        if gist_files is not None:
            files = gist_files
        elif content is not None:
            files = {"gist.txt": {"content": str(content)}}
        else:
            raise ("Either content or gist_files must be set")
        payload = {
            "description": description,
            "public": public,
            "files": files,
        }

        authorised_client = self.auth.get_session(self.client_token)
        response = authorised_client.post("https://api.github.com/gists",
                                          data=json.dumps(payload))

        if response.ok:
            return response.json()['html_url']
        else:
            print "Error " + response.text
            return

    def save_configuration(self):
        """
        Cleanup, set config and flush before exiting
        """
        #recheck the config file in case it's changed during runtime
        current_token = self.config.get_quiet('Credentials', 'client_token')

        if (self.client_token != current_token
                and self.client_token is not None):
            self.config.set('Credentials', 'client_token', self.client_token)

            self.config.write(self.config.filehandle)
            self.config.filehandle.flush()
            self.config.filehandle.close()
Example #6
0
class Gist(object):
    """
    Methods for working with GitHub Gists
    """
    OAUTH_CONFIG_FILENAME = configpaths.get_config_path('python-gist', 'oauth.cfg')

    def __init__(self):
        """
        Read and set up config, set up authentication
        """
        atexit.register(self.save_configuration)
        self.client_secret = None #allow cleanup to run even if we don't finish __init__

        self.config = ConfigParser.RawConfigParser()
        self.config.read([self.OAUTH_CONFIG_FILENAME])
        self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')

        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')

        self.client_token = self.config.get_quiet('Credentials', 'client_token')
        self.auth = GitHubAuth(app_name="python-gist", app_url="http://github.com/voltagex/python-gist")

        #todo, this logic sucks.
    def authorise(self,use_personal_access_token):
        if (self.client_token is None) and sys.stdin.isatty():
                self.authorise_password(use_personal_access_token)
        elif not sys.stdin.isatty() and self.client_token is None:
                # In case a pipe is trying to write to us
                print "Sorry, can't accept anything on stdin until I have some GitHub credentials to work with"
                sys.exit(1)
        else:
                print "Loaded saved access token, I'm good to go."

    def authorise_password(self, use_personal_access_token = False):
        """
        Authorise this script via GitHub username and password
        """
        try:
            username = raw_input("Please enter your username: "******"Please enter your password: "******"Please enter your personal access token: ")
                if not self.auth.check_personal_access_token(token):
                    raise(Exception("Incorrect token"))

            self.client_token = token
            print "Saved your token, start this script again to post gists"
            sys.exit(0)
        except Exception as ex:
            print ex.message
        sys.exit(1)

    def twofactor(self,code_type):
        return raw_input('Enter your 2FA code: ')

    def patch_gist(self, description, public, gist_files, gist_id, content):
        """
        Patch a gist, either single text string or a dictionary of files in the form of
        {"filename.ext": {"content": "some text"}}

        :param description: Gist description
        :type: str.

        :param public: Post a public or private Gist
        :type: bool.

        :param gist_files: dictionary of files for Gist
        :type: dict.

        :param content: string content for Gist
        :type: str.
        """
        if gist_files is not None:
            files = gist_files
        elif content is not None:
            files = {"gist.txt": {"content": str(content)}}
        else:
            raise ("Either content or gist_files must be set")
        payload = {
            "description": description,
            "public": public,
            "files": files,
        }

        authorised_client = self.auth.get_session(self.client_token)
        response = authorised_client.patch("https://api.github.com/gists/"+gist_id, data=json.dumps(payload))

        if response.ok:
            return response.json()['html_url']
        else:
            print "Error " + response.text
            return

    def post_gist(self, description, public, gist_files, content):
        """
        Post a gist, either single text string or a dictionary of files in the form of
        {"filename.ext": {"content": "some text"}}

        :param description: Gist description
        :type: str.

        :param public: Post a public or private Gist
        :type: bool.

        :param gist_files: dictionary of files for Gist
        :type: dict.

        :param content: string content for Gist
        :type: str.
        """
        if gist_files is not None:
            files = gist_files
        elif content is not None:
            files = {"gist.txt": {"content": str(content)}}
        else:
            raise ("Either content or gist_files must be set")
        payload = {
            "description": description,
            "public": public,
            "files": files,
        }

        authorised_client = self.auth.get_session(self.client_token)
        response = authorised_client.post("https://api.github.com/gists", data=json.dumps(payload))

        if response.ok:
            return response.json()['html_url']
        else:
            print "Error " + response.text
            return

    def save_configuration(self):
        """
        Cleanup, set config and flush before exiting
        """
        #recheck the config file in case it's changed during runtime
        current_token = self.config.get_quiet('Credentials','client_token')

        if (self.client_token != current_token and self.client_token is not None):
            self.config.set('Credentials', 'client_token', self.client_token)

            self.config.write(self.config.filehandle)
            self.config.filehandle.flush()
            self.config.filehandle.close()
Example #7
0
class Gist(object):
	"""
	Methods for working with GitHub Gists
	"""
	OAUTH_CONFIG_FILENAME = configpaths.get_config_path('python-gist','oauth.cfg')
	
	def choose_authmethod(self):
		choice = None
		try:
			choice = raw_input('Please select an authorisation method.\r\n \t 1. Open a web browser, cut and paste the access token.\r\n \t2. Use your GitHub username and password to get a token automagically.\r\n \t(Default is 2): ')
		except EOFError:
			pass

		choice = choice.strip()

		if choice == '2' or not choice:
			self.authorise_password() 
			return
		if choice == '1':
			self.authorise_web()
			return
		else: self.choose_authmethod()

	def __init__(self):
		"""
		Read and set up config, set up authentication
		"""
		atexit.register(self.cleanup)

		self.config = ConfigParser.RawConfigParser()
		self.config.read([self.OAUTH_CONFIG_FILENAME])
		self.config.filehandle = open(self.OAUTH_CONFIG_FILENAME, 'a')
		
		if not self.config.has_section('Credentials'):
			self.config.add_section('Credentials')

		self.client_token = self.config.get_quiet('Credentials', 'client_token')
		self.client_id = self.config.get_quiet('Credentials', 'client_id')
		self.client_secret = self.config.get_quiet('Credentials', 'client_secret')

		self.auth = GitHubAuth(app_name="python-gist", app_url="http://github.com/amitsaha/python-gist", \
					       client_id=self.client_id, client_secret=self.client_secret)

		if (self.client_token is None or self.client_id is None) and sys.stdin.isatty():
			self.choose_authmethod()

		elif not sys.stdin.isatty() and self.client_id is None:
			# In case a pipe is trying to write to us
			print "Sorry, can't accept anything on stdin until I have some GitHub credentials to work with"
			sys.exit(1)

		else:
			print "Loaded saved access token, I'm good to go." 
	
	def authorise_web(self):
		"""
		Authorise this script via web browser
		"""
		return self.auth.authorise_web(redir=self.redir_url, scopes="gist")

	def authorise_password(self):
		"""
		Authorise this script via GitHub username and password
		"""
		username = raw_input("Please enter your username: "******"Please enter your password: "******"Saved your token, start this script again to post gists"
			sys.exit(0)
		except Exception as ex:
			print ex.message
			print
			self.choose_authmethod()

	def post_gist(self, description, public, gist_files, content):
		"""
		Post a gist, either single text string or a dictionary of files in the form of
		{"filename.ext": {"content": "some text"}}

		:param description: Gist description
		:type: str.
		
		:param public: Post a public or private Gist 
		:type: bool.
		
		:param gist_files: dictionary of files for Gist
		:type: dict.
		
		:param content: string content for Gist
		:type: str.
		"""
		if content is not None:
			files = {"gist.txt": {"content": content}}
		elif gist_files is not None: 
			files = gist_files 
		else:
			raise("Either content or gist_files must be set")
		payload = {
			"description": description,
			"public": public,
			"files": files,
			}
		response = self.auth.get_session(self.client_token). \
		    post("https://api.github.com/gists", data=json.dumps(payload))
		if response.ok:
			return response.json['html_url']
		else: 
			print "Error " + response.text
			return

	def cleanup(self):
		"""
		Cleanup, set config and flush before exisiting
		"""
		#don't write the config file if we don't have enough data or we don't need to
		#todo, handle updates
		if (self.client_token and not self.config.get_quiet('Credentials', 'client_token')): 
			self.config.set('Credentials', 'Client_Token', self.client_token)	
			if (self.client_id):
				self.config.set('Credentials', 'Client_ID', self.client_id)
			if (self.client_secret):
				self.config.set('Credentials', 'Client_Secret', self.client_secret)
		
			self.config.write(self.config.filehandle)			
			self.config.filehandle.flush()
			self.config.filehandle.close()