def test_constructor_explicit(self):
        dictionary = {}
        key = 'test-key'
        storage = DictionaryStorage(dictionary, key)

        lock = object()
        storage = DictionaryStorage(dictionary, key, lock=lock)
        self.assertEqual(storage._lock, lock)
    def test_put(self):
        credentials = _generate_credentials()
        dictionary = {}
        key = 'credentials'
        storage = DictionaryStorage(dictionary, key)

        storage.put(credentials)
        returned = storage.get()

        self.assertIn(key, dictionary)
        self.assertIsNotNone(returned)
        self.assertEqual(returned.access_token, credentials.access_token)
        self.assertEqual(returned.id_token, credentials.id_token)
        self.assertEqual(returned.refresh_token, credentials.refresh_token)
        self.assertEqual(returned.client_id, credentials.client_id)
    def test_put(self):
        credentials = _generate_credentials()
        dictionary = {}
        key = 'credentials'
        storage = DictionaryStorage(dictionary, key)

        storage.put(credentials)
        returned = storage.get()

        self.assertIn(key, dictionary)
        self.assertIsNotNone(returned)
        self.assertEqual(returned.access_token, credentials.access_token)
        self.assertEqual(returned.id_token, credentials.id_token)
        self.assertEqual(returned.refresh_token, credentials.refresh_token)
        self.assertEqual(returned.client_id, credentials.client_id)
Example #4
0
def get_storage(request):
    # TODO(issue 319): Make this pluggable with different storage providers
    # https://github.com/google/oauth2client/issues/319
    """ Gets a Credentials storage object for the Django OAuth2 Helper object
    :param request: Reference to the current request object
    :return: A OAuth2Client Storage implementation based on sessions
    """
    return DictionaryStorage(request.session, key=_CREDENTIALS_KEY)
    def test_constructor_defaults(self):
        dictionary = {}
        key = 'test-key'
        storage = DictionaryStorage(dictionary, key)

        self.assertEqual(dictionary, storage._dictionary)
        self.assertEqual(key, storage._key)
        self.assertIsNone(storage._lock)
def main():
    if sys.version_info.major < 3:
        print('Python 3+ required')
        return

    tools.argparser.add_argument('year',
                                 type=int,
                                 help='The year of the first event')
    tools.argparser.add_argument('month',
                                 type=int,
                                 help='The month of the first event')
    tools.argparser.add_argument('day',
                                 type=int,
                                 help='The day of the first event')
    flags = tools.argparser.parse_args()

    eventDay = datetime.date(flags.year, flags.month, flags.day)
    userResponse = input('Is date {} correct? y/n: '.format(
        eventDay.strftime('%A, %B %d, %Y')))
    if userResponse.lower() != 'y':
        return

    storage_dict = {}
    store = DictionaryStorage(storage_dict, u'credentials')
    flow = client.OAuth2WebServerFlow(
        client_id=
        '570017343303-nf4f1vaclctc8d0c7ma4rahm5v49rnbm.apps.googleusercontent.com',
        client_secret='BDhRKaNZh4iRRfr2V95y3y2O',
        scope='https://www.googleapis.com/auth/calendar',
        auth_uri='https://accounts.google.com/o/oauth2/auth',
        token_uri='https://www.googleapis.com/oauth2/v3/token')
    creds = tools.run_flow(flow, store)
    service = build('calendar', 'v3', http=creds.authorize(Http()))

    oneDay = datetime.timedelta(days=1)
    for week in range(1, 5):
        for day in range(1, 8):
            event = {
                'summary': 'W{}D{}'.format(week, day),
                'transparency': 'transparent',
                'start': {
                    'date': str(eventDay),
                },
                'end': {
                    'date': str(eventDay),
                },
            }
            eventDay += oneDay
            event = service.events().insert(calendarId='primary',
                                            body=event).execute()

    print('')
    print('Events created')
    def test_delete(self):
        credentials = _generate_credentials()
        dictionary = {}
        key = 'credentials'
        storage = DictionaryStorage(dictionary, key)

        storage.put(credentials)

        self.assertIn(key, dictionary)

        storage.delete()

        self.assertNotIn(key, dictionary)
        self.assertIsNone(storage.get())
Example #8
0
    def init_app(self,
                 app,
                 scopes=None,
                 client_secrets_file=None,
                 client_id=None,
                 client_secret=None,
                 authorize_callback=None,
                 storage=None,
                 **kwargs):
        """Initialize this extension for the given app.

        Arguments:
            app: A Flask application.
            scopes: Optional list of scopes to authorize.
            client_secrets_file: Path to a file containing client secrets. You
                can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_JSON config
                value.
            client_id: If not specifying a client secrets file, specify the
                OAuth2 client id. You can also specify the
                GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a
                client secret.
            client_secret: The OAuth2 client secret. You can also specify the
                GOOGLE_OAUTH2_CLIENT_SECRET config value.
            authorize_callback: A function that is executed after successful
                user authorization.
            storage: A oauth2client.client.Storage subclass for storing the
                credentials. By default, this is a Flask session based storage.
            kwargs: Any additional args are passed along to the Flow
                constructor.
        """
        self.app = app
        self.authorize_callback = authorize_callback
        self.flow_kwargs = kwargs

        if storage is None:
            storage = DictionaryStorage(session, key=_CREDENTIALS_KEY)
        self.storage = storage

        if scopes is None:
            scopes = app.config.get('GOOGLE_OAUTH2_SCOPES', _DEFAULT_SCOPES)
        self.scopes = scopes

        self._load_config(client_secrets_file, client_id, client_secret)

        app.register_blueprint(self._create_blueprint())
    def test_delete(self):
        credentials = _generate_credentials()
        dictionary = {}
        key = 'credentials'
        storage = DictionaryStorage(dictionary, key)

        storage.put(credentials)

        self.assertIn(key, dictionary)

        storage.delete()

        self.assertNotIn(key, dictionary)
        self.assertIsNone(storage.get())
Example #10
0
 def __init__(self):
     self.storage_dict = {}
     self.storage = DictionaryStorage(self.storage_dict, "creds")
Example #11
0
class GoogleAuthentication(object):

    def __init__(self):
        self.storage_dict = {}
        self.storage = DictionaryStorage(self.storage_dict, "creds")

    def credentials_supplied(self):
        return CREDENTIALS_ENV_VAR in os.environ

    def get_credentials(self):
        """Get credentials from environment.

        Returns None if no credentials were supplied or the supplied
        credentials were invalid.

        Otherwise returns an oauth2client Credentials object.
        """
        serialised_creds = os.environ.get(CREDENTIALS_ENV_VAR)
        if serialised_creds:
            self.storage_dict["creds"] = zlib.decompress(base64.decodestring(serialised_creds))
        creds = self.storage.get()

        if creds is None or creds.invalid:
            return None
        return creds

    def initial_auth(self):
        """Run the authorisation flow with Google to make some credentials.

        This should only need to be run once, and requires that a client
        secrets file has been downloaded.
        """
        if CLIENT_SECRET_FILE_ENV_VAR not in os.environ:
            print("""
You need to download a client secret file, and set the
{} environment variable to point to it.

To generate a client secret file, you will need a google project, which is
authorised to use the appropriate APIs, and to generate an OAuth client ID for
it, of application type "other".  You can use
https://console.developers.google.com/ to create such a project. 
""".format(CLIENT_SECRET_FILE_ENV_VAR))
            return
        client_secrets_file = os.environ[CLIENT_SECRET_FILE_ENV_VAR]
        flow = client.flow_from_clientsecrets(client_secrets_file, [
            CALENDAR_SCOPE,
        ])
        creds = tools.run_flow(flow, self.storage, None)
        return not(creds is None or creds.invalid)

    def display_credentials(self):
        print("""
Persistent credentials have been generated.  These allow access to the google
account without further authorisation.  Keep them secure, and revoke them in
the google dashboard when they're no longer needed or if there is a risk that
they may have leaked.

Please now delete the supplied client secrets file.
""")

        print("{}='{}'".format(CREDENTIALS_ENV_VAR,
            base64.encodestring(zlib.compress(self.storage_dict["creds"],
                9)).replace("\n", ""),
        ))