Exemplo n.º 1
0
def set_get_user_pass(service):
	
	# store username and password in keychain if not found
	if not service in [x[0] for x in keychain.get_services()]:
		print 'Keychain does not contain %s username and password.' % service
		username = raw_input('Enter your %s username and press enter:' % service)
		password = raw_input('Enter your %s password and press enter:' % service)
		print 'Username %s and password saved for %s.' % (username, service)
		keychain.set_password(service, username, password)
		
	else:
		# get the username---can be multiple accounts for one service
		usernamelist = [x[1] for x in keychain.get_services() if x[0]==service]
		
		if len(usernamelist) > 1:
			print 'Multiple usernames were found for %s.' % service
			for uname in enumerate(usernamelist):
				print '     [%d]: %s'%(uname[0]+1, uname[1])
			unum = int(raw_input('Enter the number of the correct one:').strip()) - 1
			username = usernamelist[unum]
		else:
			username = usernamelist[0]
			
		# get the password based on correct username
		password = keychain.get_password(service, username)
	
	return username, password
Exemplo n.º 2
0
def git_push(args):
    parser = argparse.ArgumentParser(prog='git push'
                                     , usage='git push [http(s)://<remote repo> or remote] [-u username[:password]]'
                                     , description="Push to a remote repository")
    parser.add_argument('url', type=str, nargs='?', help='URL to push to')
    parser.add_argument('-u', metavar='username[:password]', type=str, required=False, help='username[:password]')
    result = parser.parse_args(args)

    user, sep, pw = result.u.partition(':') if result.u else (None,None,None)

    repo = _get_repo()

    origin='origin'
    if not result.url:
        result.url = repo.remotes.get('origin','')
    if result.url in repo.remotes:
        origin=result.url
        result.url=repo.remotes.get(origin)

    branch_name = os.path.join('refs','heads', repo.active_branch)  #'refs/heads/%s' % repo.active_branch

    print "Attempting to push to: {0}, branch: {1}".format(result.url, branch_name)

    netloc = urlparse.urlparse(result.url).netloc

    keychainservice = 'stash.git.{0}'.format(netloc)

    if sep and not user:
        # -u : clears keychain for this server
        for service in keychain.get_services():
            if service[0]==keychainservice:
                keychain.delete_password(*service)

    #Attempt to retrieve user
    if not user and SAVE_PASSWORDS and result.url.startswith('http'):
        try:
            user = dict(keychain.get_services())[keychainservice]
        except KeyError:
            user = raw_input('Enter username: ')
            pw = raw_input('Enter password: ')
            #user, pw = console.login_alert('Enter credentials for {0}'.format(netloc))

    if user:
        if not pw and SAVE_PASSWORDS:
            pw = keychain.get_password(keychainservice, user)

        #Check again, did we retrieve a password?
        if not pw:
            user, pw = console.login_alert('Enter credentials for {0}'.format(netloc), login=user)
            #pw = getpass.getpass('Enter password for {0}: '.format(user))
        host_with_auth='{}:{}@{}'.format(user,pw,netloc)
        url=urlparse.urlunparse(
            urlparse.urlparse(result.url)._replace(
                netloc=host_with_auth))
        porcelain.push(repo.repo.path, url, branch_name)
        keychain.set_password(keychainservice, user, pw)

    else:
        porcelain.push(repo.repo.path, result.url, branch_name)
    print 'success!'
Exemplo n.º 3
0
def get_token():
	token = keychain.get_password('gistcheck','gistcheck')
	if token is None:
		u, p = console.login_alert('GitHub Login')
		token = auth(u, p)['token']
		keychain.set_password('gistcheck','gistcheck',token)
	return token
Exemplo n.º 4
0
	def _get_key(self):
		''' Retrieve the working copy key or prompt for a new one.
		'''
		key = keychain.get_password('wcSync', 'xcallback')
		if not key:
			key = console.password_alert('Working Copy Key')
			keychain.set_password('wcSync', 'xcallback', key)
		return key
Exemplo n.º 5
0
def getGithubPassword(username):
	service = 'github'
	password = keychain.get_password(service, username)
	if password == None:
		print "Enter password for user", username
		password = console.secure_input()
		keychain.set_password(service, username, password)
	return password
Exemplo n.º 6
0
 def _get_key(self):
   ''' Retrieve the working copy key or prompt for a new one. See https://github.com/ahenry91/wc_sync
   '''
 
   key = keychain.get_password('wcSync', 'xcallback')
   if not key:
     key = console.password_alert('Working Copy Key')
     keychain.set_password('wcSync', 'xcallback', key)
   return key  
Exemplo n.º 7
0
def save_dropbox_data(username, access_token):
	"""saves dropbox access information for username."""
	data = {
		"api_version": 2,
		"access_token": access_token,
	}
	dumped = pickle.dumps(data)
	encoded = base64.b64encode(dumped)
	keychain.set_password(DB_SERVICE, username, encoded)
Exemplo n.º 8
0
def WC_callback_key(overwrite_key=False):
    service = "Working Copy"
    # UUID appended to avoid collision with another script
    # (generated on original dev machine)
    account = "x_callback_url_6653ee08-4c43-4453-a400-c5de315b0725"
    key = keychain.get_password(service, account)
    if overwrite_key or not key:
        key = console.input_alert("Enter Working Copy URL key:")
        keychain.set_password(service, account, key)
    return key
Exemplo n.º 9
0
 def push_callback(user,pw):
     print  "Attempting to push to: {0}, branch: {1}".format(remote, branch_name)
     console.show_activity()
     if user:
         opener = auth_urllib2_opener(None, remote, user, pw)
         porcelain.push(repo.path, remote, branch_name, opener=opener)
         keychain.set_password(keychainservice, user, pw)
     else:
         porcelain.push(repo.repo, result.url, branch_name)
     console.hide_activity()
     console.hud_alert('push complete')
Exemplo n.º 10
0
def get_access_token():
	token_str = keychain.get_password('dropbox', app_key)
	if token_str:
		key, secret = pickle.loads(token_str)
		return session.OAuthToken(key, secret)
	request_token = get_request_token()
	sess = session.DropboxSession(app_key, app_secret, access_type)
	access_token = sess.obtain_access_token(request_token)
	token_str = pickle.dumps((access_token.key, access_token.secret))
	keychain.set_password('dropbox', app_key, token_str)
	return access_token
Exemplo n.º 11
0
def save_dropbox_data(key, sec, access_type, access_token):
	"""saves dropbox access information."""
	data = {
		"app_key": key,
		"app_sec": sec,
		"access_type": access_type,
		"access_token_key": access_token.key,
		"access_token_sec": access_token.secret
	}
	dumped = pickle.dumps(data)
	encoded = base64.b64encode(dumped)
	keychain.set_password("stash:mc", "dropbox", encoded)
Exemplo n.º 12
0
    def git_push(args):
        parser = argparse.ArgumentParser(prog='git push'
                                         , usage='git push [http(s)://<remote repo>] [-u username[:password]]'
                                         , description="Push to a remote repository")
        parser.add_argument('url', type=str, nargs='?', help='URL to push to')
        parser.add_argument('-u', metavar='username[:password]', type=str, required=False, help='username[:password]')
        result = parser.parse_args(args)

        user, sep, pw = result.u.partition(':') if result.u else (None,None,None)

        repo = _get_repo()
        
        #Try to get the remote origin
        if not result.url:
            result.url = repo.remotes.get('origin','')

        branch_name = os.path.join('refs','heads', repo.active_branch)  #'refs/heads/%s' % repo.active_branch

        print "Attempting to push to: {0}, branch: {1}".format(result.url, branch_name)

        netloc = urlparse.urlparse(result.url).netloc

        keychainservice = 'shellista.git.{0}'.format(netloc)

        if sep and not user:
            # -u : clears keychain for this server
            for service in keychain.get_services():
                if service[0]==keychainservice:
                    keychain.delete_password(*service)

        #Attempt to retrieve user
        if not user and SAVE_PASSWORDS:
            try:
                user = dict(keychain.get_services())[keychainservice]
            except KeyError:
                user, pw = console.login_alert('Enter credentials for {0}'.format(netloc))

        if user:
            if not pw and SAVE_PASSWORDS:
                pw = keychain.get_password(keychainservice, user)

            #Check again, did we retrieve a password?
            if not pw:
                user, pw = console.login_alert('Enter credentials for {0}'.format(netloc), login=user)
                #pw = getpass.getpass('Enter password for {0}: '.format(user))

            opener = auth_urllib2_opener(None, result.url, user, pw)

            porcelain.push(repo.repo, result.url, branch_name, opener=opener)
            keychain.set_password(keychainservice, user, pw)

        else:
            porcelain.push(repo.repo, result.url, branch_name)
Exemplo n.º 13
0
def get_access_token():
	token_str = keychain.get_password('dropbox', app_key)
	if token_str:
		key, secret = token_str.split(',')
		return session.OAuthToken(key, secret)
	request_token = get_request_token()
	sess = session.DropboxSession(app_key, app_secret, access_type)
	access_token = sess.obtain_access_token(request_token)
	key = access_token.key.decode('ascii')
	secret = access_token.secret.decode('ascii')
	token_str = key + ',' + secret
	keychain.set_password('dropbox', app_key, token_str)
	return session.OAuthToken(key, secret)
Exemplo n.º 14
0
def save_handler(sender):
	addr_file = open(os.path.join(cur_dir, 'ftp_addr.txt'), 'w')
	name_file = open(os.path.join(cur_dir, 'ftp_name.txt'), 'w')
	dir_file = open(os.path.join(cur_dir, 'ftp_dir.txt'), 'w')
	root_dir_file = open(os.path.join(cur_dir, 'ftp_rootdir.txt'), 'w')
	addr_file.write(root['addr'].text)
	name_file.write(root['name'].text)
	dir_file.write(root['dir'].text)
	root_dir_file.write(os.path.abspath(root['rootdir'].text))
	addr_file.close()
	name_file.close()
	dir_file.close()
	root_dir_file.close()
	keychain.set_password('ftpsync', root['name'].text, root['pswd'].text)
Exemplo n.º 15
0
def commit():
	gist = get_gist_id(editor.get_path())
	if gist is not None:
		token = keychain.get_password('gistcheck','gistcheck')
		if token is None:
			u, p = console.login_alert('GitHub Login')
			r = json.loads(auth(u, p))
			print r
			token = r['token']
			keychain.set_password('gistcheck','gistcheck',token)
		fname = os.path.basename(editor.get_path())
		m = console.input_alert('Edit Description','Enter a new description:','')
		if m == '': m = None
		return edit(gist,{fname:editor.get_text()},token,m)
Exemplo n.º 16
0
 def connect(self):
     self.api = onedrive.OneDriveAPI(
         client_id=self.app_key, client_secret=self.app_secret)
     token_str = keychain.get_password('onedrive', self.app_key)
     if token_str:
         at, ac, ar = pickle.loads(token_str)
         self.api.auth_access_token = at
         self.api.auth_refresh_token = ar
         self.auth_code = ac
         self.api.auth_get_token()
     else:
         request_token = self._get_request_token()
         self.api.auth_user_process_url(request_token)
         self.api.auth_get_token()
         keychain.set_password('onedrive', self.app_key, pickle.dumps((
             self.api.auth_access_token,
             self.api.auth_code,
             self.api.auth_refresh_token
         )))
Exemplo n.º 17
0
def get_password_from_keychain(service, account, message=None):
  ''' Retrieve the working copy key or prompt for a new one. See https://github.com/ahenry91/wc_sync
  '''
  
  if not message:
    message = "Enter password for account '%s' of service '%s'" % (account, service)
  key = keychain.get_password(service, account)
  if not key:
    try:
      key = console.password_alert(message)
    except KeyboardInterrupt as k:
      key = None
    
    if key:
      keychain.set_password(service, account, key)
    else:
      keychain.delete_password(service, account)
  return key  
  
Exemplo n.º 18
0
import requests
import json
import base64

SITE_BRANCH = 'master' # either master or gh-pages
COMMITTER = {'name': 'Joe Bloggs', 'email': '[email protected]'}

#keychain.delete_password('GitHub', 'username')    # Uncomment these lines
#keychain.delete_password('GitHub', 'token')       # to change the details
#keychain.delete_password('GitHub', 'repository')  # stored in the keychain

# Get Username, API Token and Repository
username = keychain.get_password('GitHub', 'username')
if not username:
	username = console.input_alert("Username", "Enter your GitHub Username", '', "Save")
	keychain.set_password('GitHub', 'username', username)
	
tokn = keychain.get_password('GitHub', 'token')
if not tokn:
	tokn = console.password_alert("API Token", "Enter your GitHub API Token", '', "Save")
	keychain.set_password('GitHub', 'token', tokn)

repo = keychain.get_password('GitHub', 'repository')
if not repo:
	repo = console.input_alert("Repository", "Enter your GitHub Repository name", '', "Save")
	keychain.set_password('GitHub', 'repository', repo)

# Mangle the post ;)
post_text = editor.get_text()

post_sections = post_text.split('---')
Exemplo n.º 19
0
	def save_settings(self):
		settings_str = str(self.settings) # convert dict -> str
		settings_str = keychain.set_password('Braille','settings',settings_str)		
Exemplo n.º 20
0
def set_password(args):
  p = console.password_alert("Tradervue Credentials", args['user'])
  keychain.set_password(KEYCHAIN_ID, args['user'], p)
  return True
Exemplo n.º 21
0
 def __setitem__(self, key, value):
   keychain.set_password(DB_NAME, key, value)
Exemplo n.º 22
0
import keychain
import console

get_or_set = console.alert('Get or set?','','Get','Set')

if get_or_set == 1:
	 service = console.input_alert('Service to get?')
	 user = console.input_alert('What user?')
	 mypass = keychain.get_password(service, user)
	 if mypass == None:
	 	console.alert('Couldn\'t find that one.')
	 else:
	 	copy_here = console.alert('Print, clipboard, or console?','','Print','Clipboard','Console')
	 	if copy_here == 1:
	 		console.clear()
	 		print(mypass)
	 	elif copy_here == 2:
	 		import clipboard
	 		clipboard.set(mypass)
	 	elif copy_here == 3:
	 		console.alert(mypass)
	 		
elif get_or_set == 2:
	service = console.input_alert('Service name to store')
	user = console.input_alert('Username to store')
	mypass = console.input_alert('Password to store')
	keychain.set_password(service, user, mypass)
	console.alert('All done.')
Exemplo n.º 23
0
def checkKey():
	global key
	key = keychain.get_password('wcSync','xcallback')
	if key == None:
		pwd = console.password_alert('Working Copy Key')
		keychain.set_password('wcSync','xcallback',pwd)
Exemplo n.º 24
0
import pickle
import cgi
import sys




# Uncomment this line to reset stored password
# keychain.delete_password('vaughanje', 'editorial')
login = keychain.get_password('vaughanje', 'editorial')
if login is not None:
	user, pw = pickle.loads(login)
else:
	user, pw = console.login_alert('FTPS Login Needed', 'No login credentials found.')
	pickle_token = pickle.dumps((user, pw))
	keychain.set_password('vaughanje', 'editorial', pickle_token)


# 

remotePath = "/public_html/blog/source/"
host = "crawlab.org"
port = 21


docTitle = console.input_alert("Filename", "Enter File Name")
fileName = docTitle+'.md'
confirmation = console.alert('Confirm', 'Go ahead and post?','Yes','No')

postContent = sys.argv[1]#editor.get_text()
import console, keychain
device = raw_input('Enter device hostname or IP: ')
username = raw_input('Enter username: ')
password = console.secure_input('Enter password: ')

keychain.set_password(device, username, password)

print 'Account saved to keychain.'
Exemplo n.º 26
0
def main():
    if not appex.is_running_extension():
        print 'Running in Pythonista app, using test data...\n'
        text = '''
'''
    else:
        text = appex.get_text()
    if text:
        author          = 'Taha Dhiaeddine Amdouni'

        github_repo     = 'tdamdouni.github.io'
        github_user     = 'tdamdouni'
        github_password = keychain.get_password('github', github_user) or ''

        (title, text)   = extract_title(text)
        filename        = '%s-%s.md' % (date.today(), slug(title))

        github_fields = (
            'Github Settings',
            [
                dict(title='Github Username', key='github_user', type='text', value=github_user, autocorrection=False, autocapitalization=False),
                dict(title='Github Password', key='github_password', type='password', value=github_password),
                dict(title='Repository', key='github_repo', type='text', value=github_repo, autocorrection=False, autocapitalization=False)
            ]
        )

        posting_fields = (
            'Post Settings',
            [
                dict(title='Title', key='title', type='text', value=title),
                dict(title='Author', key='author', type='text', value=author),
                dict(title='Layout', key='layout', type='text', value='post', autocorrection=False, autocapitalization=False),
                dict(title='Tags', key='tags', type='text', value=''),
                dict(title='Filename', key='filename', type='text', value=filename, autocorrection=False, autocapitalization=False)
            ],
            'Please seperate tags by spaces.'
        )

        results = dialogs.form_dialog(title='Publish new post', sections=[
            posting_fields,
            github_fields
        ])

        if results is None:
            console.hud_alert('Posting was cancelled', 'error')
            return

        metas = {
            'tags': results['tags'],
            'branch': 'master',
            'author': results['author'],
            'layout': results['layout'],
            'filename': results['filename']
        }

        if github_password != results['github_password']:
            keychain.set_password('github', results['github_user'], results['github_password'])

        console.show_activity()
        mb = MobileBlogger(results['github_user'], results['github_password'], results['github_repo'])
        mb.create_new_post(results['title'], text, metas)
        console.hud_alert('New post created!')
    else:
        print 'No input text found.'
Exemplo n.º 27
0
email, password = console.login_alert('LastPass login', '', email, password)
device = keychain.get_password('lastpass_uuid', 'lastpass')

try:
	blob = lastpass.Vault.fetch_blob(email, password, None, device)
except lastpass.LastPassIncorrectGoogleAuthenticatorCodeError as e:
	googleauth = None
	if not device:
		console.hud_alert(message='You will now be redirected to Google Authenticator',duration=1)
		webbrowser.open('otpauth:')
		console.hud_alert(message='Enter the 2FA code',duration=5.0)
		googleauth = console.input_alert('GoogleAuth', '', clipboard.get())
		trusted = console.alert('Trusted', 'Save this device as trusted?', 'Save', 'Don\'t Save', hide_cancel_button=True)
		if not trusted:
			device = str(uuid.uuid1())
			keychain.set_password('lastpass_uuid', 'lastpass', device)
	blob = lastpass.Vault.fetch_blob(email, password, googleauth, device)

save_vault = console.alert("Save to keychain", "Would you like to save your vault to the keychain?", "Don't Save", "Save", hide_cancel_button=True)
if not save_vault:
	save_blob = console.alert("Save blob local", "Would you like to save the encrypted blob locally?", "Don't Save", "Save", hide_cancel_button=True)
	if save_blob:
		import pickle, os
		print "Saving blob to .lastpass.blob"
		FILENAME = os.path.join(os.getcwd(),'.lastpass.blob')
		pickle.dump(blob, open(FILENAME,'wb'))
		console.hud_alert('Saved blob')
else:
	try:
		# don't want both the blob and the keychain - avoids conflicts
		import os