示例#1
0
def get_credentials(code):
    if code:
        params = get_oauth_keys('gcal')
        params.update({
            "scope": 'https://www.googleapis.com/auth/calendar',
            "redirect_uri": get_redirect_uri('calendar'),
            "params": {
                "approval_prompt": "force",
                'access_type': 'offline',
                "response_type": "code"
            }
        })
        flow = OAuth2WebServerFlow(**params)
        credentials = flow.step2_exchange(code)
        # Store Credentials in Keyring Storage
        store = Storage('Google Account', frappe.session.user)
        store.put(credentials)

        frappe.get_doc({
            "doctype": "Google Account",
            "name": frappe.session.user,
            "authenticated": 1
        }).save(ignore_permissions=True)

        frappe.local.response["type"] = "redirect"
        frappe.local.response[
            "location"] = "/desk#Form/Google Account/%s", frappe.sesion.user
示例#2
0
def get_drive_service():
    """Authenticate to the Google Drive API and return a service object."""
    # See https://developers.google.com/api-client-library/python/guide/aaa_oauth#oauth2client
    import oauth2client
    from oauth2client.client import flow_from_clientsecrets
    from oauth2client.keyring_storage import Storage as CredentialStorage
    from oauth2client.tools import run
    from apiclient.discovery import build as build_service

    # For keyring credential storage
    APP_NAME = 'gdutil'
    USER_NAME = os.environ['USER'] or 'default_user'

    CLIENT_SECRETS_FILE = 'client_secrets.json'

    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
    
    storage = CredentialStorage(APP_NAME, USER_NAME)
    credentials = storage.get()

    if credentials is None:
        try:
            # See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
            flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, OAUTH_SCOPE)
        except oauth2client.clientsecrets.InvalidClientSecretsError, e:
            print "error: couldn't read client secrets: ", e
            exit(1)

        # See https://developers.google.com/api-client-library/python/guide/aaa_oauth#oauth2client
        credentials = run(flow, storage)
示例#3
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 get_credentials(code):
	if code:
		params = get_oauth_keys('gcal')
		params.update({
			"scope": 'https://www.googleapis.com/auth/calendar',
			"redirect_uri": get_redirect_uri('calendar'),
			"params": {
				"approval_prompt":"force",
				'access_type': 'offline',
				"response_type": "code"
			}
		})
		flow = OAuth2WebServerFlow(**params)
		credentials = flow.step2_exchange(code)
		# Store Credentials in Keyring Storage
		store = Storage('Google Account', frappe.session.user)
		store.put(credentials)
		
		frappe.get_doc({
			"doctype": "Google Account",
			"name": frappe.session.user,
			"authenticated": 1
		}).save(ignore_permissions=True)
		
		frappe.local.response["type"] = "redirect"
		frappe.local.response["location"] = "/desk#Form/Google Account/%s", frappe.sesion.user
示例#5
0
    def _youtube(cls, authenticate=False):
        while True:
            try:
                if not authenticate:
                    return build(cls.YOUTUBE_API_SERVICE_NAME, cls.YOUTUBE_API_VERSION, developerKey=cls.DEVELOPER_KEY)

                storage = Storage('mpris-youtube', os.getlogin())
                credentials = storage.get()

                if credentials is None:
                    flow = OAuth2WebServerFlow(
                            client_id=cls.CLIENT_ID,
                            client_secret=cls.CLIENT_SECRET,
                            scope=cls.AUTH_SCOPE
                            #redirect_uri='urn:ietf:wg:oauth:2.0:oob'
                            )
                    credentials = run(flow, storage)

                http = httplib2.Http()
                credentials.authorize(http)
                return build(
                        cls.YOUTUBE_API_SERVICE_NAME,
                        cls.YOUTUBE_API_VERSION,
                        http=http)

            except Exception as e:
                print e
                time.sleep(3)
示例#6
0
def generate_token():
    # check storage for credentials
    store = Storage('Google Account', frappe.session.user)
    # store = Storage('GCal', "*****@*****.**")
    credentials = store.get()
    if not credentials or credentials.invalid:
        url = get_oauth2_authorize_url('calendar')
        return {"url": url, "is_synced": False}
示例#7
0
 def test_non_existent_credentials_storage(self):
   with mock.patch.object(keyring, 'get_password',
                          return_value=None,
                          autospec=True) as get_password:
     s = Storage('my_unit_test', 'me')
     credentials = s.get()
     self.assertEquals(None, credentials)
     get_password.assert_called_once_with('my_unit_test', 'me')
 def test_get_with_malformed_json_credentials_stored(self):
     with mock.patch.object(keyring, 'get_password',
                            return_value='{',
                            autospec=True) as get_password:
         store = Storage('my_unit_test', 'me')
         credentials = store.get()
         self.assertEquals(None, credentials)
         get_password.assert_called_once_with('my_unit_test', 'me')
 def test_get_with_malformed_json_credentials_stored(self):
     with mock.patch.object(keyring, 'get_password',
                            return_value='{',
                            autospec=True) as get_password:
         store = Storage('my_unit_test', 'me')
         credentials = store.get()
         self.assertEquals(None, credentials)
         get_password.assert_called_once_with('my_unit_test', 'me')
示例#10
0
    def _get_credentials(self):
        storage = Storage("ftw.recipe.translations", os.getlogin())
        credentials = storage.get()

        if credentials:
            credentials.refresh(httplib2.Http())
            return credentials

        return self._authorize(storage)
 def test_locked_delete(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     store = Storage(service_name, user_name)
     with mock.patch.object(keyring, 'set_password',
                            return_value=None,
                            autospec=True) as set_password:
         store.locked_delete()
         set_password.assert_called_once_with(service_name, user_name, '')
示例#12
0
    def _get_credentials(self):
        storage = Storage('ftw.recipe.translations', os.getlogin())
        credentials = storage.get()

        if credentials:
            credentials.refresh(httplib2.Http())
            return credentials

        return self._authorize(storage)
 def test_locked_delete(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     store = Storage(service_name, user_name)
     with mock.patch.object(keyring, 'set_password',
                            return_value=None,
                            autospec=True) as set_password:
         store.locked_delete()
         set_password.assert_called_once_with(service_name, user_name, '')
示例#14
0
文件: auth.py 项目: coquelicot/GBD
    def get_credentials(self):

        storage = Storage(self.appname, os.getlogin())

        credentials = storage.get()
        if not credentials or credentials.invalid:
            credentials = self.request_credentials()
            storage.put(credentials)

        return credentials
示例#15
0
文件: auth.py 项目: marcogrossi/GBD
    def get_credentials(self):

        storage = Storage(self.appname, os.getlogin())

        credentials = storage.get()
        if not credentials or credentials.invalid:
            credentials = self.request_credentials()
            storage.put(credentials)

        return credentials
示例#16
0
文件: tasks.py 项目: spiderninja/GCAL
def sych_users_calender(users):
	for user in users:
		# get user credentials from keyring storage
		store = Storage('GCal', user[0])
		credentials = store.get()
		if not credentials or credentials.invalid:
			# invalid credentials
			print "invalid credentials", user[0]
		else:
			sync_google_calendar(credentials)
def generate_token():
	# check storage for credentials
	store = Storage('Google Account', frappe.session.user)
	# store = Storage('GCal', "*****@*****.**")
	credentials = store.get()
	if not credentials or credentials.invalid:
		url = get_oauth2_authorize_url('calendar')
		return {
			"url":url,
			"is_synced": False
		}
示例#18
0
def get_service_object():
	# get google credentials from storage
	service = None
	store = Storage('GCal', frappe.session.user)
	credentials = store.get()
	if not credentials or credentials.invalid:
		# get credentials
		frappe.throw("Invalid Credentials")
	else:
		service = build('calendar', 'v3', http=credentials.authorize(Http()))

	return service
示例#19
0
def get_service_object():
    # get google credentials from storage
    service = None
    store = Storage('GCal', frappe.session.user)
    credentials = store.get()
    if not credentials or credentials.invalid:
        # get credentials
        frappe.throw("Invalid Credentials")
    else:
        service = build('calendar', 'v3', http=credentials.authorize(Http()))

    return service
示例#20
0
  def test_malformed_credentials_in_storage(self):
    m = mox.Mox()
    m.StubOutWithMock(keyring, 'get_password')
    m.StubOutWithMock(keyring, 'set_password')
    keyring.get_password('my_unit_test', 'me').AndReturn('{')
    m.ReplayAll()

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

    m.UnsetStubs()
    m.VerifyAll()
    def test_malformed_credentials_in_storage(self):
        m = mox.Mox()
        m.StubOutWithMock(keyring, 'get_password')
        m.StubOutWithMock(keyring, 'set_password')
        keyring.get_password('my_unit_test', 'me').AndReturn('{')
        m.ReplayAll()

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

        m.UnsetStubs()
        m.VerifyAll()
示例#22
0
def sync_calender():
    # check storage for credentials
    store = Storage('GCal', frappe.session.user)
    # store = Storage('GCal', "makarand")
    credentials = store.get()

    if not credentials or credentials.invalid:
        url = get_oauth2_authorize_url('gcal')
        return {"url": url, "is_synced": False}
    else:
        from gcal.tasks import sync_google_calendar
        sync_google_calendar(credentials)
        return {"url": None, "is_synced": True}
示例#23
0
def build_service(config):
    storage = Storage("kitakubu-" + config["client_id"], getpass.getuser())
    credentials = storage.get()
    if config["reauth"] or credentials is None or credentials.invalid:
        flow = OAuth2WebServerFlow(
            config["client_id"],
            config["client_secret"],
            OAUTH_SCOPES,
        )
        gflags.FLAGS([sys.argv[0]])
        credentials = run_oauth(flow, storage)

    http = httplib2.Http()
    http = credentials.authorize(http)
    return build_apiclient("drive", "v2", http=http)
 def test_locked_put(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     store = Storage(service_name, user_name)
     with mock.patch.object(keyring, 'set_password',
                            return_value=None,
                            autospec=True) as set_password:
         credentials = mock.MagicMock()
         to_json_ret = object()
         credentials.to_json = to_json = mock.MagicMock(
             name='to_json', return_value=to_json_ret)
         store.locked_put(credentials)
         to_json.assert_called_once_with()
         set_password.assert_called_once_with(service_name, user_name,
                                              to_json_ret)
 def test_locked_put(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     store = Storage(service_name, user_name)
     with mock.patch.object(keyring, 'set_password',
                            return_value=None,
                            autospec=True) as set_password:
         credentials = mock.MagicMock()
         to_json_ret = object()
         credentials.to_json = to_json = mock.MagicMock(
             name='to_json', return_value=to_json_ret)
         store.locked_put(credentials)
         to_json.assert_called_once_with()
         set_password.assert_called_once_with(service_name, user_name,
                                              to_json_ret)
 def test_constructor(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     store = Storage(service_name, user_name)
     self.assertEqual(store._service_name, service_name)
     self.assertEqual(store._user_name, user_name)
     lock_type = type(threading.Lock())
     self.assertTrue(isinstance(store._lock, lock_type))
示例#27
0
def get_service(secrets, scope, service_name, service_version,
                keyring_storename):
    """
    return a service for google
    """
    flow = flow_from_clientsecrets(secrets,
                                   scope=scope,
                                   redirect_uri='http://localhost:8080')
    store = Storage(keyring_storename, getpass.getuser())
    # Check if we already have credentials
    credentials = store.get()
    if not credentials or credentials.invalid:
        # if not, spawn a browser to get credentials
        credentials = run(flow, store)
    # finally create a service object:
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build(service_name, service_version, http=http)
    return service
示例#28
0
def sync_calender():
	# check storage for credentials
	store = Storage('GCal', frappe.session.user)
	# store = Storage('GCal', "makarand")
	credentials = store.get()

	if not credentials or credentials.invalid:
		url = get_oauth2_authorize_url('gcal')
		return {
			"url":url,
			"is_synced": False
		}
	else:
		from gcal.tasks import sync_google_calendar
		sync_google_calendar(credentials)
		return {
			"url":None,
			"is_synced": True
		}
 def test_locked_get(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     mock_content = (object(), 'mock_content')
     mock_return_creds = mock.MagicMock()
     mock_return_creds.set_store = set_store = mock.MagicMock(
         name='set_store')
     with mock.patch.object(keyring, 'get_password',
                            return_value=mock_content,
                            autospec=True) as get_password:
         with mock.patch(
                 'oauth2client.keyring_storage.Credentials') as MockCreds:
             MockCreds.new_from_json = new_from_json = mock.MagicMock(
                 name='new_from_json', return_value=mock_return_creds)
             store = Storage(service_name, user_name)
             credentials = store.locked_get()
             new_from_json.assert_called_once_with(mock_content)
             get_password.assert_called_once_with(service_name, user_name)
             self.assertEqual(credentials, mock_return_creds)
             set_store.assert_called_once_with(store)
 def test_locked_get(self):
     service_name = 'my_unit_test'
     user_name = 'me'
     mock_content = (object(), 'mock_content')
     mock_return_creds = mock.MagicMock()
     mock_return_creds.set_store = set_store = mock.MagicMock(
         name='set_store')
     with mock.patch.object(keyring, 'get_password',
                            return_value=mock_content,
                            autospec=True) as get_password:
         with mock.patch(
                 'oauth2client.keyring_storage.Credentials') as MockCreds:
             MockCreds.new_from_json = new_from_json = mock.MagicMock(
                 name='new_from_json', return_value=mock_return_creds)
             store = Storage(service_name, user_name)
             credentials = store.locked_get()
             new_from_json.assert_called_once_with(mock_content)
             get_password.assert_called_once_with(service_name, user_name)
             self.assertEqual(credentials, mock_return_creds)
             set_store.assert_called_once_with(store)
    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()
        token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
        user_agent = 'refresh_checker/1.0'

        credentials = OAuth2Credentials(access_token, client_id, client_secret,
                                        refresh_token, token_expiry, 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 test_get_and_set_with_json_credentials_stored(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)

        # Setting autospec on a mock with an iterable side_effect is
        # currently broken (http://bugs.python.org/issue17826), so instead
        # we patch twice.
        with mock.patch.object(keyring, 'get_password',
                               return_value=None,
                               autospec=True) as get_password:
            with mock.patch.object(keyring, 'set_password',
                                   return_value=None,
                                   autospec=True) as set_password:
                store = Storage('my_unit_test', 'me')
                self.assertEquals(None, store.get())

                store.put(credentials)

                set_password.assert_called_once_with(
                    'my_unit_test', 'me', credentials.to_json())
                get_password.assert_called_once_with('my_unit_test', 'me')

        with mock.patch.object(keyring, 'get_password',
                               return_value=credentials.to_json(),
                               autospec=True) as get_password:
            restored = store.get()
            self.assertEqual('foo', restored.access_token)
            self.assertEqual('some_client_id', restored.client_id)
            get_password.assert_called_once_with('my_unit_test', 'me')
示例#33
0
def get_credentials(code):
	if code:
		params = get_oauth_keys('gcal')
		params.update({
			"scope": 'https://www.googleapis.com/auth/calendar',
			"redirect_uri": get_redirect_uri('gcal'),
			"params": {
				"approval_prompt":"force",
				'access_type': 'offline',
				"response_type": "code"
			}
		})
		flow = OAuth2WebServerFlow(**params)
		credentials = flow.step2_exchange(code)
		# Store Credentials in Keyring Storage
		store = Storage('GCal', frappe.session.user)
		store.put(credentials)
		# get events and create new doctype
		from gcal.tasks import sync_google_calendar
		sync_google_calendar(credentials)

	frappe.local.response["type"] = "redirect"
	frappe.local.response["location"] = "/desk#Calendar/Event"
示例#34
0
def get_credentials(code):
    if code:
        params = get_oauth_keys('gcal')
        params.update({
            "scope": 'https://www.googleapis.com/auth/calendar',
            "redirect_uri": get_redirect_uri('gcal'),
            "params": {
                "approval_prompt": "force",
                'access_type': 'offline',
                "response_type": "code"
            }
        })
        flow = OAuth2WebServerFlow(**params)
        credentials = flow.step2_exchange(code)
        # Store Credentials in Keyring Storage
        store = Storage('GCal', frappe.session.user)
        store.put(credentials)
        # get events and create new doctype
        from gcal.tasks import sync_google_calendar
        sync_google_calendar(credentials)

    frappe.local.response["type"] = "redirect"
    frappe.local.response["location"] = "/desk#Calendar/Event"
示例#35
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)

        # Setting autospec on a mock with an iterable side_effect is
        # currently broken (http://bugs.python.org/issue17826), so instead
        # we patch twice.
        with mock.patch.object(keyring,
                               'get_password',
                               return_value=None,
                               autospec=True) as get_password:
            with mock.patch.object(keyring,
                                   'set_password',
                                   return_value=None,
                                   autospec=True) as set_password:
                s = Storage('my_unit_test', 'me')
                self.assertEquals(None, s.get())

                s.put(credentials)

                set_password.assert_called_once_with('my_unit_test', 'me',
                                                     credentials.to_json())
                get_password.assert_called_once_with('my_unit_test', 'me')

        with mock.patch.object(keyring,
                               'get_password',
                               return_value=credentials.to_json(),
                               autospec=True) as get_password:
            restored = s.get()
            self.assertEqual('foo', restored.access_token)
            self.assertEqual('some_client_id', restored.client_id)
            get_password.assert_called_once_with('my_unit_test', 'me')
示例#36
0
 def get_storage(self):
     return Storage(
         "cactus/gcs", self.engine.bucket_name
     )  #TODO: Not a great key, but do we want to ask for email?
#! /usr/bin/env python
import logging
from oauth2client.keyring_storage import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from httplib2 import Http
import json
from cmislib.model import CmisClient
import os, pwd

uid = pwd.getpwuid(os.getuid())[0]
storage = Storage("Jeff's Sample Python App", uid)
http = Http(
    disable_ssl_certificate_validation=True)  # Should not have to do this!
flow = flow_from_clientsecrets('client_secrets.json',
                               scope='public_api',
                               redirect_uri='http://localhost:8080/')

credentials = storage.get()
if credentials == None:
    credentials = run(flow, storage, http=http)
    storage.put(credentials)

print "Your access_token is: %s" % credentials.access_token

http = credentials.authorize(http)

headers = {'Authorization': 'Bearer ' + credentials.access_token}

client = CmisClient('https://api.alfresco.com/cmis/versions/1.0/atom',
                    '',
示例#38
0
def get_credentials(user):
	store = Storage('Google Account', user)
	credentials = store.get()
	
	return credentials
 def test_release_lock(self):
     store = Storage('my_unit_test', 'me')
     store._lock = lock = _FakeLock()
     self.assertEqual(lock._release_count, 0)
     store.release_lock()
     self.assertEqual(lock._release_count, 1)
示例#40
0
def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)

  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))

  # If the Credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # Credentials will get written back to a file.
  storage = Storage('Google_Plus_Sample', getpass.getuser())
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run(FLOW, storage)

  # Create an httplib2.Http object to handle our HTTP requests and authorize it
  # with our good Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("plus", "v1", http=http)

  try:
    person = service.people().get(userId='me').execute(http)
 def test_release_lock(self):
     store = Storage('my_unit_test', 'me')
     store._lock = lock = _FakeLock()
     self.assertEqual(lock._release_count, 0)
     store.release_lock()
     self.assertEqual(lock._release_count, 1)
示例#42
0
def get_credentials(user):
    store = Storage('Google Account', user)
    credentials = store.get()

    return credentials