Beispiel #1
0
    def __init__(self):

        if USE_APPLESCRIPT is False:

            if not mw.col.conf.get(SETTING_TOKEN, False):
                # First run of the Plugin we did not save the access key yet
                client = EvernoteClient(
                    consumer_key='scriptkiddi-2682',
                    consumer_secret='965f1873e4df583c',
                    sandbox=False
                )
                request_token = client.get_request_token('https://fap-studios.de/anknotes/index.html')
                url = client.get_authorize_url(request_token)
                showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
                openLink(url)
                oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
                auth_token = client.get_access_token(
                    request_token.get('oauth_token'),
                    request_token.get('oauth_token_secret'),
                    oauth_verifier)
                mw.col.conf[SETTING_TOKEN] = auth_token
            else:
                auth_token = mw.col.conf.get(SETTING_TOKEN, False)

            self.token = auth_token
            self.client = EvernoteClient(token=auth_token, sandbox=False)
            self.noteStore = self.client.get_note_store()
Beispiel #2
0
 def __init__(self):
     if not mw.col.conf.get(SETTING_TOKEN, False):
         # First run of the Plugin we did not save the access key yet
         client = EvernoteClient(
             consumer_key='scriptkiddi-2682',
             consumer_secret='965f1873e4df583c',
             sandbox=False
         )
         request_token = client.get_request_token('http://brunomart.in/anknotes/index.html')
         url = client.get_authorize_url(request_token)
         showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
         openLink(url)
         oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
         secret_key = getText(prompt="protect your value with a password, it will be asked each time you import your notes")[0]
         auth_token = client.get_access_token(
             request_token.get('oauth_token'),
             request_token.get('oauth_token_secret'),
             oauth_verifier)
         mw.col.conf[SETTING_TOKEN] = encode(secret_key, auth_token)
     else:
         secret_key = getText(prompt="password")[0]
         auth_token_encoded = mw.col.conf.get(SETTING_TOKEN, False)
         auth_token = decode(secret_key, auth_token_encoded)
     self.token = auth_token
     self.client = EvernoteClient(token=auth_token, sandbox=False)
     self.noteStore = self.client.get_note_store()
Beispiel #3
0
Datei: oauth.py Projekt: jodv/not
def setup():
    '''
    oauth flow for new users or updating users
    most of this was shamelessly copied from :
    https://gist.github.com/inkedmn/5041037
    '''
    client = EvernoteClient(
                consumer_key = config.CONSUMER_KEY,
                consumer_secret = config.CONSUMER_SECRET,
                sandbox = False
            )
    request_token = client.get_request_token('http://localhost:10668')
    print "Paste this URL in your browser and login:"******"Token saved."
Beispiel #4
0
def setup():
    """
    oauth flow for new users or updating users
    adapted from https://gist.github.com/inkedmn/5041037
    """
    client = EvernoteClient(
        consumer_key=CONSUMER_KEY,
        consumer_secret=CONSUMER_SECRET,
        sandbox=False
    )

    request_token = client.get_request_token('http://localhost:10668')
    print(
        "Paste this URL in your browser and login:"******"-> {url}  \n\n"
        "Be advised, this will save your oauth token in plaintext to ~/.not_token !"
        "if you aren't cool with that, ctrl-c now and never return!".format(
            url=client.get_authorize_url(request_token)
        )
    )
    single_server = single_serve()
    single_server.handle_request()
    auth_url = path  # noqa
    vals = parse_query_string(auth_url)
    auth_token = client.get_access_token(
        request_token['oauth_token'],
        request_token['oauth_token_secret'],
        vals['oauth_verifier']
    )
    with open(os.path.join(os.environ['HOME'], '.not_token'), 'w') as f:
        f.write(auth_token)
        print("Token saved.")
Beispiel #5
0
    def authorize(self, storage_name):
        '''Authorize/reauthorize the app if something is wrong
		with the token or storage.
		'''
        # Start oauth flow
        client = EvernoteClient(consumer_key=self.consumer_key,
                                consumer_secret=self.consumer_secret,
                                sandbox=False)

        request_token = client.get_request_token('http://localhost')
        #Prompt the user to open the request URL in their browser
        print "Paste this URL in your browser and login\n"
        print client.get_authorize_url(request_token) + '\n'
        # Have the user paste the resulting URL so we can pull it
        # apart
        print "Paste the URL after login here:"
        authurl = raw_input()
        ## Parse the URL to get the OAuth verifier
        vals = self.parse_query_string(authurl)
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        auth_token = client.get_access_token(
            request_token['oauth_token'], request_token['oauth_token_secret'],
            vals['oauth_verifier'])
        # We will need it for some methods
        self.token = auth_token
        # Write it to the storage file
        try:
            storage = open(storage_name, 'w')
            storage.write(auth_token)
        except ImportError, e:
            # Should never happen
            print 'Error while saving the auth token: ', e
            print 'Your auth token is: ', auth_token
Beispiel #6
0
def setup():
    """
    oauth flow for new users or updating users
    adapted from https://gist.github.com/inkedmn/5041037
    """
    client = EvernoteClient(consumer_key=CONSUMER_KEY,
                            consumer_secret=CONSUMER_SECRET,
                            sandbox=False)

    request_token = client.get_request_token('http://localhost:10668')
    print(
        "Paste this URL in your browser and login:"******"-> {url}  \n\n"
        "Be advised, this will save your oauth token in plaintext to ~/.not_token !"
        "if you aren't cool with that, ctrl-c now and never return!".format(
            url=client.get_authorize_url(request_token)))
    single_server = single_serve()
    single_server.handle_request()
    auth_url = path  # noqa
    vals = parse_query_string(auth_url)
    auth_token = client.get_access_token(request_token['oauth_token'],
                                         request_token['oauth_token_secret'],
                                         vals['oauth_verifier'])
    with open(os.path.join(os.environ['HOME'], '.not_token'), 'w') as f:
        f.write(auth_token)
        print("Token saved.")
def auth():
	"""Takes a callback for Evernote's OAuth process 

	Redirect to main after login is confirmed an token is stored in the session"""
	
	#check to make sure the user approved the appliction (oauth_verifier will not be present if they declined)
	if "oauth_verifier" in request.args:
		#setup client
		client = EvernoteClient(
		consumer_key=CONSUMER_KEY,
		consumer_secret=CONSUMER_SECRET,
		sandbox= sandbox
		)
		
		#get access token
		try:
			auth_token = client.get_access_token(session['oauth_token'], session['oauth_token_secret'], request.args['oauth_verifier'])
		except:
			return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)	
		
		#attach the user's access token to the session
		session["access_token"]=auth_token

		#redirect to main
		return redirect(url_for("main"))
	
	#If the user did not approve access to our application let the user know
	else:
		return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)
Beispiel #8
0
class OAuthView(QWebView):
    accessTokenChanged = Signal(str)
    def __init__(self, parent=None):
        QWebView.__init__(self)
        self.urlChanged.connect(self.pageChanged)
        conf = ConfigParser.SafeConfigParser()
        conf.read(CONFIG_FILE)
        consumer_key = conf.get('API', 'consumer_key')
        consumer_secret = conf.get('API', 'consumer_secret')
        self.client = EvernoteClient(
                consumer_key=consumer_key,
                consumer_secret=consumer_secret,
                sandbox=True)
        self.request_token = self.client.get_request_token('https://www.google.co.jp/')
        url = self.client.get_authorize_url(self.request_token)
        self.load(url)

    @Slot(QUrl)
    def pageChanged(self, url):
        queries = url.queryItems()
        if len(queries) == 2 and queries[1][0] == u'oauth_verifier':
            self.hide()
            self.access_token = self.client.get_access_token(
                    self.request_token['oauth_token'],
                    self.request_token['oauth_token_secret'],
                    queries[1][1]
                    )
            self.accessTokenChanged.emit(self.access_token)
Beispiel #9
0
    def on_navigation_requested(self, view, frame, req, data=None):
        logging.debug('Requesting new page')
        self.__spinner.show()
        self.__status_label.set_text(AuthDialog.STATUS_MESSAGE_CONNECTING)
        url = req.get_uri()
        if PROGRAM_NAME.lower() in url:
            query = urlparse.urlparse(url).query
            data = dict(urlparse.parse_qsl(query))
            
            try:
                self.__authData['oauth_verifier'] = data['oauth_verifier']
            except KeyError:
                logging.error('authorization failed')
                return False

            client = EvernoteClient(
                consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
                consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
                service_host = MetaData.get_evernote_host(),
                sandbox=False # Default: True
            )
            self.__auth_token = client.get_access_token(
                self.__authData['oauth_token'],
                self.__authData['oauth_token_secret'],
                self.__authData['oauth_verifier']
            )
            self.__dialog.response(100)
        return False
Beispiel #10
0
    def getAuthToken(self, c_key, c_secret):
        ##
        # Create an instance of EvernoteClient using your API
        # key (consumer key and consumer secret)
        ##
        client = EvernoteClient(
            consumer_key=c_key,
            consumer_secret=c_secret,
            sandbox=False # Default: True
        )

        ##
        # Provide the URL where the Evernote Cloud API should 
        # redirect the user after the request token has been
        # generated. In this example, localhost is used; note
        # that in this example, we're copying the URLs manually
        # and that, in production, this URL will need to 
        # automatically parse the response and send the user
        # to the next step in the flow.
        ##
        request_token = client.get_request_token('http://localhost')

        ##
        # Prompt the user to open the request URL in their browser
        ##
        print "Paste this URL in your browser and login"
        print
        print '\t'+client.get_authorize_url(request_token)
        print
        print '-------'

        ##
        # Have the user paste the resulting URL so we can pull it
        # apart
        ##
        print "Paste the URL after login here:"
        authurl = raw_input()

        ##
        # Parse the URL to get the OAuth verifier
        ##
        vals = parse_query_string(authurl)

        ##
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        ##
        auth_token = client.get_access_token(
                    request_token['oauth_token'],
                    request_token['oauth_token_secret'],
                    vals['oauth_verifier']
                )
        return auth_token        
Beispiel #11
0
def request_oauth_token(sandbox=False):
    client = EvernoteClient(consumer_key=MY_CONSUMER_KEY,
                            consumer_secret=MY_CONSUMER_SECRET,
                            sandbox=sandbox)
    resp_server = CLEVERNOTE_AUTH_WEB_SERVER
    # resp_server = 'http://localhost:8090/oauth'
    req_token = client.get_request_token(resp_server)
    webbrowser.open_new_tab(client.get_authorize_url(req_token))
    auth_string64 = str(raw_input("Auth String: "))
    auth_string = base64.b64decode(auth_string64)
    auth_dict = pickle.loads(auth_string)
    oauth_token = auth_dict['token']
    verifier = auth_dict['verifier']
    access_token = client.get_access_token(oauth_token, req_token['oauth_token_secret'], verifier)
    return access_token
Beispiel #12
0
def request_evernote_token():
    client = EvernoteClient(consumer_key=config.CONSUMER_KEY,
                            consumer_secret=config.CONSUMER_SECRET,
                            sandbox=config.SANDBOX)
    request_token = client.get_request_token(OAUTH_URL)
    print('Paste this URL in your browser and login')
    print(client.get_authorize_url(request_token))
    print('Paste the URL after login here:')
    auth_url = input()
    values = parse_query_string(auth_url)
    auth_token = client.get_access_token(request_token['oauth_token'],
                                         request_token['oauth_token_secret'],
                                         values['oauth_verifier'])
    print('Auth done')
    return auth_token
Beispiel #13
0
def _get_evernote_token(app_debug):
    
    client = EvernoteClient(
        consumer_key=CONSUMER_KEY,
        consumer_secret =CONSUMER_SECRET,
        sandbox=SANDBOX_ENABLE
    )    

    request_token = client.get_request_token("http://gevernote/")    

    if request_token['oauth_callback_confirmed']:
        url_callback = client.get_authorize_url(request_token)
        
        if app_debug:
            print ("URL:                 %s" % url_callback)
            print ("oauth_token:         %s" % request_token['oauth_token'])
            print ("oauth_token_secret:  %s" % request_token['oauth_token_secret'])
            
        window = AuthWindow(url_callback)
        window.show_all()
        Gtk.main()

        if app_debug:
            print ("oauth_verifier:      %s" % window.oauth_verifier)
                                
        if not (window.oauth_verifier == "None"):
        	   # get the token for authorization     
            user_token = client.get_access_token(
                request_token['oauth_token'],
                request_token['oauth_token_secret'],
                window.oauth_verifier
            )
        else:
            # handle window closed by cancel and no token            
            user_token = window.oauth_verifier	
        	        
        Gtk.main_quit
        
        if app_debug:
            print ("user_token:          %s" % user_token)
    
    elif app_debug:
        # need app error checking/message here        
        print("bad callback")    
    
    # Token available?
    return user_token
Beispiel #14
0
def request_oauth_token(sandbox=False):
    client = EvernoteClient(consumer_key=MY_CONSUMER_KEY,
                            consumer_secret=MY_CONSUMER_SECRET,
                            sandbox=sandbox)
    resp_server = CLEVERNOTE_AUTH_WEB_SERVER
    # resp_server = 'http://localhost:8090/oauth'
    req_token = client.get_request_token(resp_server)
    webbrowser.open_new_tab(client.get_authorize_url(req_token))
    auth_string64 = str(raw_input("Auth String: "))
    auth_string = base64.b64decode(auth_string64)
    auth_dict = pickle.loads(auth_string)
    oauth_token = auth_dict['token']
    verifier = auth_dict['verifier']
    access_token = client.get_access_token(oauth_token,
                                           req_token['oauth_token_secret'],
                                           verifier)
    return access_token
Beispiel #15
0
def auth():
	if "oauth_verifier" in request.args:
		client = EvernoteClient(
		consumer_key=CONSUMER_KEY,
		consumer_secret=CONSUMER_SECRET,
		sandbox= True
		)
		
		try:
			auth_token = client.get_access_token(session['oauth_token'], session['oauth_token_secret'], request.args['oauth_verifier'])
		except:
			return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)	
		
		session["access_token"]=auth_token
		return redirect(url_for("main"))
	else:
		return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)
Beispiel #16
0
def auth_finish():
    """After the user has authorized this app on Evernote's website,
    they will be redirected back to this URL to finish the process."""

    oauth_verifier = request.args.get('oauth_verifier', '')

    oauth_token = session['oauth_token']
    oauth_token_secret = session['oauth_token_secret']

    client = EvernoteClient(consumer_key=EN_CONSUMER_KEY, consumer_secret=EN_CONSUMER_SECRET,sandbox=False)

    authToken = client.get_access_token(oauth_token, oauth_token_secret, oauth_verifier)

    # session['identifier'] = authToken
    resp = make_response(redirect(url_for('get')))
    resp.set_cookie('token', authToken)

    return resp
Beispiel #17
0
def get_client():
    token = get_token()
    if not token:
        print 'Username:\t',
        username = raw_input()
        print 'Password:\t',
        password = raw_input()
        print '\n'
        client = EvernoteClient(consumer_key='freddieshoreditch-8876',
                                consumer_secret='13801fb7745664f3',
                                sandbox=False)

        req_token = client.get_request_token('http://localhost/')
        os_ = get_os()
        url_ = client.get_authorize_url(req_token)
        if (os_ == 'Mac OS X'):
            command = 'open {}'.format(url_)
        elif (os == 'Windows'):
            print 'Unimplemented for Windows.'
            sys.exit(3)
        elif (os == 'Linux or other'):
            print 'Unimplemented for Linux or other.'
            sys.exit(3)
        else:
            print 'Unimplemented for your operating system.'
            sys.exit(3)
        tries = 0
        exit_code = -1
        while (exit_code != 0 and tries < 5):
            tries += 1
            exit_code = subprocess.call(command, shell=True)
        if exit_code != 0:
            print 'Could not open authorisation url, please open it manually:',
            print url_

        print '\n\nPASTE the URL after logging in:\t'
        result = raw_input()
        vals = parse_query_string(result)
        token = client.get_access_token(req_token['oauth_token'],
                                        req_token['oauth_token_secret'],
                                        vals['oauth_verifier'])
        with open('token.json', 'w') as f:
            f.write(json.dumps(token))
    return EvernoteClient(token=token), token
def get_client():
    token = get_token()
    if not token:
        print "Username:\t",
        username = raw_input()
        print "Password:\t",
        password = raw_input()
        print "\n"
        client = EvernoteClient(
            consumer_key="freddieshoreditch-8876", consumer_secret="13801fb7745664f3", sandbox=False
        )

        req_token = client.get_request_token("http://localhost/")
        os_ = get_os()
        url_ = client.get_authorize_url(req_token)
        if os_ == "Mac OS X":
            command = "open {}".format(url_)
        elif os == "Windows":
            print "Unimplemented for Windows."
            sys.exit(3)
        elif os == "Linux or other":
            print "Unimplemented for Linux or other."
            sys.exit(3)
        else:
            print "Unimplemented for your operating system."
            sys.exit(3)
        tries = 0
        exit_code = -1
        while exit_code != 0 and tries < 5:
            tries += 1
            exit_code = subprocess.call(command, shell=True)
        if exit_code != 0:
            print "Could not open authorisation url, please open it manually:",
            print url_

        print "\n\nPASTE the URL after logging in:\t"
        result = raw_input()
        vals = parse_query_string(result)
        token = client.get_access_token(
            req_token["oauth_token"], req_token["oauth_token_secret"], vals["oauth_verifier"]
        )
        with open("token.json", "w") as f:
            f.write(json.dumps(token))
    return EvernoteClient(token=token), token
Beispiel #19
0
    def get_client_oauth(self):
        client = EvernoteClient(consumer_key = self.customer_key, 
                                consumer_secret = self.customer_secret,
                                sandbox = self.is_sandbox)

        request_token = client.get_request_token(self.url)
        print request_token

        request_url = client.get_authorize_url(request_token)

        print request_url
        auth_url = raw_input()
        vals = parse_query_string(auth_url)

        auth_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            vals['oauth_verifier'])
        return client
Beispiel #20
0
def auth_evernote():
    #import evernote.edam.userstore.constants as UserStoreConstants
    #import evernote.edam.type.ttypes as Types
    from evernote.api.client import EvernoteClient
    client = EvernoteClient(
        consumer_key = 'baschtik-3522',
        consumer_secret = '9851242b79ad58cd',
        sandbox = True, 
    )
    request_token = client.get_request_token('http://always-backup.com/external_auth/evernote/')

    try:
        text = '''\
        1) Go to: \n%s 
        1a) Make sure that you have the complete URL (Scroll to te right).
        2) Click "Allow" (you might have to log in first)
        3) You will get a Code. Copy it to the Clip-board 
        ''' % client.get_authorize_url(request_token)
    except:
        d.msgbox("Sorry, Evernote reportet an error. "
                 "I quit the setup and show you the Response from Evernote.")
        print request_token
        raise

    d.scrollbox( text, height=15, width=0)
    code, verifier = d.inputbox( "Now enter the code here:", width=150 )
    if code != 0:
        sync_pairs()

    try:
        auth_token = client.get_access_token(
                    request_token['oauth_token'],
                    request_token['oauth_token_secret'],
                    verifier
                )
    except:
        d.msgbox("There was an error gernerating the access token\n"
                 "The profile will be saved, continue and edit it later."
                 "Otherwise sync will not work""", height=10, width=50)
        auth_token = False
    return auth_token
Beispiel #21
0
def oauth():
    client = EvernoteClient(consumer_key=conf.key, consumer_secret=conf.sec, sandbox=conf.env)
    token = client.get_request_token(conf.url)
    url = client.get_authorize_url(token)
    c = requests.session()
    c.get(url)

    print "==> Please Sign in. Never store your PASSWORD!"
    cnt = 3
    while cnt:
        cnt -= 1
        payload = {"login": "******", "targetUrl": url}
        if hasattr(conf, "username"):
            payload["username"] = conf.username
        else:
            payload["username"] = raw_input("Username: "******"password"):
            payload["password"] = conf.password
        else:
            payload["password"] = getpass().strip()
        resp = c.post(url, data=payload)
        if resp.history:
            break
        else:
            if not cnt:
                print "Incorrect Username or Passowrd!"
                sys.exit(1)
            else:
                print "Sorry, incorrect Username or Password."
    print "<== Signed in."

    payload = {"authorize": "Authorize", "embed": "false"}
    payload["oauth_token"] = token["oauth_token"]
    payload["oauth_callback"] = conf.url
    resp = c.post(url, data=payload, allow_redirects=False)
    return client.get_access_token(
        token["oauth_token"],
        token["oauth_token_secret"],
        resp.headers["location"].split("?")[1].split("&")[1].split("=")[1],
    )
Beispiel #22
0
def get_auth_token():
    """
    Run through the Evernote OAuth procedure

    :returns: User token string
    """
    # Create an HTTP server on a spare port
    httpd = MininoteHTTPServer(('127.0.0.1', 0), MininoteHTTPRequestHandler)
    callbackurl = urljoin("http://{}:{}".format(*httpd.server_address),
                          RETURN_PATH)

    client = EvernoteClient(consumer_key=EVERNOTE_CONSUMER_KEY,
                            consumer_secret=EVERNOTE_CONSUMER_SECRET,
                            sandbox=DEVELOPMENT_MODE)

    request_token = client.get_request_token(callbackurl)

    authorize_url = client.get_authorize_url(request_token)
    print 'Please login at the following url:\n{}'.format(authorize_url)

    # Open browser to auth page
    SilentWebbrowser(authorize_url).start()

    # Wait until browser is redirected
    httpd.server_activate()
    while httpd.auth_path is None:
        httpd.handle_request()
    httpd.server_close()

    def parse_query_string(authorize_url):
        query_params = urlparse(authorize_url).query
        return dict(kv.split('=') for kv in query_params.split('&'))

    vals = parse_query_string(httpd.auth_path)
    if 'oauth_verifier' not in vals:
        raise OAuthError('There was an error logging in.  Please try again.')
    return client.get_access_token(request_token['oauth_token'],
                                   request_token['oauth_token_secret'],
                                   vals['oauth_verifier'])
def auth():
    """Takes a callback for Evernote's OAuth process

    Redirect to main after auth token is retrived/stored in session"""

    # Check to make sure the user approved the appliction
    # (oauth_verifier will not be present if they declined)
    if "oauth_verifier" in request.args:
        # Setup client
        client = EvernoteClient(
            consumer_key=CONSUMER_KEY,
            consumer_secret=CONSUMER_SECRET,
            sandbox=sandbox
        )

        # Get access token
        try:
            auth_token = client.get_access_token(
                session['oauth_token'], session['oauth_token_secret'],
                request.args['oauth_verifier']
            )
        except:
            # Display anerror message to the user if unable to
            # authorize Evernote account access
            error_message = "OAuth Error with application '%s'" % CONSUMER_KEY
            return render_template("error.html", error_message=error_message)

        # Attach the user's access token to the session
        session["access_token"] = auth_token

        # Redirect to main
        return redirect(url_for("main"))

    # Display an error to the user when the user doesn't grant access
    # of the application to access their Evernote account
    else:
        error_message = "OAuth Error:\
        Please approve access to the appliction %s" % CONSUMER_KEY
        return render_template("error.html", error_message=error_message)
Beispiel #24
0
def evernote_auth(client_id, client_secret, storage, sandbox=False):
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    host = 'localhost'
    port = 9343
    client = EvernoteClient(
      consumer_key=client_id,
      consumer_secret=client_secret,
      sandbox=sandbox
    )
    request_token = client.get_request_token('http://{}:{}/'.format(host, port))
    authorize_url = client.get_authorize_url(request_token)
    print 'Go to the following link in your browser:'
    print
    print '    ' + authorize_url
    print
    http = tools.ClientRedirectServer((host, port), tools.ClientRedirectHandler)
    http.handle_request()
    if 'oauth_verifier' not in http.query_params:
      print "Bad Evernote Oauth, no verifier:{}".format(http.query_params)
      return

    access_token = client.get_access_token(
      request_token['oauth_token'],
      request_token['oauth_token_secret'],
      http.query_params['oauth_verifier']
    )
    token_uri = 'https://{}evernote.com/oauth'.format('sandbox.' if sandbox else '')
    credentials = OAuth2Credentials(
      access_token,
      client_id,
      client_secret,
      refresh_token=request_token['oauth_token'], # not really
      token_expiry=datetime.now() - timedelta(days=-365),
      token_uri=token_uri,
      user_agent='evernote.basic'
    )
    storage.put(credentials)
  return credentials
Beispiel #25
0
def get_auth_token():
    """
    Run through the Evernote OAuth procedure

    :returns: User token string
    """
    # Create an HTTP server on a spare port
    httpd = MininoteHTTPServer(('127.0.0.1', 0), MininoteHTTPRequestHandler)
    callbackurl = urljoin("http://{}:{}".format(*httpd.server_address), RETURN_PATH)

    client = EvernoteClient(consumer_key=EVERNOTE_CONSUMER_KEY,
                            consumer_secret=EVERNOTE_CONSUMER_SECRET,
                            sandbox=DEVELOPMENT_MODE)

    request_token = client.get_request_token(callbackurl)

    authorize_url = client.get_authorize_url(request_token)
    print 'Please login at the following url:\n{}'.format(authorize_url)

    # Open browser to auth page
    SilentWebbrowser(authorize_url).start()

    # Wait until browser is redirected
    httpd.server_activate()
    while httpd.auth_path is None:
        httpd.handle_request()
    httpd.server_close()

    def parse_query_string(authorize_url):
        query_params = urlparse(authorize_url).query
        return dict(kv.split('=') for kv in query_params.split('&'))

    vals = parse_query_string(httpd.auth_path)
    if 'oauth_verifier' not in vals:
        raise OAuthError('There was an error logging in.  Please try again.')
    return client.get_access_token(request_token['oauth_token'],
                                   request_token['oauth_token_secret'],
                                   vals['oauth_verifier'])
print "Paste the URL after login here:"
authurl = raw_input()

##
# Parse the URL to get the OAuth verifier
##
vals = parse_query_string(authurl)

##
# Use the OAuth verifier and the values from request_token
# to built the request for our authentication token, then
# ask for it.
##
auth_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            vals['oauth_verifier']
        )

print("token is:" + auth_token)
		
##
# Create a new EvernoteClient instance with our auth
# token.
##
client = EvernoteClient(token=auth_token,sandbox=SANDBOX)

##
# Test the auth token...
##
userStore = client.get_user_store()
Beispiel #27
0
 def get_access_token(self, api_key, api_secret, oauth_token, oauth_token_secret, oauth_verifier):
     sdk = EvernoteSdk(consumer_key=api_key, consumer_secret=api_secret, sandbox=self.sandbox)
     return sdk.get_access_token(oauth_token, oauth_token_secret, oauth_verifier)
    def authenticate(
            self):
        """
        *authenticate*

        **Key Arguments:**
            # -

        **Return:**
            - None

        .. todo::

            - @review: when complete, clean authenticate method
            - @review: when complete add logging
        """
        self.log.info('starting the ``authenticate`` method')

        # Python OAuth example

        import evernote.edam.userstore.constants as UserStoreConstants
        import evernote.edam.type.ttypes as Types

        ##
        # Helper function to turn query string parameters into a
        # Python dictionary
        ##
        def parse_query_string(authorize_url):
            uargs = authorize_url.split('?')
            vals = {}
            if len(uargs) == 1:
                raise Exception('Invalid Authorization URL')
            for pair in uargs[1].split('&'):
                key, value = pair.split('=', 1)
                vals[key] = value
            return vals

        ##
        # Create an instance of EvernoteClient using your API
        # key (consumer key and consumer secret)
        ##
        client = EvernoteClient(
            consumer_key=self.settings["evernote"]["consumer_key"],
            consumer_secret=self.settings["evernote"]["consumer_secret"],
            sandbox=False
        )

        ##
        # Provide the URL where the Evernote Cloud API should
        # redirect the user after the request token has been
        # generated. In this example, localhost is used; note
        # that in this example, we're copying the URLs manually
        # and that, in production, this URL will need to
        # automatically parse the response and send the user
        # to the next step in the flow.
        ##
        request_token = client.get_request_token('http://localhost')
        print request_token

        ##
        # Prompt the user to open the request URL in their browser
        ##
        print "Paste this URL in your browser and login"
        print
        print '\t' + client.get_authorize_url(request_token)
        print
        print '-------'

        ##
        # Have the user paste the resulting URL so we can pull it
        # apart
        ##
        print "Paste the URL after login here:"
        authurl = raw_input()

        ##
        # Parse the URL to get the OAuth verifier
        ##
        vals = parse_query_string(authurl)

        ##
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        ##

        print request_token['oauth_token']
        print request_token['oauth_token_secret']
        print vals['oauth_verifier']

        auth_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            vals['oauth_verifier']
        )

        print auth_token

        ##
        # Create a new EvernoteClient instance with our auth
        # token.
        ##
        client = EvernoteClient(
            token=auth_token,
            sandbox=False
        )

        ##
        # Test the auth token...
        ##
        userStore = client.get_user_store()
        user = userStore.getUser()

        ##
        # If our username prints, it worked.
        ##
        print "Authorised under " + user.username
        print "Please add these to the evernote section in your settings file ..."
        print "auth_token: " + auth_token

        self.log.info('completed the ``authenticate`` method')
        return None
    print "Please complete the following steps to continue: "
    print "1. Go to: %s" % auth_url
    print "2. Grant access to your application"
    print "3. Inspect at the URL you are directed to"
    print "4. Find the code in between '&oauth_verifier=' and '&sandbox_lnb'"
    print "5. Enter that code (the OAuth verifier) below: "
    verifier = raw_input("OAuth verifier: ")

    auth_token = None

    # Get access token
    while not auth_token:
        try:
            auth_token = client.get_access_token(
                temp_token,
                temp_secret,
                verifier
            )
        except:
            print "Incorrect OAuth verifier."
            print "Try again or press control+Z to exit."
            verifier = raw_input("OAuthVerifier: ")

user_store = client.get_user_store()

version_ok = user_store.checkVersion(
    "Evernote EDAMTest (Python)",
    UserStoreConstants.EDAM_VERSION_MAJOR,
    UserStoreConstants.EDAM_VERSION_MINOR
)
print "Is my Evernote API version up to date? ", str(version_ok)
Beispiel #30
0
def get_access_token(api_key, api_secret, sandbox=False, **oauth_kwargs):
    sdk = EvernoteSdk(consumer_key=api_key,
                      consumer_secret=api_secret,
                      sandbox=sandbox)
    return sdk.get_access_token(oauth_kwargs["token"], oauth_kwargs["secret"],
                                oauth_kwargs["verifier"])