Declare an authentication token that was generated outside of the IPython Notebook using the instructions found in the Setting Up Authentication Credentials section of the Python API Installation and Access page of the Earth Engine API documentation.
In [ ]:
import ee
import errno
import json
import os
import urllib
import urllib2
from IPython.display import HTML
from IPython.display import display
from ee.oauthinfo import OAuthInfo
# This URI prompts user to copy and paste a code after successful
# authorization.
ee_redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
def create_auth_url():
# TODO(user): Add an additional, non-commandline flow for iPython notebook
# for added convenience, and to work in notebook environments where
# commandline isn't available.
# This implements the flow from:
# https://developers.google.com/accounts/docs/OAuth2ForDevices
### Request authorization from user
auth_request_params = {
'scope': OAuthInfo.SCOPE,
'redirect_uri': ee_redirect_uri,
'response_type': 'code',
'client_id': OAuthInfo.CLIENT_ID
}
auth_request_url = ('https://accounts.google.com/o/oauth2/auth?' +
urllib.urlencode(auth_request_params))
return auth_request_url
def ee_authenticate(auth_code):
token_request_params = {
'code': auth_code,
'client_id': OAuthInfo.CLIENT_ID,
'client_secret': OAuthInfo.CLIENT_SECRET,
'redirect_uri': ee_redirect_uri,
'grant_type': 'authorization_code'
}
refresh_token = None
try:
response = urllib2.urlopen('https://accounts.google.com/o/oauth2/token',
urllib.urlencode(token_request_params)).read()
tokens = json.loads(response)
refresh_token = tokens['refresh_token']
except urllib2.HTTPError, e:
raise Exception('Problem requesting tokens. Please try again. %s %s' %
(e, e.read()))
### Write refresh token to filesystem for later use
credentials_path = OAuthInfo.credentials_path()
dirname = os.path.dirname(credentials_path)
try:
os.makedirs(dirname)
except OSError, e:
if e.errno != errno.EEXIST:
raise Exception('Error creating %s: %s' % (dirname, e))
json.dump({'refresh_token': refresh_token}, open(credentials_path, 'w'))
print '\nSuccessfully saved authorization to %s' % credentials_path
ee.Initialize()
return True
def auth_html():
return HTML(
("""You need to authorize access to your Earth Engine account.<br>
Please follow <a href="%s" target="_blank">this link</a>, """ % create_auth_url()) +
"""and paste the token you receive after authorization here:
<input id="ee_auth_token" type="password"></input>
<button id = "ee_authenticate">Submit</button> <span id="ee_auth_result"></span>
<script>
// Send auth token to python
function ee_authenticate(token, callback) {
cmd = 'ee_authenticate(' + JSON.stringify(token) + ')'
console.log(cmd);
function cb(msg) {
console.log(msg);
console.log(msg.content.data['text/plain'] == 'True');
callback(msg.content.data['text/plain'] == 'True')
}
IPython.notebook.kernel.execute(cmd,
{iopub: {output: cb}}, {silent: false});
}
$('#ee_authenticate').click(function() {
$('#ee_auth_result').text('...');
console.log('debug 1');
ee_authenticate($('#ee_auth_token').val(),
function(success) {
console.log('debug 2');
$('#ee_auth_result').text(success ? 'Success' : 'Failed');
});
});
</script>
""")
# For now, call ee_initialize() instead of ee.Initialize()
def ee_initialize():
try:
ee.Initialize()
display(HTML("""Authentication successful!"""))
except ee.EEException, e:
display(auth_html())
In [ ]: