Example #1
0
 def set_credentials(self, username, password):
     """Store username and password"""
     if not self._config.has_section(SECTION):
         self._config.add_section(SECTION)
     self._config.set(SECTION, 'username', username)
     self._config.write(open(USER_CONFIG_FILE, 'w'))
     keyring.set_password(KEYRING_SERVICE, username, password)
Example #2
0
 def _login(self, username=None, store_password=False):
     if username is None:
         if self.USERNAME == "":
             raise LoginError("If you do not pass a username to login(), you should configure a default one!")
         else:
             username = self.USERNAME
     # Get password from keyring or prompt
     password_from_keyring = keyring.get_password("astroquery:www.eso.org", username)
     if password_from_keyring is None:
         if system_tools.in_ipynb():
             log.warn("You may be using an ipython notebook:"
                      " the password form will appear in your terminal.")
         password = getpass.getpass("{0}, enter your ESO password:\n".format(username))
     else:
         password = password_from_keyring
     # Authenticate
     log.info("Authenticating {0} on www.eso.org...".format(username))
     # Do not cache pieces of the login process
     login_response = self._request("GET", "https://www.eso.org/sso/login", cache=False)
     login_result_response = self._activate_form(login_response,
                                                 form_index=-1,
                                                 inputs={'username': username,
                                                         'password': password})
     root = BeautifulSoup(login_result_response.content, 'html5lib')
     authenticated = not root.select('.error')
     if authenticated:
         log.info("Authentication successful!")
     else:
         log.exception("Authentication failed!")
     # When authenticated, save password in keyring if needed
     if authenticated and password_from_keyring is None and store_password:
         keyring.set_password("astroquery:www.eso.org", username, password)
     return authenticated
 def get_username_and_pw (self):
     print 'Let us get a password...'
     username = self.prefs.get('cooksillustrated-username','')
     print 'Username='******'http://www.cooksillustrated.com',
             username
             )
     else:
         pw = ''
     print 'Initial password: '******'Launch dialog...'
     #
     username, pw = de.getUsernameAndPassword(
         username=username,
         pw=pw
         )
     # broken :( - temporary workaround?
     #username,pw = 'USERNAME','PASSWORD'
     print 'Done with dialog'
     self.prefs['cooksillustrated-username'] = username
     keyring.set_password(
         'http://www.cooksillustrated.com',username,pw
         )
     return username, pw
Example #4
0
def db_login(force_password=False):
	"""Makes sure that config.PASSWORD is set to the database password. 
	If config.PASSWORD is alread defined, this function will not do anything. Otherwise
	it will try to fetch the password from the systems keychain. If no password is stored
	in the keychain yet, the user is prompted to enter the password and optinally store it
	in the system keychain.

	Args:
		force_password: If set to True, the user is prompted even if the password 
		is stored in the keychain (useful if the password needs to be changed
	"""

	if "PASSWORD" in dir(config) != None: #password already set in config.py
		return
	
	import keyring, getpass
	config.PASSWORD = keyring.get_password(config.DATABASE, config.USER)
	if config.PASSWORD == None or force_password == True:
		while 1:
			print("A password is needed to continue. Please enter the password for")
			print(" * service: postgresql")
			print(" * database: " + config.DATABASE)
			print(" * user: "******"to continue.")
			config.PASSWORD = getpass.getpass("Please enter the password:\n")
			if config.PASSWORD != "":
				break
			else:
				print ("Authorization failed (no password entered).")
		# store the password
		if confirm("Do you want to securely store the password in the keyring of your operating system?",default=True):
			keyring.set_password(config.DATABASE, config.USER, config.PASSWORD)
			print("Password has been stored. You will not have to enter it again the next time. If you need to edit the password use the keychain manager of your system.")
Example #5
0
def set_password(config, password=None):
    """
    Save the password safely
    """
    if password is None:
        password = getpass.getpass('Dein HSR-Kennwort (wird sicher im Keyring gespeichert): ')
    keyring.set_password('openhsr-connect', config['login']['username'], password)
Example #6
0
def set(target, username):
    target_list = lst(targets())
    if target not in target_list:
        raise ValueError("%s must be one of %r" % (target, target_list))

    keyring.set_password(target, username, getpass.getpass())
    print "Password set for %s, %s" % (target, username)
Example #7
0
def set_password(password):
    """Stores the password in the keyring."""
    username = get_conf(USERNAME_KEY)
    if not username:
        raise ValueError("Cannot set password without a username specified.")

    keyring.set_password("system", username, password)
Example #8
0
def config_get(config, section, key=None, default=None):
    """Return value that matches key in config settings.
    Reference keyring if needed.
    """
    config_section = config.get(section)
    if not key:
        return config_section
    if config_section.get(key, default) == 'USE_KEYRING':
        keyring_path = '%s/%s' % (section, key)
        keyring_value = keyring.get_password('serverherald', keyring_path)
        if keyring_value is None:
            print ('The keyring storage mechanism has been selected for'
                   '%s but the keyring is empty' % keyring_path)

            while 1:
                user_value = getpass.getpass("%s: " % key)
                if user_value != '':
                    keyring.set_password('serverherald', keyring_path,
                                         user_value)
                    break
            return user_value
        else:
            return keyring_value
    else:
        return config_section.get(key, default)
Example #9
0
def run(pelican):
    update_settings(pelican)

    host = pelican.settings['IMAP_IMPORTER']['HOST']
    user = pelican.settings['IMAP_IMPORTER']['USER']
    folders = pelican.settings['IMAP_IMPORTER']['FOLDERS']

    new_password = False
    password = keyring.get_password('PELICAN_IMAP_IMPORTER', user)
    if password is None:
        password = get_password(user)
        new_password = True

    host = pelican.settings['IMAP_IMPORTER']['HOST']

    # Connect
    imap = None
    try:
        imap = imaplib.IMAP4(host)
        context = ssl.create_default_context()
        imap.starttls(context)
    except Exception as e:
        logger.critical(_log + "Couldn't connect to '" + host + "'")
        logger.critical(_log + str(e))
        exit()

    # Login
    try_again = True
    fail_counter = 0
    while try_again:
        try:
            imap.login(user, password)
            try_again = False
        except imaplib.IMAP4_SSL.error as e:
            fail_counter += 1
            logger.warning(_log + "Authentication failed!")
            logger.warning(_log + "Make sure that the user name and password are correct")
            if fail_counter > 3:
                exit()
            password = get_password(user)
            new_password = True

    # successful login
    if new_password:
        keyring.set_password('PELICAN_IMAP_IMPORTER', user, password)
    
    for folder in folders:
        imap.select(folder)
        typ, data = imap.search(None, 'ALL')
        for num in data[0].split():
            typ, data = imap.fetch(num, '(RFC822)')
            #imap.append('INBOX.Server.Comments', None, None, message=data[0][1])
            msg = email.message_from_bytes(data[0][1])
            if process_email(pelican.settings, msg):
                del msg['X-PELICAN-IMAP-IMPORTER']
                msg['X-PELICAN-IMAP-IMPORTER'] = 'processed-debug4'
                imap.store(num, '+FLAGS', '\\Deleted') # delete email
                imap.append(folder, '\\Seen', None, message=msg.as_bytes())
        imap.expunge()
    imap.logout()
  def locked_delete(self):
    """Delete Credentials file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name, '')
Example #11
0
File: umma.py Project: mankoff/umma
    def get_user_pass(self, _, reset=False):

        if reset is True:
            with app.open('user', 'r') as f:
                user = f.read()
            keyring.delete_password("umma", user) # delete password
            with app.open('user','w') as f:
                os.remove(f.name)
        
        try:
            with app.open('user', 'r') as f:
                user = f.read()
        except IOError:
            w = rumps.Window(message='US Mobile login name/email',
                             title='Login',
                             dimensions=(250,24),
                             default_text="*****@*****.**")
            r = w.run()
            user = r.text

        passwd = keyring.get_password("umma", user)
        if passwd is None:
            w = rumps.Window(message='US Mobile login password',
                             title='Login',
                             dimensions=(250, 24),
                             default_text="Your password")
            r = w.run()
            passwd = r.text
            keyring.set_password("umma", user, passwd)
        with app.open('user', 'w') as f:
            f.write(user)
        return user, passwd
Example #12
0
def get_config_data():
    fn = os.path.expanduser(DEFAULT_CONFIG_FILE)
    data = {}
    try:
        if os.path.exists(fn):
            with open(fn) as fd:
                data = yaml.safe_load(fd)

            if 'password' in data:
                keyring.set_password("zmon-cli", data['user'], data['password'])
                del data['password']
                with open(fn, mode='w') as fd:
                    yaml.dump(data, fd, default_flow_style=False,
                              allow_unicode=True,
                              encoding='utf-8')
        else:
            clickclick.warning("No configuration file found at [{}]".format(DEFAULT_CONFIG_FILE))
            data['url'] = click.prompt("ZMon Base URL (e.g. https://zmon2.local/rest/api/v1)")
            data['user'] = click.prompt("ZMon username", default=os.environ['USER'])

            with open(fn, mode='w') as fd:
                yaml.dump(data, fd, default_flow_style=False,
                          allow_unicode=True,
                          encoding='utf-8')
    except Exception as e:
        error(e)

    return validate_config(data)
Example #13
0
def get_auth_token():
    global token

    if token is not None:
        return token

    import keyring

    token = keyring.get_password("github", fake_username)
    if token is not None:
        return token

    print(
        "Please enter your github username and password. These are not "
        "stored, only used to get an oAuth token. You can revoke this at "
        "any time on Github."
    )
    user = input("Username: "******"Password: "******"scopes": ["public_repo", "gist"],
        "note": "IPython tools",
        "note_url": "https://github.com/ipython/ipython/tree/master/tools",
    }
    response = requests.post("https://api.github.com/authorizations", auth=(user, pw), data=json.dumps(auth_request))
    response.raise_for_status()
    token = json.loads(response.text)["token"]
    keyring.set_password("github", fake_username, token)
    return token
Example #14
0
    def login(self):
        from work import get_setting_dict
        self.email = get_setting_dict()['email']
        #self.username = self.getCredentials()['username']
        if get_setting_dict().has_key('explicitFBToken'):
            self.fbConnection.logonTok(get_setting_dict()['explicitFBToken'])
        else:
            password = keyring.get_password('fogbugz', self.email)
            if not password:
                while True:
                    if not password:
                        import getpass
                        password = getpass.getpass("FogBugz password: "******"No username was found!")
        #print self.username
        self.ixPerson = self.usernameToIXPerson()
Example #15
0
def _setUp_maildiff(log, config):
	"""	this function prompts user to enter email settings
		for this git maildiff command to store in .gitconfig
		while password is stored in os keychain.

		Args:
			config(dict): existing config from .gitconfig
	"""
	# check if data in  global config
	if not config.has_key('maildiff.mailfrom'):
		log.info("\x1b[32mFirst time mail setup.\x1b[m")
		userEmail = config['user.email']
		log.warning("Do you want to use your git email '%s' to send diffs or any other email address ?", userEmail)
		ret = raw_input('[YES]')
		if ret.lower() in ['', 'yes', 'y']:
			ret = userEmail
			__update_config(log, 'maildiff.mailfrom', ret)
		else:
			ret = __validate_address(ret)
			_exec_git_command(log, 'git maildiff.mailfrom %s' % ret)
		__update_config(log, 'maildiff.mailfrom', ret)
		log.info("Please enter password for the email: %s" , ret)
		emailPwd = getpass.getpass(prompt=" Password: "******"Add SMTP details for '%s'.", ret)
		smtpServer = raw_input(" SMTP Server: ")
		__update_config(log, 'maildiff.smtpserver', smtpServer)
		smtpServerPort = raw_input(" SMTP Server Port: ")
		__update_config(log, 'maildiff.smtpserverport', smtpServerPort)
		smtpEncryption = raw_input(" Server Encryption: ")
		__update_config(log, 'maildiff.smtpencryption', smtpEncryption)
	return True
Example #16
0
File: base.py Project: lvsv/lancet
    def get_credentials(self, service, checker=None):
        url = self.config.get(service, "url")
        username = self.config.get(service, "username")
        key = "lancet+{}".format(url)
        if username:
            password = keyring.get_password(key, username)
            if password:
                return url, username, password

        with taskstatus.suspend():
            while True:
                click.echo("Please provide your authentication information for {}".format(url))
                if not username:
                    username = click.prompt("Username")
                else:
                    click.echo("Username: {}".format(username))
                password = click.prompt("Password", hide_input=True)

                if checker:
                    with taskstatus("Checking provided credentials") as ts:
                        if not checker(url, username, password):
                            ts.fail("Login failed")
                            username, password = None, None
                            continue
                        else:
                            ts.ok("Correctly authenticated to {}", url)

                keyring.set_password(key, username, password)
                return url, username, password
Example #17
0
def store(username):
    """
    Store given password for this username to keystore
    """
    passwd = getpass.getpass()
    keyring.set_password('linkedinpy', username, passwd)
    click.echo("Password updated successfully")
Example #18
0
 def _login(self, username):
     import keyring
     from lxml import html
     # Get password from keyring or prompt
     password_from_keyring = keyring.get_password("astroquery:www.eso.org", username)
     if password_from_keyring is None:
         password = getpass.getpass("{0}, enter your ESO password:\n".format(username))
     else:
         password = password_from_keyring
     # Authenticate
     print("Authenticating {0} on www.eso.org...".format(username))
     login_response = self.request("GET", "https://www.eso.org/sso/login")
     login_result_response = self._activate_form(login_response,
                                                 form_index=-1,
                                                 inputs={'username': username,
                                                         'password':password})
     root = html.document_fromstring(login_result_response.content)
     authenticated = (len(root.find_class('error')) == 0)
     if authenticated:
         print("Authentication successful!")
     else:
         print("Authentication failed!")
     # When authenticated, save password in keyring if needed
     if authenticated and password_from_keyring is None:
         keyring.set_password("astroquery:www.eso.org", username, password)
     return authenticated
Example #19
0
  def test_json_credentials_storage(self):
    access_token = 'foo'
    client_id = 'some_client_id'
    client_secret = 'cOuDdkfjxxnv+'
    refresh_token = '1/0/a.df219fjls0'
    token_expiry = datetime.datetime.utcnow()
    user_agent = 'refresh_checker/1.0'

    credentials = OAuth2Credentials(
        access_token, client_id, client_secret,
        refresh_token, token_expiry, GOOGLE_TOKEN_URI,
        user_agent)

    m = mox.Mox()
    m.StubOutWithMock(keyring, 'get_password')
    m.StubOutWithMock(keyring, 'set_password')
    keyring.get_password('my_unit_test', 'me').AndReturn(None)
    keyring.set_password('my_unit_test', 'me', credentials.to_json())
    keyring.get_password('my_unit_test', 'me').AndReturn(credentials.to_json())
    m.ReplayAll()

    s = Storage('my_unit_test', 'me')
    self.assertEquals(None, s.get())

    s.put(credentials)

    restored = s.get()
    self.assertEqual('foo', restored.access_token)
    self.assertEqual('some_client_id', restored.client_id)

    m.UnsetStubs()
    m.VerifyAll()
def configure(config_file, env):
    config = {}
    conf = SafeConfigParser()
    passwd = None
    if conf.read(config_file):
        config['username'] = conf.get(env, 'username')
        config['dreadnot'] = conf.get(env, 'dreadnot')
        config['region'] = conf.get(env, 'region')
    else:
        config['dreadnot'] = raw_input('Dreadnot URL:')
        config['region'] = raw_input('Deployment region:')
        config['username'] = raw_input('Dreadnot username:'******'dreadnot', 'region', 'username'):
            conf.set(env, name, config[name])
        with open(config_file, 'w') as f:
            conf.write(f)
    if keyring:
        passwd = keyring.get_password('dreadnot', config['dreadnot'])
    if not passwd:
        passwd = getpass.getpass('Dreadnot password:'******'dreadnot', config['dreadnot'], passwd)
    config['password'] = passwd
    return config
    def configure(self):
        print("Enter user email ([email protected]) or press enter to skip")

        username = raw_input('({0})>'.format(self.USERNAME))

        print("Enter email password or press enter to skip")
        password = getpass.getpass(
            prompt='>')  # To stop shoulder surfing
        if username:
            gmailSettings.USERNAME = username
        if password:
            keyring.set_password(self.KEYRING_APP_ID, self.USERNAME, password)

        print("Clear alerts list? (yes/no)?")
        import distutils.util

        try:
            if distutils.util.strtobool(raw_input(">")):
                gmailSettings.SEND_ALERT_TO = []  # Clear the list
                print("Alerts list cleared")
        except ValueError:
            pass

        print("Send alerts to (press enter when done):")
        while True:
            user_input = raw_input('({0})>'.format(','.join(self.SEND_ALERT_TO)))
            if not user_input:
                break
            else:
                gmailSettings.SEND_ALERT_TO.append(user_input)
        self.saveSettings()
Example #22
0
def get_username_and_password(force_fresh_input = False):
    """
    Reads username and password from keyring or prompts user for them
    and saves them to the keyring. force_fresh_input enforces
    the prompt (to be used after bad login for example).
    """
    import keyring, getpass

    username = keyring.get_password("mekk.greader", "default-login")
    if (not username) or force_fresh_input:
        while True:
            username = raw_input("Your Google account name: ")
            if username:
                break
        keyring.set_password("mekk.greader", "default-login", username)

    password = keyring.get_password("mekk.greader", username)
    if (not password) or force_fresh_input:
        while True:
            password = getpass.getpass("Password for %s: " % username)
            if password:
                break
        keyring.set_password("mekk.greader", username, password)

    return username, password
Example #23
0
    def get_config(self, args):
        stored_config_harvester = keyring.get_password("INDX", "INDX_Fitbit_Harvester")
        stored_config_fitbit = keyring.get_password("Fitbit.com", "Fitbit")

        self.logger.debug("Loaded harvester config from keyring: {0}".format(stored_config_harvester))
        self.logger.debug("Loaded fitbit config from keyring: {0}".format(stored_config_fitbit))

        if stored_config_fitbit is None :
            token_url = self.fitbit.get_token_url()
            config_fitbit = {}
            config_fitbit["url"] = token_url['url']
            config_fitbit["req_token"] = token_url['req_token']
        else :
            if (type(stored_config_fitbit) != dict):
                config_fitbit = json.loads(stored_config_fitbit)
            # if (type(config_fitbit) != dict):
            #     config_fitbit = json.loads(config_fitbit)
            if 'token' not in config_fitbit :
                token_url = self.fitbit.get_token_url()
                config_fitbit["url"] = token_url['url']
                config_fitbit["req_token"] = token_url['req_token']
                keyring.set_password("Fitbit.com", "Fitbit", json.dumps(config_fitbit))
        if stored_config_harvester is None:
            return json.dumps({"fitbit":config_fitbit}) # don't send the req_token
        return json.dumps({"fitbit":config_fitbit, "harvester":json.loads(stored_config_harvester)}) # don't send the req_token
Example #24
0
def set_password(smtp_server, from_email):
    ''' Set the keyring password for the mail connection. Interactive.'''
    if keyring is None:
        raise ImportError('keyring module missing - service unsupported')

    password = getpass.getpass(prompt='Enter password for {} using {}: '.format(from_email, smtp_server))
    keyring.set_password(smtp_server, from_email, password)
Example #25
0
    def set_config(self, args):
        stored_config_harvester = keyring.get_password("INDX", "INDX_Fitbit_Harvester")
        if stored_config_harvester is not None:
            stored_config_harvester = json.loads(stored_config_harvester)
        stored_config_fitbit = keyring.get_password("Fitbit.com", "Fitbit")
        if stored_config_fitbit is not None:
            stored_config_fitbit = json.loads(stored_config_fitbit)

        received_config = json.loads(args['config'])
        if (type(received_config) != dict):
            received_config = json.loads(received_config)
        self.logger.debug("Received config ({0}): {1}".format(type(received_config), received_config))
        config = {}
        if 'fitbit' in received_config:
            fitbit_config = received_config['fitbit']
            if fitbit_config and ('pin' in fitbit_config) and ('req_token' in fitbit_config): # this should check for the req_token in the stored config!
                self.logger.debug("Received pin: {0}".format(fitbit_config['pin']))
                try:
                    token = self.fitbit.get_token_with_pin(fitbit_config['pin'], fitbit_config['req_token'])
                    self.logger.debug("Got auth token {0}, of type {1}".format(token, type(token)))
                    if token:
                        config['token']=token
                        keyring.set_password("Fitbit.com", "Fitbit", json.dumps(config))
                except Exception as exc:
                    self.logger.error("Could not authorise to fitbit, with pin {0}, error: {1}".format(fitbit_config['pin'], exc))
        if 'harvester' in received_config:
            harvester_config = received_config['harvester']
            if harvester_config != stored_config_harvester:
                keyring.set_password("INDX", "INDX_Fitbit_Harvester", json.dumps(harvester_config)) 
Example #26
0
def main(argv):
    encrypt = argv[0]
    keyfile = argv[1]
    service = argv[2]
    username = argv[3]

    if isinstance(encrypt, str):
        if encrypt.lower().startswith('t'):
            encrypt = True
        else:
            encrypt = False

    if encrypt:
        password = argv[4]
        key = RSA.generate(1024)
        cipher = PKCS1_v1_5.new(key)

        keyring.set_password(service, username, key.exportKey())

        with open(keyfile, 'wb') as outf:
            outf.write(cipher.encrypt(password))
    else:
        key = RSA.importKey(keyring.get_password(service, username))
        cipher = PKCS1_v1_5.new(key)

        with open(keyfile, 'rb') as inf:
            return cipher.decrypt(inf.read(), None)
Example #27
0
def read_config(args):
    config = osp.join(configdir, "login.conf")

    username = ""
    password = ""

    # read
    if keyring:
        log.debug("Reading credentials from keyring")
        try:
            username, password = (keyring.get_password(myname, "").split("\n") + ["\n"])[:2]
        except IOError as e:
            log.error(e)
    else:
        log.debug("Reading credentials from '%s'" % config)
        try:
            with open(config, "r") as fd:
                username, password = (fd.read().splitlines() + ["\n"])[:2]
        except IOError as e:
            log.error(e)

    # save
    if args.username or args.password:
        log.info("Saving credentials")
        if keyring:
            keyring.set_password(myname, "", "%s\n%s" % (args.username or username, args.password or password))
        else:
            try:
                with open(config, "w") as fd:
                    fd.write("%s\n%s\n" % (args.username or username, args.password or password))
                os.chmod(config, 0600)
            except IOError as e:
                log.error(e)

    return dict(username=username, password=password)
    def configure(self):
        print("Enter database username (postgres) or press enter to skip")
        username = raw_input('({0})>'.format(self.USERNAME))
        if username:
            db_settings.USERNAME = username

        print("Enter database password or press enter to skip")
        password = getpass.getpass(
            prompt='>')  # To stop shoulder surfing
        if password:
            keyring.set_password(self.KEYRING_APP_ID, self.USERNAME, password)

        print("Enter database server HOST Address to edit (127.0.0.1) or press enter to skip")
        DB_HOST = raw_input('({0})>'.format(self.DB_HOST))
        if DB_HOST:
            db_settings.DB_HOST = DB_HOST

        print("Enter database server port to edit (playerStats) or press enter to skip")
        port = raw_input('({0})>'.format(str(self.PORT)))
        if port:
            db_settings.PORT = int(port)
        self.saveSettings()

        print("Settings Updated")
        sys.exit(0)
Example #29
0
    def login(self, reddit_id):

        passwd = keyring.get_password(app_name, reddit_id)

        if not passwd:
            passwd = getpass.getpass()

            # save it for next time
            keyring.set_password(app_name, reddit_id, passwd)


        headers = {"User-Agent": config['reddit_boot']}


        auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
        data = {'grant_type': 'password' ,'username': reddit_id, 'password': passwd}

        response = requests.post(token_url,data=data,auth=auth,headers=headers)

        if response.status_code != 200:
            pprint(response.json())
            sys.exit()

        json_data= response.json()

        self.access_token = json_data['access_token']

        return User(reddit_id)
Example #30
0
def get_auth():
    def check_auth(auth):
        return requests.head(full_repo_url, auth=auth).status_code != httplib.UNAUTHORIZED

    # config file init
    config_file = os.path.join(BaseDirectory.save_config_path("malucrawl_reportificate"), "settings.ini")
    config = configparser.SafeConfigParser()
    config.read(config_file)

    if not config.has_section('auth'):
        config.add_section('auth')

    try:
        username = config.get('auth', 'username')
    except configparser.NoOptionError:
        username = raw_input("Username: "******"Authorization Failed"
        username = raw_input("Username: ")
        password = getpass.getpass()

    keyring.set_password(github_url, username, password)
    config.set('auth', 'username', username)
    config.write(open(config_file, 'w'))

    return (username, password)
Example #31
0
def save_default_recipient(recipient_email: str):
    keyring.set_password(KEYRING_NAME, 'default_recipient', recipient_email)
Example #32
0
 def _set_key(self, servicename, key, value, **kwargs):
     keyring.set_password(servicename, key, value)
def _set_password(service):
    from keyring import set_password
    from getpass import getpass
    set_password(service, input("Username: "), getpass.getpass())
Example #34
0
import sys, keyring

print sys.argv[1], sys.argv[2], sys.argv[3]

keyring.set_password("system", "myphoneemail", sys.argv[1])
keyring.set_password("system", "email", sys.argv[2])
keyring.set_password("system", sys.argv[2], sys.argv[3])
Example #35
0
def SetPassword(new_password):
    keyring.set_password(_systemname, _username, new_password)
    _log.info("new password set to: {}".format(new_password))
def build_repo(args):
    payload = {
        'clean': args.clean,
        'platform': args.target,
        'repo': args.repo,
        'extra_symbols': args.extra_symbols
    }

    if args.replace_file:
        replace = []
        for pair in args.replace_file:
            dest, src = pair.split(':')
            print(dest)
            cwd = os.getcwd()

            with open(join(cwd, src), 'r') as srcfile:
                replace.append({dest: srcfile.read()})

        payload['replace'] = replace
        log.debug("Payload is: %s", payload)

    host = urlparse(args.api_url).netloc
    user = password = None

    try:
        user, host = urlparts.netloc.rsplit('@', 1)
    except:
        pass
    else:
        try:
            user, password = user.split(':', 1)
        except:
            pass

    user = args.user or user

    if not user:
        try:
            user = input('mbed username: '******'')
            return 1

    if not password:
        try:
            password = keyring.get_password(host, user)
            if password is None:
                raise ValueError
        except:
            try:
                password = getpass.getpass('mbed password: '******'')
                return 1

    log.debug("Auth info: host='%s' user='******' password='******'", host, user,
              password)

    # Send task to api
    log.debug(args.api_url + "/api/v2/tasks/compiler/start/ | data: %r",
              payload)
    r = requests.post(args.api_url + "/api/v2/tasks/compiler/start/",
                      json=payload,
                      auth=(user, password))

    log.debug(r.content)

    if r.status_code != 200:
        raise Exception("Error while talking to the mbed API. Status: %s" %
                        r.status_code)

    if keyring and confirm("Save password for user '%s' to keyring?"):
        keyring.set_password(urlparts.netloc, args.user, password)

    uuid = r.json()['result']['data']['task_id']
    log.debug("Task accepted and given ID: %s", uuid)

    # Poll for output
    success = False
    for check in range(0, 40):
        log.debug("Checking for output: cycle %s of %s", check, 10)
        time.sleep(2)
        url = args.api_url + "/api/v2/tasks/compiler/output/%s" % uuid
        r = requests.get(url, auth=(user, password))
        log.debug(r.content)
        response = r.json()
        messages = response['result']['data']['new_messages']
        percent = 0

        for message in messages:
            if message.get('message'):
                if message.get('type') != 'debug':
                    log.info("[%s] %s", message['type'], message['message'])

            if message.get('action'):
                if message.get('percent'):
                    percent = message['percent']
                log.info("[%s%% - %s] %s", percent, message['action'],
                         message.get('file', ''))

        if response['result']['data']['task_complete']:
            log.info("Task completed.")
            success = response['result']['data']['compilation_success']
            log.info("Compile success: %s", success)
            break

    # Download binary
    if success:
        log.info("Downloading your binary")
        params = {
            'repomode': True,
            'program': response['result']['data']['program'],
            'binary': response['result']['data']['binary'],
            'task_id': uuid
        }
        r = requests.get(args.api_url + "/api/v2/tasks/compiler/bin/",
                         params=params,
                         auth=(user, password))
        destination = join(args.destdir or os.getcwd(),
                           response['result']['data']['binary'])

        with open(destination, 'wb') as fd:
            for chunk in r.iter_content(1024):
                fd.write(chunk)

        log.info("Finished!")
Example #37
0
 def set_wallet_password(self, password):
     keyring.set_password('tribler', 'btc_wallet_password', password)
    # read and attach all files
    for file_name in attachments:
        # read in bytes mode to handle all file types
        with open(file_name, 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            # add the file data to the MIME part
            part.set_payload(attachment.read())
        # apparently, encoding in ASCII is necessary for it to be in email
        encoders.encode_base64(part)
        # necessary headers to recognize as file attachment
        part.add_header("Content-Disposition",
                        f'attachment; filename= {file_name}')
        # attach the file
        message.attach(part)
    # convert the message with attachments in order to send
    text = message.as_string()
    context = ssl.create_default_context()
    # connect to the gmail SMTP server
    with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server:
        # login to gmail account
        server.login(sender, get_password())
        # send email to each recipient
        for recipient in RECIPIENTS:
            server.sendmail(sender, recipient, text)


if __name__ == '__main__':
    em = input('Enter the email to add to the keychain: ')
    pw = input('Enter the password for that email: ')
    keyring.set_password('gmail', em, pw)
Example #39
0
    def setUp(self):
        """Set up for test"""
        print("Set up for [" + self.shortDescription() + "]")

        print("password is set ", keyring.set_password(SKYPE_KEYRING, "nexus12142", "xxxxxxxxx"))
def set_password(email, password):
    keyring.set_password('gmail', email, password)  # setting the password
Example #41
0
 def set_password(self, password):
     try:
         logging.debug("Storing password in the keyring")
         keyring.set_password("UFO", conf.USER, str(password))
     except:
         logging.debug("import keyring failed, (keyring.set_password)!")
Example #42
0
import getpass
import keyring  # pip3 install keyring
import re

# Customize this!

define_success = {'QB Rush': 3, 'Outside Run': 2, 'Inside Run': 2, 'Pass': 0}

#Checking/Prompting for username/password

user_name = keyring.get_password('glb2', 'user_name')
password = keyring.get_password('glb2', 'password')
if user_name is None:
    user_name = input('Your GLB2 Username: '******'glb2', 'user_name', user_name)
if password is None:
    password = getpass.getpass('Your GLB2 Password: '******'glb2', 'password', password)

login = {'action': 'login', 'user_name': user_name, 'password': password}

# Grabs the whole defensive playbook:

import requests  # pip3 install requests
import json

with requests.Session() as c:
    c.post('http://glb2.warriorgeneral.com/game/login', data=login)
    r = c.get('http://glb2.warriorgeneral.com/game/playbook/O/ajax').content
    w = c.get('http://glb2.warriorgeneral.com/game/playbook/D/ajax').content
Example #43
0
    def activate(cls, ctxt, args):
        """
        Called to determine whether to activate the extension.  This call
        is made after processing command line arguments, and must
        return either ``None`` or an initialized instance of the
        extension.  Note that this is a class method.

        :param ctxt: An instance of ``timid.context.Context``.
        :param args: An instance of ``argparse.Namespace`` containing
                     the result of processing command line arguments.

        :returns: An instance of the extension class if the extension
                  has been activated, ``None`` if it has not.  If this
                  method returns ``None``, no further extension
                  methods will be called.
        """

        # If no pull request was specified, do nothing
        if not args.github_pull:
            return None

        ctxt.emit('Github plugin activated')

        # Ensure we have a password
        service = 'timid-github!%s' % args.github_api
        passwd = args.github_pass
        if passwd is None and not args.github_keyring_set:
            # Try getting it from the keyring
            passwd = keyring.get_password(service, args.github_user)
        if passwd is None:
            # OK, try prompting for it
            passwd = getpass.getpass('[%s] Password for "%s"> ' %
                                     (args.github_api, args.github_user))

        # Are we supposed to set it?
        if args.github_keyring_set:
            ctxt.emit('Saving password in keyring as requested')
            keyring.set_password(service, args.github_user, passwd)

        # Now we have authentication information, get a Github handle
        gh = github.Github(args.github_user, passwd, args.github_api)

        # Next, interpret the pull request designation
        try:
            # Try JSON first
            pull_raw = json.loads(args.github_pull)
        except ValueError:
            # Raw string
            repo, _sep, number = args.github_pull.partition('#')

            # Interpret the number
            if not number or not number.isdigit():
                sys.exit('Invalid pull request number "%s"' % number)
            number = int(number)

            # Interpret the repo
            if '/' not in repo:
                user = gh.get_user()
                repo = '%s/%s' % (user.login, repo)

            # Look up the pull request
            try:
                repo = gh.get_repo(repo)
                pull = repo.get_pull(number)
            except Exception:
                # No such pull request, I guess
                sys.exit('Unable to resolve pull request "%s"' %
                         args.github_pull)
        else:
            # OK, we have raw JSON data; wrap it in a PullRequest
            pull = gh.create_from_raw_data(github.PullRequest.PullRequest,
                                           pull_raw)

        ctxt.emit('Testing pull request %s#%d' %
                  (pull.base.repo.full_name, pull.number))

        # Need the repository name
        repo_name = pull.base.repo.name

        # Also need the branches
        repo_branch = pull.base.ref
        change_branch = pull.head.ref

        # Select the correct repository URL
        repo_url = _select_url(args.github_repo, pull.base.repo)
        ctxt.emit('Base repository %s' % repo_url, level=2)

        # Select the correct change repository URL.  If not
        # independently specified, default to the same as the
        # repo_url.  Note: the URLs could legally be the same, as a PR
        # could be made from one branch to another of the same
        # repository.
        change_url = _select_url(args.github_change_repo or args.github_repo,
                                 pull.head.repo)
        ctxt.emit('PR repository %s' % change_url, level=2)

        # With the pull, we need to select an appropriate commit
        last_commit = list(pull.get_commits())[-1]

        # Set up the final status information
        final_status = {
            'status': 'success',
            'text': 'Tests passed!',
            'url': args.github_status_url,
        }

        # Handle the --github-override option
        if args.github_override:
            try:
                override_raw = json.loads(args.github_override)
                for key in final_status:
                    if key in override_raw:
                        final_status[key] = override_raw[key]
            except ValueError:
                pass

        # Now we process the other override options
        if args.github_override_status:
            final_status['status'] = args.github_override_status
        if args.github_override_text:
            final_status['text'] = args.github_override_text
        if args.github_override_url:
            final_status['url'] = args.github_override_url

        # Set some variables in the context for the use of any callers
        ctxt.variables.declare_sensitive('github_api_password')
        ctxt.variables.update({
            'github_api':
            args.github_api,
            'github_api_username':
            args.github_user,
            'github_api_password':
            passwd,
            'github_repo_name':
            repo_name,
            'github_pull':
            '%s#%d' % (pull.base.repo.full_name, pull.number),
            'github_base_repo':
            repo_url,
            'github_base_branch':
            repo_branch,
            'github_change_repo':
            change_url,
            'github_change_branch':
            change_branch,
            'github_success_status':
            final_status['status'],
            'github_success_text':
            final_status['text'],
            'github_success_url':
            final_status['url'],
            'github_status_url':
            args.github_status_url,
        })

        # We are all set; initialize the extension
        return cls(gh, pull, last_commit, args.github_status_url, final_status,
                   repo_name, repo_url, repo_branch, change_url, change_branch)
Example #44
0
 def process_bind_param(self, value, uuid):
     if value is None:
         return value
     keyring.set_password('systemcheck', username=uuid, password=value)
Example #45
0
 def _set_password(self):
     """
     Записывает пароль в keyring
     :return:
     """
     keyring.set_password(self._service_name, self._user, self._password)
Example #46
0
def store_password_in_keyring(host, username, password):
    keyring.set_password('bonfire_' + host, username, password)
Example #47
0
 def set_password(self, password):
     keyring.set_password('photini', self.name, password)
Example #48
0
def process_auth(args, config):
    # Set up logging
    logging.getLogger().setLevel(getattr(logging, args.log_level.upper(),
                                         None))

    if config.region is None:
        config.region = util.Util.get_input("AWS Region: ")
        logging.debug('%s: region is: %s', __name__, config.region)

    # If there is a valid cache and the user opted to use it, use that instead
    # of prompting the user for input (it will also ignroe any set variables
    # such as username or sp_id and idp_id, as those are built into the SAML
    # response). The user does not need to be prompted for a password if the
    # SAML cache is used.
    if args.saml_assertion:
        saml_xml = base64.b64decode(args.saml_assertion)
    elif args.saml_cache and config.saml_cache:
        saml_xml = config.saml_cache
        logging.info('%s: SAML cache found', __name__)
    else:
        # No cache, continue without.
        logging.info('%s: SAML cache not found', __name__)
        if config.username is None:
            config.username = util.Util.get_input("Google username: "******"Google IDP ID: ")
            logging.debug('%s: idp is: %s', __name__, config.idp_id)
        if config.sp_id is None:
            config.sp_id = util.Util.get_input("Google SP ID: ")
            logging.debug('%s: sp is: %s', __name__, config.sp_id)

        # There is no way (intentional) to pass in the password via the command
        # line nor environment variables. This prevents password leakage.
        keyring_password = None
        if config.password_cmd:
            with os.popen(config.password_cmd) as subproc:
                config.password = subproc.read().strip()
        elif config.keyring:
            keyring_password = keyring.get_password("aws-google-auth",
                                                    config.username)
            if keyring_password:
                config.password = keyring_password
            else:
                config.password = util.Util.get_password("Google Password: "******"Google Password: "******"aws-google-auth", config.username,
                                 config.password)

    # We now have a new SAML value that can get cached (If the user asked
    # for it to be)
    if args.saml_cache:
        config.saml_cache = saml_xml

    # The amazon_client now has the SAML assertion it needed (Either via the
    # cache or freshly generated). From here, we can get the roles and continue
    # the rest of the workflow regardless of cache.
    amazon_client = amazon.Amazon(config, saml_xml)
    roles = amazon_client.roles

    # Determine the provider and the role arn (if the the user provided isn't an option)
    if config.role_arn in roles and not config.ask_role:
        config.provider = roles[config.role_arn]
    else:
        if config.account and config.resolve_aliases:
            aliases = amazon_client.resolve_aws_aliases(roles)
            config.role_arn, config.provider = util.Util.pick_a_role(
                roles, aliases, config.account)
        elif config.account:
            config.role_arn, config.provider = util.Util.pick_a_role(
                roles, account=config.account)
        elif config.resolve_aliases:
            aliases = amazon_client.resolve_aws_aliases(roles)
            config.role_arn, config.provider = util.Util.pick_a_role(
                roles, aliases)
        else:
            config.role_arn, config.provider = util.Util.pick_a_role(roles)
    if not config.quiet:
        print("Assuming " + config.role_arn)
        print("Credentials Expiration: " +
              format(amazon_client.expiration.astimezone(get_localzone())))

    if config.print_creds:
        amazon_client.print_export_line()

    if config.profile:
        config.write(amazon_client)
Example #49
0
def _main(argv=None):
    # Protect access token and potentially encryption keys
    block_tracing()

    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()
    userspacefs.add_cli_arguments(parser)
    parser.add_argument("-c", "--config-file", help="config file path")
    parser.add_argument(
        "-e",
        "--encrypted-folder",
        dest='encrypted_folders',
        type=parse_encrypted_folder_arg,
        default=[],
        action='append',
        help=
        "relative paths of encrypted folders, can be used multiple times. requires safefs"
    )
    parser.add_argument(
        "--print-default-config-file",
        action='store_true',
        help="print default config file path to standard out and quit")
    parser.add_argument("mount_point", nargs='?')
    args = parser.parse_args(argv[1:])

    config_dir = appdirs.user_config_dir(APP_NAME)

    if args.config_file is not None:
        config_file = args.config_file
    else:
        config_file = os.path.join(config_dir, "config.json")

    if args.print_default_config_file:
        print(config_file)
        return 0

    try:
        os.makedirs(config_dir, exist_ok=True)
    except OSError as e:
        print("Unable to create configuration directory: %s" % (e, ))
        return -1

    config = {}
    try:
        f = open(config_file)
    except IOError as e:
        if e.errno != errno.ENOENT: raise
    else:
        try:
            with f:
                config = json.load(f)
        except ValueError as e:
            print("Config file %r is not valid json: %s" % (config_file, e))
            return -1

    mount_point = args.mount_point
    if mount_point is None:
        mount_point = config.get("mount_point")

    if not args.smb_no_mount and mount_point is None:
        parser.print_usage()
        print("%s: error: please provide the mount_point argument" %
              (os.path.basename(argv[0]), ))
        return 1

    encrypted_folders = config.get("encrypted_folders",
                                   []) + args.encrypted_folders
    if safefs_wrap_create_fs is None and encrypted_folders:
        print(
            "safefs not installed, can't transparently decrypt encrypted folders"
        )
        return 1

    access_token = None
    save_access_token = False
    save_config = False

    access_token_command = config.get("access_token_command", None)
    if access_token_command is not None:
        print("Running %r for access token" %
              (' '.join(access_token_command), ))
        try:
            access_token = subprocess.check_output(
                access_token_command).decode("utf-8")
        except UnicodeDecodeError:
            print("Access token command output is not utf-8 encoded")
            return -1
        except TypeError:
            print("Bad access token command: %r, " % (access_token_command, ))
            return -1

    if access_token is None:
        keyring_user = config.get("keyring_user", None)

        if keyring_user is not None:
            try:
                access_token = keyring.get_password(APP_NAME, keyring_user)
            except KeyringError as e:
                print("Failed to get access token from keyring: %s" % (e, ))

    if access_token is None:
        access_token_privy = config.get("access_token_privy", None)
        if access_token_privy is not None:
            passwd = None
            while True:
                passwd = getpass.getpass(
                    "Enter access token passphrase (not your Dropbox password) (Ctrl-C to quit): "
                )
                try:
                    access_token = privy.peek(access_token_privy,
                                              passwd).decode('utf-8')
                except ValueError:
                    if not yes_no_input(
                            "Incorrect password, create new access token?"):
                        continue
                break
            del passwd

    try_directly = False
    while True:
        if access_token is None:
            save_access_token = True

        if (access_token is None and try_directly and yes_no_input(
                "Want to try entering the access token directly?")):
            print("Go to https://dropbox.com/developers/apps to "
                  "create an app and generate a personal access token.")

            while True:
                access_token = getpass.getpass(
                    "Enter Access token (Ctrl-C to quit): ")
                if not access_token:
                    print("Access tokens cannot be empty")
                    continue
                break

        if access_token is None:
            auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(
                APP_KEY, APP_SECRET)
            authorize_url = auth_flow.start()
            print("We need an access token. Perform the following steps:")
            print("1. Go to " + authorize_url)
            print("2. Click \"Allow\" (you may have to log in first)")
            print("3. Copy the authorization code.")

            while True:
                auth_code = input(
                    "Enter authorization code (Ctrl-C to quit): ")
                if not auth_code:
                    print("Authorization code cannot be empty")
                    continue
                break

            try:
                oauth_result = auth_flow.finish(auth_code)
            except Exception as e:
                print("Authorization code was invalid!")
                try_directly = True
                continue

            access_token = oauth_result.access_token

        # test out access token
        try:
            dropbox.Dropbox(access_token).users_get_current_account()
        except (dropbox.exceptions.BadInputError, dropbox.exceptions.AuthError,
                ValueError) as e:
            print("Error using access token: %s" % (e, ))
            access_token = None
            try_directly = True
        except OSError:
            if not yes_no_input("Error connecting to Dropbox, Try again?"):
                return 1
        else:
            break

    if save_access_token and yes_no_input(
            "We're all connected. Do you want to save your credentials for future runs?",
            default_yes=True):
        keyring_user = ''.join(
            [random.choice("asdfghjklzxcvbnmqwertyuiop") for _ in range(24)])
        try:
            keyring.set_password(APP_NAME, keyring_user, access_token)
        except (KeyringError, RuntimeError) as e:
            print(
                "We need a passphrase to encrypt your access token before we can save it."
            )
            print(
                "Warning: Your access token passphrase must contain enough randomness to be resistent to hacking. You can read this for more info: https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/"
            )
            while True:
                pass_ = getpass.getpass("Enter new access token passphrase: ")
                pass2_ = getpass.getpass(
                    "Enter new access token passphrase (again): ")
                if pass_ != pass2_:
                    print("Passphrases didn't match, please re-enter")
                else:
                    del pass2_
                    break
            config.pop('keyring_user', None)
            config['access_token_privy'] = privy.hide(
                access_token.encode('utf-8'), pass_, server=False)
            del pass_
            save_config = True
        else:
            config.pop('access_token_privy', None)
            config['keyring_user'] = keyring_user
            save_config = True

    if not config.get("asked_send_error_reports", False):
        if yes_no_input(
                "Would you like to help us improve %s by providing anonymous error reports?"
                % (APP_NAME, ),
                default_yes=True):
            config['send_error_reports'] = True
        config['asked_send_error_reports'] = True
        save_config = True

    if not os.path.exists(mount_point):
        if yes_no_input(
                "Mount point \"%s\" doesn't exist, do you want to create it?" %
            (mount_point, ),
                default_yes=True):
            try:
                os.makedirs(mount_point, exist_ok=True)
            except OSError as e:
                print("Unable to create mount point: %s" % (e, ))
                return -1

    if save_access_token and yes_no_input(
            "Do you want \"%s\" to be the default mount point?" %
        (mount_point, ),
            default_yes=True):
        config['mount_point'] = mount_point
        save_config = True

    if save_config:
        with open(config_file, "w") as f:
            json.dump(config, f)

    log.info("Starting %s...", APP_NAME)

    if config.get('send_error_reports', False):
        try:
            version = pkg_resources.require("dbxfs")[0].version
        except Exception:
            log.warning("Failed to get version", exc_info=True)
            version = ''

        try:
            sentry_sdk.init(
                "https://[email protected]/1293235",
                release='%s@%s' % (APP_NAME, version),
                with_locals=False)
        except Exception:
            log.warning("Failed to initialize sentry", exc_info=True)

    cache_folder = os.path.join(appdirs.user_cache_dir(APP_NAME), "file_cache")
    try:
        os.makedirs(cache_folder, exist_ok=True)
    except OSError:
        log.warning(
            "Failed to create cache folder, running without file cache")
        cache_folder = None

    def create_fs():
        fs = CachingFileSystem(DropboxFileSystem(access_token),
                               cache_folder=cache_folder)
        if sys.platform == 'darwin':
            fs = DisableQuickLookFileSystem(fs)

        return fs

    if safefs_wrap_create_fs is not None:
        create_fs = safefs_wrap_create_fs(create_fs, encrypted_folders)

    return userspacefs.simple_main(mount_point, "dbxfs", create_fs, args)
Example #50
0
def storePwd(pwd, username):
    keyring.set_password(SPIDER_NAME, username, pwd)
Example #51
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email',
                         nargs='?',
                         default=None,
                         help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password',
                         nargs='?',
                         default=None,
                         help='The password for your Mint.com account')

    home = os.path.expanduser("~")
    default_session_path = os.path.join(home, '.mintapi', 'session')
    cmdline.add_argument(
        '--session-path',
        nargs='?',
        default=default_session_path,
        help='Directory to save browser session, including cookies. '
        'Used to prevent repeated MFA prompts. Defaults to '
        '$HOME/.mintapi/session.  Set to None to use '
        'a temporary profile.')
    cmdline.add_argument('--accounts',
                         action='store_true',
                         dest='accounts',
                         default=False,
                         help='Retrieve account information'
                         '(default if nothing else is specified)')
    cmdline.add_argument('--budgets',
                         action='store_true',
                         dest='budgets',
                         default=False,
                         help='Retrieve budget information')
    cmdline.add_argument('--budget_hist',
                         action='store_true',
                         dest='budget_hist',
                         default=None,
                         help='Retrieve 12-month budget history information')
    cmdline.add_argument('--net-worth',
                         action='store_true',
                         dest='net_worth',
                         default=False,
                         help='Retrieve net worth information')
    cmdline.add_argument('--credit-score',
                         action='store_true',
                         dest='credit_score',
                         default=False,
                         help='Retrieve current credit score')
    cmdline.add_argument('--credit-report',
                         action='store_true',
                         dest='credit_report',
                         default=False,
                         help='Retrieve full credit report')
    cmdline.add_argument('--extended-accounts',
                         action='store_true',
                         dest='accounts_ext',
                         default=False,
                         help='Retrieve extended account information (slower, '
                         'implies --accounts)')
    cmdline.add_argument('--transactions',
                         '-t',
                         action='store_true',
                         default=False,
                         help='Retrieve transactions')
    cmdline.add_argument(
        '--extended-transactions',
        action='store_true',
        default=False,
        help='Retrieve transactions with extra information and arguments')
    cmdline.add_argument(
        '--start-date',
        nargs='?',
        default=None,
        help='Earliest date for transactions to be retrieved from. '
        'Used with --extended-transactions. Format: mm/dd/yy')
    cmdline.add_argument('--include-investment',
                         action='store_true',
                         default=False,
                         help='Used with --extended-transactions')
    cmdline.add_argument('--skip-duplicates',
                         action='store_true',
                         default=False,
                         help='Used with --extended-transactions')
    # Displayed to the user as a postive switch, but processed back
    # here as a negative
    cmdline.add_argument(
        '--show-pending',
        action='store_false',
        default=True,
        help='Exclude pending transactions from being retrieved. '
        'Used with --extended-transactions')
    cmdline.add_argument('--filename',
                         '-f',
                         help='write results to file. can '
                         'be {csv,json} format. default is to write to '
                         'stdout.')
    cmdline.add_argument('--keyring',
                         action='store_true',
                         help='Use OS keyring for storing password '
                         'information')
    cmdline.add_argument(
        '--headless',
        action='store_true',
        help='Whether to execute chromedriver with no visible window.')
    cmdline.add_argument('--mfa-method',
                         default='sms',
                         choices=['sms', 'email'],
                         help='The MFA method to automate.')
    cmdline.add_argument('--imap-account',
                         default=None,
                         help='IMAP login account')
    cmdline.add_argument('--imap-password',
                         default=None,
                         help='IMAP login password')
    cmdline.add_argument('--imap-server', default=None, help='IMAP server')
    cmdline.add_argument('--imap-folder', default="INBOX", help='IMAP folder')
    cmdline.add_argument('--imap-test',
                         action='store_true',
                         help='Test imap login and retrieval.')
    cmdline.add_argument(
        '--no_wait_for_sync',
        action='store_true',
        default=False,
        help=('By default, mint api will wait for accounts to sync with the '
              'backing financial institutions. If this flag is present, do '
              'not wait for them to sync.'))
    cmdline.add_argument(
        '--wait_for_sync_timeout',
        type=int,
        default=5 * 60,
        help=('Number of seconds to wait for sync.  Default is 5 minutes'))
    cmdline.add_argument(
        '--attention',
        action='store_true',
        help='Display accounts that need attention (None if none).')

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:  # python 2.x
        from __builtin__ import raw_input as input
    except ImportError:  # python 3
        from builtins import input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: "******"MFA CODE:", mfa_code)
        sys.exit()

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext))
        except Exception:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except Exception:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except Exception:
            data = None
    elif options.budget_hist:
        try:
            data = mint.get_budgets(hist=12)
        except Exception:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext))
        except Exception:
            data = None
    elif options.transactions:
        data = mint.get_transactions(
            include_investment=options.include_investment)
    elif options.extended_transactions:
        data = mint.get_detailed_transactions(
            start_date=options.start_date,
            include_investment=options.include_investment,
            remove_pending=options.show_pending,
            skip_duplicates=options.skip_duplicates)
    elif options.net_worth:
        data = mint.get_net_worth()
    elif options.credit_score:
        data = mint.get_credit_score()
    elif options.credit_report:
        data = mint.get_credit_report(details=True)

    # output the data
    if options.transactions or options.extended_transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')

    if options.attention:
        attention_msg = mint.get_attention()
        if attention_msg is None or attention_msg == "":
            attention_msg = "no messages"
        if options.filename is None:
            print(attention_msg)
        else:
            with open(options.filename, 'w+') as f:
                f.write(attention_msg)
Example #52
0
import keyring
keyring.set_password('on', 'for', 'secret')
keyring.get_password('on', 'for')
Example #53
0
 def set_mfa_secret(self, user: str, mfa_secret: str):
     keyring.set_password(FIGGY_KEYRING_NAMESPACE, f'{user}-mfa',
                          mfa_secret)
    def _login(self,
               username=None,
               store_password=False,
               reenter_password=False):
        """
        Login to the NRAO archive

        Parameters
        ----------
        username : str, optional
            Username to the NRAO archive. If not given, it should be specified
            in the config file.
        store_password : bool, optional
            Stores the password securely in your keyring. Default is False.
        reenter_password : bool, optional
            Asks for the password even if it is already stored in the
            keyring. This is the way to overwrite an already stored passwork
            on the keyring. Default is False.
        """

        # Developer notes:
        # Login via https://my.nrao.edu/cas/login
        # # this can be added to auto-redirect back to the query tool: ?service=https://archive.nrao.edu/archive/advquery.jsp

        if username is None:
            if not self.USERNAME:
                raise LoginError("If you do not pass a username to login(), "
                                 "you should configure a default one!")
            else:
                username = self.USERNAME

        # Check if already logged in
        loginpage = self._request("GET",
                                  "https://my.nrao.edu/cas/login",
                                  cache=False)
        root = BeautifulSoup(loginpage.content, 'html5lib')
        if root.find('div', class_='success'):
            log.info("Already logged in.")
            return True

        # Get password from keyring or prompt
        if reenter_password is False:
            password_from_keyring = keyring.get_password(
                "astroquery:my.nrao.edu", username)
        else:
            password_from_keyring = None

        if password_from_keyring is None:
            if system_tools.in_ipynb():
                log.warning("You may be using an ipython notebook:"
                            " the password form will appear in your terminal.")
            password = getpass.getpass("{0}, enter your NRAO archive password:"******"\n".format(username))
        else:
            password = password_from_keyring
        # Authenticate
        log.info("Authenticating {0} on my.nrao.edu ...".format(username))
        # Do not cache pieces of the login process
        data = {
            kw: root.find('input', {'name': kw})['value']
            for kw in ('lt', '_eventId', 'execution')
        }
        data['username'] = username
        data['password'] = password
        data['execution'] = 'e1s1'  # not sure if needed
        data['_eventId'] = 'submit'
        data['submit'] = 'LOGIN'

        login_response = self._request("POST",
                                       "https://my.nrao.edu/cas/login",
                                       data=data,
                                       cache=False)

        authenticated = ('You have successfully logged in'
                         in login_response.text)

        if authenticated:
            log.info("Authentication successful!")
            self.USERNAME = username
        else:
            log.exception("Authentication failed!")
        # When authenticated, save password in keyring if needed
        if authenticated and password_from_keyring is None and store_password:
            keyring.set_password("astroquery:my.nrao.edu", username, password)

        return authenticated
Example #55
0
def read_config(config_file: pathlib.Path) -> dict:
    if not config_file.exists():
        raise ConfigurationError("Configuration file %s does not exist." %
                                 config_file)

    config = configparser.ConfigParser()
    config.optionxform = str  # do not lowercase the aliases section!
    config.read(config_file)

    if not config.has_section('gtimelog2jira'):
        raise ConfigurationError(
            "Section [gtimelog2jira] is not present in %s config file." %
            config_file)

    url = config.get('gtimelog2jira', 'jira')
    username = config.get('gtimelog2jira', 'username')
    password = config.get('gtimelog2jira', 'password')
    timelog = config.get('gtimelog2jira', 'timelog')
    jiralog = config.get('gtimelog2jira', 'jiralog')
    projects = config.get('gtimelog2jira', 'projects')
    midnight = config.get('gtimelog', 'virtual_midnight', fallback='06:00')

    if not url:
        raise ConfigurationError(
            "Jira URL is not specified, set Jira URL via gtimelog2jira.jira setting."
        )

    if not username:
        raise ConfigurationError(
            "Jira username is not specified, set Jira username via gtimelog2jira.username setting."
        )

    if not projects:
        raise ConfigurationError(
            "List of projects is not specified, set Jira projects via gtimelog2jira.projects setting."
        )

    projects = set(projects.split())

    if config.has_section('gtimelog2jira:aliases'):
        aliases = dict(config.items('gtimelog2jira:aliases'))
    else:
        aliases = {}

    if not timelog:
        timelog = config_file.parent / 'timelog.txt'

    timelog = pathlib.Path(timelog).expanduser().resolve()
    if not timelog.exists():
        raise ConfigurationError("Timelog file %s does not exist." % timelog)

    jiralog = pathlib.Path(jiralog).expanduser().resolve()
    try:
        jiralog.open('a').close()
    except OSError as e:
        raise ConfigurationError("Jira log file %s is not writable: %s." %
                                 (jiralog, e))

    if not url.endswith('/'):
        url += '/'

    api = url + 'rest/api/2'

    session = requests.Session()

    if not password:
        try:
            password = keyring.get_password(url, username)
        except NoKeyringError as err:
            print("keyring:", err)

    attempts = range(3)
    for attempt in attempts:
        if attempt > 0 or not password:
            password = getpass.getpass('Enter Jira password for %s at %s: ' %
                                       (username, url))
            try:
                keyring.set_password(url, username, password)
            except NoKeyringError:
                print("Failed to save the password in the system keyring.")
            else:
                print("Saved the password in the system keyring.")
        session.auth = (username, password)
        resp = session.get('%s/myself' % api)
        if resp.ok:
            break
        elif resp.status_code == 401:
            try:
                keyring.delete_password(url, username)
            except NoKeyringError:
                pass
            else:
                print(
                    "Removed the saved incorrect password from the system keyring."
                )
            raise ConfigurationError("Error: Incorrect password or username.")
        elif resp.status_code == 403:
            raise ConfigurationError(
                "Jira credentials seems to be correct, but this user does "
                "not have permission to log in.\nTry to log in via browser, "
                "maybe you need to answer a security question: %s" % url)
        else:
            raise ConfigurationError(
                "Something went wrong, Jira gave %s status code." %
                resp.status_code)

    return {
        'url': url,
        'api': api,
        'credentials': (username, password),
        'self': resp.json(),
        'timelog': timelog,
        'jiralog': jiralog,
        'projects': projects,
        'aliases': aliases,
        'session': session,
        'midnight': midnight,
    }
Example #56
0
 def set_password(self, user: str, password: str) -> None:
     keyring.set_password(FIGGY_KEYRING_NAMESPACE, user, password)
Example #57
0
def set_password(*args):
    if not keyring is None:
        return keyring.set_password(*args)
    return False
Example #58
0
def read_config(args, appname=None, authfile=None):
    appname = appname or APPNAME
    authfile = authfile or AUTHFILE

    username = ""
    password = ""

    # read
    if keyring:
        log.debug("Reading credentials from keyring")
        try:
            username, password = (
                keyring.get_password(appname, appname).split('\n') +
                ['\n'])[:2]
        except AttributeError as e:
            # Check for old keyring format and migrate before throwing warning
            data = keyring.get_password(appname, '')
            if data:
                log.info("Migrating credentials to new keyring format")
                keyring.set_password(appname, appname, data)
                try:
                    keyring.delete_password(appname, '')
                except AttributeError as e:
                    log.warning(
                        "Error deleting old keyring. Outdated library? (%s)",
                        e)
            else:
                log.warning(
                    "Credentials not found in keyring. First time usage?")
        except IOError as e:  # keyring sometimes raises this
            log.error(e)
    else:
        log.debug("Reading credentials from '%s'" % authfile)
        try:
            with open(authfile, 'r') as fd:
                username, password = (fd.read().splitlines() + ['\n'])[:2]
        except IOError as e:
            if e.errno == 2:  # No such file or directory
                log.warning("Credentials file not found. First time usage?")
            else:
                log.error(e)

    # save
    if args.username or args.password:
        log.info("Saving credentials")
        if keyring:
            keyring.set_password(
                appname, appname, '%s\n%s' % (
                    args.username or username,
                    args.password or password,
                ))
        else:
            try:
                with open(authfile, 'w') as fd:
                    fd.write("%s\n%s\n" % (
                        args.username or username,
                        args.password or password,
                    ))
                os.chmod(authfile, 0o600)
            except IOError as e:
                log.error(e)

    return dict(
        username=username,
        password=password,
    )
Example #59
0
def encrypt_password(username, password):
    keyring.set_password(SERVICE_ID, username, password)
    return keyring.get_password()
Example #60
0
def main():

    with open(configfile, 'r') as f:
        jsonfile = json.load(f)

        #FIRST RUN
        if jsonfile["first_run"]:

            print('''

		   _____             __ _       
		  / ____|           / _(_)      
		 | |     ___  _ __ | |_ _  __ _ 
		 | |    / _ \| '_ \|  _| |/ _` |
		 | |___| (_) | | | | | | | (_| |
		  \_____\___/|_| |_|_| |_|\__, |
		                           __/ |
		  Developed by MemoriasIT |___/ 

				''')

            prompt = 'Would you like to be asked for credentials every run? '
            askEveryRun = validAnswer(prompt)

            #Requires Mac OS X Keychain/Freedesktop Secret Service (requires secretstorage)/KWallet (requires dbus)/Windows Credential Locker
            prompt = 'Would you like to use the KeyRing feature? (see requirements in readme)'
            useKeyring = validAnswer(prompt)

            if not askEveryRun:
                prompt = 'What is your email? '
                email = input(prompt)
                if useKeyring:
                    YourPW = getpass.getpass("Introduce password: "******"MyBBScraper", email, YourPW)
            else:
                email = ''

            prompt = 'Would you like to use the SMTP notification feature?'
            useSMTP = validAnswer(prompt)

            if useSMTP:
                SMTP = input('Introduce SMTP:Port ')
                fromaddr = input('From: ')
                toaddrs = input('To: ')
            else:
                SMTP = ''
                fromaddr = ''
                toaddrs = ''

            prompt = 'How often would you like to refresh the data? (s)'
            RefreshRate = input(prompt)

            first_run = False

            data = {
                'first_run': False,
                'askEveryRun': askEveryRun,
                'email': email,
                'RefreshRate': RefreshRate,
                'useKeyring': useKeyring,
                'useSMTP': useSMTP,
                'fromaddr': fromaddr,
                'toaddrs': toaddrs,
                'version': 'V2.3'
            }

            # Writing JSON data
            with open(configfile, 'w') as f:
                json.dump(data, f)

        if jsonfile["askEveryRun"] and not jsonfile["first_run"]:

            print("""
		  _      ____   _____ _____ _   _ 
		 | |    / __ \ / ____|_   _| \ | |
		 | |   | |  | | |  __  | | |  \| |
		 | |   | |  | | | |_ | | | | . ` |
		 | |___| |__| | |__| |_| |_| |\  |
		 |______\____/ \_____|_____|_| \_|
		  - %s Written by MemoriasIT -
		  				                  
		""" % (jsonfile["version"]))

            askEveryRun = jsonfile["askEveryRun"]
            RefreshRate = jsonfile["RefreshRate"]
            useKeyring = jsonfile["useKeyring"]
            useSMTP = jsonfile["useSMTP"]
            fromaddr = jsonfile["fromaddr"]
            toaddrs = jsonfile["toaddrs"]
            email = ''