Git Product home page Git Product logo

identity-toolkit-python-client's Introduction

This is the python client library for Google Identity Toolkit services.

Build Status

Installation

pip install identity-toolkit-python-client

If you run into issues installing, you may be missing some dependencies such as libffi or python-dev. On Debian, you can install these with:

sudo apt-get install python-dev libffi-dev

(replace python-dev with python3-dev if using Python 3)

Usage

Initialize Gitkit client instance

  p12_file = 'YOUR_SERVICE_ACCOUNT_PRIVATE_KEY_FILE.p12'
  f = file(p12_file, 'rb')
  key = f.read()
  f.close()
  gitkit_instance = gitkitclient.GitkitClient(
      client_id='YOUR_WEB_APPLICATION_CLIENT_ID_AT_GOOGLE_DEVELOPER_CONSOLE',
      service_account_email='[email protected]',
      service_account_key=key,
      widget_url='URL_ON_YOUR_SERVER_TO_HOST_GITKIT_WIDGET')

Verify Gitkit Token in HTTP request cookie

  user = gitkit_instance.VerifyGitkitToken(request.COOKIES['gtoken'])

Upload Multiple Accounts

  hashKey = 'hash-key'
  user1 = gitkitclient.GitkitUser()
  user1.email = '[email protected]'
  user1.user_id = '1234'
  user1.salt = 'salt-1'
  user1.passwordHash = calcHmac(hashKey, '1111', 'salt-1')

  user2 = gitkitclient.GitkitUser()
  user2.email = '[email protected]'
  user2.user_id = '5678'
  user2.salt = 'salt-2'
  user2.passwordHash = calcHmac(hashKey, '5555', 'salt-2')

  gitkit_instance.UploadUsers('HMAC_SHA1', hashKey, [user1, user2])

Download Accounts

  for account in gitkit_instance.GetAllUsers(2):
    pprint(vars(account))

Get Account Info

  pprint(vars(gitkit_instance.GetUserById('1234')))
  pprint(vars(gitkit_instance.GetUserByEmail('[email protected]')))

Delete Account

  gitkit_instance.DeleteUser('1234')

identity-toolkit-python-client's People

Contributors

cslink avatar liujin-google avatar naokigoogle avatar revolutiontech avatar tjohns avatar vmenezes avatar wuyanna avatar wyhao31 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

identity-toolkit-python-client's Issues

Deprecation and migration to Firebase

Is this library deprecated?

https://developers.google.com/identity/toolkit/ states that

The newest version of Google Identity Toolkit has been released as Firebase Authentication. It includes upgraded client SDKs, open source UI libraries, session management and integrated email sending service for forgotten password flows.

New projects should use Firebase Authentication. To migrate an existing project from Identity Toolkit to Firebase Authentication, see the migration guide.

When checking the migration site, there aren't really a lot of precise infos.

First off, I think it's really great that this will give us now access to all of the Firebase offerings, as I was in some kind of need for the Cloud Messaging feature.

My question is, how do we replace this library in our Python backend server?

As I have understood the migration guide, an Android App authenticates to Firebase, requests a JWT token from the Firebase server, and our custom Python backend only has to receive this token, verify its validity and extract the info, both with the help of a JWT library, in order to create a new session? This means that server-side now only a JWT library from https://jwt.io/ is needed?

And the same goes for a JavaScript WebApp?

UnicodeDecodeError

Getting this error trying to run this code in app engine:

File "identitytoolkit/rpchelper.py", line 231, in _GetAccessToken
'assertion': self._GenerateAssertion(),
File "identitytoolkit/rpchelper.py", line 259, in _GenerateAssertion
crypt.Signer.from_string(self.service_account_key),
File "oauth2client/_pure_python_crypt.py", line 167, in from_string
key = _from_bytes(key) # pem expects str in Py3
File "oauth2client/_helpers.py", line 87, in _from_bytes
if isinstance(value, six.binary_type) else value)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x82 in position 1: invalid start byte

Do I need a specific version of a dependency? I saw some talk on stackoverfly about pyopenSSL which I tried to upgrade but still no luck.

PKCS12 format is not supported by the PyCrypto library

I am getting the following error while trying to execute methods on the GitkitClient:

def get_client():
    with open(current_app.config['GOOGLE_PRIVATE_KEY_FILE'], 'rb') as key_file:
        key = key_file.read()
    return gitkitclient.GitkitClient(client_id=current_app.config['GOOGLE_CLIENT_ID'],
                                     service_account_email=current_app.config['GOOGLE_SERVICE_ACCOUNT_EMAIL'],
                                     service_account_key=key,
                                     widget_url=url_for('widget', _external=True),  # flask route for the widget
                                     cookie_name=current_app.config['GITKIT_COOKIE_NAME'])

get_client().GetClientId()  # throws

NotImplementedError: PKCS12 format is not supported by the PyCrypto library. Try converting to a "PEM" (openssl pkcs12 -in xxxxx.p12 -nodes -nocerts > privatekey.pem) or using PyOpenSSL if native code is an option.

GitkitClient.VerifyGitkitToken works as expected.

Provide identity-toolkit on app engine

It is completely incomprehensible how to use this with Google App Engine.

In particular, it is crazy that we have to "vendor" install a dozen dependencies.

All identity-toolkit libraries should be preinstalled ("runtime provided") by Google App Engine:
https://cloud.google.com/appengine/docs/python/tools/libraries27

and a simple example of a federated-login app engine application should be added, that can be test-driven locally. The example at https://github.com/googlesamples/identity-toolkit-python/blob/master/gitkit_command_tool.py does not make any sense for app engine.

base64 decode error with unicode password hash

I get the follow traceback consistently when attempting to log in with a "password account":

base64.urlsafe_b64decode works if you str() it's arg but fails with a unicode arg on line 81.

ERROR 2016-03-19 20:27:29,864 base.py:223] gitkit_instance.GetUserById("07250307095831458805DA000527416E2C4F6C611400"):
Traceback (most recent call last):
File "/Users/rmasse/google-app-engine/laruta-1031/default/bp_content/themes/macpa/handlers/base.py", line 221, in _authorize
gitkit_user_data = main.gitkit_instance.GetUserById(gitkit_user.user_id)
File "/Users/rmasse/google-app-engine/laruta-1031/default/lib/identitytoolkit/gitkitclient.py", line 296, in GetUserById
return GitkitUser.FromApiResponse(user)
File "/Users/rmasse/google-app-engine/laruta-1031/default/lib/identitytoolkit/gitkitclient.py", line 104, in FromApiResponse
return cls(**response)
File "/Users/rmasse/google-app-engine/laruta-1031/default/lib/identitytoolkit/gitkitclient.py", line 81, in init
self.password_hash = base64.urlsafe_b64decode(kwargs['passwordHash'])
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py", line 116, in urlsafe_b64decode
return b64decode(s.translate(_urlsafe_decode_translation))
TypeError: character mapping must return integer, None or unicode

Not Python3 compatible

This module use plenty of libraries and few syntax that are deprecated on Python3. Is there anyone working on an update?
If not, I did some fixes on it and ended up with a new fork that runs on both Python2.x and Python3.x. Should I make a pull request?

ApplicationDefaultCredentialsError on AWS

Apparently the changes introduced two days ago in gitkitclient.py and rpchelper.py (Add support to use Google application default credential) are not backwards compatible.

When running code which worked on AWS in version 0.1.8, that code is now throwing an error in version 0.1.9.

  Traceback (most recent call last):
    File "SERVER.py", line 161, in <module>
      settings['key']
    File "/home/USER/VENV/local/lib/python2.7/site-packages/identitytoolkit/gitkitclient.py", line 192, in __init__
      use_app_default_credentials)
    File "/home/USER/VENV/local/lib/python2.7/site-packages/identitytoolkit/rpchelper.py", line 50, in __init__
      self.credentials = GoogleCredentials.get_application_default() \
    File "/home/USER/VENV/local/lib/python2.7/site-packages/oauth2client/client.py", line 1319, in get_application_default
      return GoogleCredentials._get_implicit_credentials()
    File "/home/USER/VENV/local/lib/python2.7/site-packages/oauth2client/client.py", line 1309, in _get_implicit_credentials
      raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
  ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

After modifying the call to gitkitclient.GitkitClient by adding use_app_default_credentials=True and removing the service account key as a parameter, I'm now getting

ApplicationDefaultCredentialsError: An error was encountered while reading json file: ../FILENAME-DOWNLOADED-FILE.p12 (pointed to by GOOGLE_APPLICATION_CREDENTIALS environment variable): Extra data: line 1 column 2 - line 11 column 21 (char 1 - 2572)

Is it safe to set use_app_default_credentials to False? What is the content of the GOOGLE_APPLICATION_CREDENTIALS? Isn't it the p12 file which can be downloaded from the developer console, the one which was the servive account key?

Ok, it's the json file that can be generated and downloaded from the developer console. Now, the question that remains is the following: Is it safe to set use_app_default_credentials to False?

Google app engine cannot access key

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/base/data/home/apps/s~appname/1.391345578538984665/run.py", line 6, in <module>
    import application
  File "/base/data/home/apps/s~appname/1.391345578538984665/application/__init__.py", line 32, in <module>
    app.config.from_object('application.settings.Production')
  File "/base/data/home/apps/s~appname/1.391345578538984665/lib/flask/config.py", line 162, in from_object
    obj = import_string(obj)
  File "/base/data/home/apps/s~appname/1.391345578538984665/lib/werkzeug/utils.py", line 417, in import_string
    return getattr(__import__(module, None, None, [obj]), obj)
  File "/base/data/home/apps/s~appname/1.391345578538984665/application/settings.py", line 14, in <module>
    class Config(object):
  File "/base/data/home/apps/s~appname/1.391345578538984665/application/settings.py", line 40, in Config
    server_config_json)
  File "/base/data/home/apps/s~appname/1.391345578538984665/lib/identitytoolkit/gitkitclient.py", line 234, in FromConfigFile
    key_file = open(json_data['serviceAccountPrivateKeyFile'], 'rb')
IOError: [Errno 2] No such file or directory: u'./google_key.json'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.