1- """Firebase Authentication Library .
1+ """Firebase Authentication module .
22
3- This library contains helper methods and utilities for minting and verifying
3+ This module contains helper methods and utilities for minting and verifying
44JWTs used for authenticating against Firebase services.
55"""
66
7- import json
87import os
9- import sys
108import threading
119import time
1210
13- import httplib2
14- from oauth2client import client
1511from oauth2client import crypt
1612
17- import firebase
18- from firebase import jwt
13+ import firebase_admin
14+ from firebase_admin import credentials
15+ from firebase_admin import jwt
1916
2017_auth_lock = threading .Lock ()
2118
3027
3128def _get_initialized_app (app ):
3229 if app is None :
33- return firebase .get_app ()
34- elif isinstance (app , firebase .App ):
35- initialized_app = firebase .get_app (app .name )
30+ return firebase_admin .get_app ()
31+ elif isinstance (app , firebase_admin .App ):
32+ initialized_app = firebase_admin .get_app (app .name )
3633 if app is not initialized_app :
3734 raise ValueError ('Illegal app argument. App instance not '
3835 'initialized via the firebase module.' )
3936 return app
4037 else :
4138 raise ValueError ('Illegal app argument. Argument must be of type '
42- ' firebase .App, but given "{0}".' .format (type (app )))
39+ ' firebase_admin .App, but given "{0}".' .format (type (app )))
4340
4441
4542def _get_token_generator (app ):
@@ -99,7 +96,7 @@ def verify_id_token(id_token, app=None):
9996
10097 Raises:
10198 ValueError: If the input parameters are invalid, or if the App was not
102- initialized with a CertificateCredential .
99+ initialized with a credentials.Certificate .
103100 AppIdenityError: The JWT was found to be invalid, the message will contain
104101 details.
105102 """
@@ -147,10 +144,9 @@ def create_custom_token(self, uid, developer_claims=None):
147144 Raises:
148145 ValueError: If input parameters are invalid.
149146 """
150- credential = self ._app .options .credential
151- if not isinstance (credential , CertificateCredential ):
147+ if not isinstance (self ._app .credential , credentials .Certificate ):
152148 raise ValueError (
153- 'Must initialize Firebase App with a certificate credential'
149+ 'Must initialize Firebase App with a certificate credential '
154150 'to call create_custom_token().' )
155151
156152 if developer_claims is not None :
@@ -176,8 +172,8 @@ def create_custom_token(self, uid, developer_claims=None):
176172
177173 now = int (time .time ())
178174 payload = {
179- 'iss' : credential .service_account_email ,
180- 'sub' : credential .service_account_email ,
175+ 'iss' : self . _app . credential .service_account_email ,
176+ 'sub' : self . _app . credential .service_account_email ,
181177 'aud' : self .FIREBASE_AUDIENCE ,
182178 'uid' : uid ,
183179 'iat' : now ,
@@ -187,7 +183,7 @@ def create_custom_token(self, uid, developer_claims=None):
187183 if developer_claims is not None :
188184 payload ['claims' ] = developer_claims
189185
190- return jwt .encode (payload , credential .signer )
186+ return jwt .encode (payload , self . _app . credential .signer )
191187
192188 def verify_id_token (self , id_token ):
193189 """Verifies the signature and data for the provided JWT.
@@ -202,22 +198,21 @@ def verify_id_token(self, id_token):
202198 A dict consisting of the key-value pairs parsed from the decoded JWT.
203199
204200 Raises:
205- ValueError: The app was not initialized with a CertificateCredential
201+ ValueError: The app was not initialized with a credentials.Certificate instance.
206202 AppIdenityError: The JWT was found to be invalid, the message will
207203 contain details.
208204 """
209205 if not id_token or not isinstance (id_token , basestring ):
210206 raise ValueError ('Illegal ID token provided: {0}. ID token '
211207 'must be a non-empty string.' .format (id_token ))
212208
213- credential = self ._app .options .credential
214209 try :
215- project_id = credential .project_id
210+ project_id = self . _app . credential .project_id
216211 except AttributeError :
217212 project_id = os .environ .get (GCLOUD_PROJECT_ENV_VAR )
218213
219214 if not project_id :
220- raise ValueError ('Must initialize app with a CertificateCredential '
215+ raise ValueError ('Must initialize app with a credentials.Certificate '
221216 'or set your Firebase project ID as the '
222217 'GCLOUD_PROJECT environment variable to call '
223218 'verify_id_token().' )
@@ -281,76 +276,3 @@ def verify_id_token(self, id_token):
281276 audience = project_id ,
282277 kid = header .get ('kid' ),
283278 http = _http )
284-
285-
286- class Credential (object ):
287- """Provides OAuth2 access tokens for accessing Firebase services.
288- """
289-
290- def get_access_token (self , force_refresh = False ):
291- """Fetches a Google OAuth2 access token using this credential instance.
292-
293- Args:
294- force_refresh: A boolean value indicating whether to fetch a new token
295- or use a cached one if available.
296- """
297- raise NotImplementedError
298-
299- def get_credential (self ):
300- """Returns the credential instance used for authentication."""
301- raise NotImplementedError
302-
303-
304- class CertificateCredential (Credential ):
305- """A Credential initialized from a JSON keyfile."""
306-
307- def __init__ (self , file_path ):
308- """Initializes a credential from a certificate file.
309-
310- Parses the specified certificate file (service account file), and
311- creates a credential instance from it.
312-
313- Args:
314- file_path: Path to a service account certificate file.
315-
316- Raises:
317- IOError: If the specified file doesn't exist or cannot be read.
318- ValueError: If an error occurs while parsing the file content.
319- """
320- super (CertificateCredential , self ).__init__ ()
321- # TODO(hkj): Clean this up once we are able to take a dependency
322- # TODO(hkj): on latest oauth2client.
323- with open (file_path ) as json_keyfile :
324- json_data = json .load (json_keyfile )
325- self ._project_id = json_data .get ('project_id' )
326- try :
327- self ._signer = crypt .Signer .from_string (
328- json_data .get ('private_key' ))
329- except Exception as error :
330- err_type , err_value , err_traceback = sys .exc_info ()
331- err_message = 'Failed to parse the private key string: {0}' .format (
332- error )
333- raise ValueError , (err_message , err_type , err_value ), err_traceback
334- self ._service_account_email = json_data .get ('client_email' )
335- self ._g_credential = client .GoogleCredentials .from_stream (file_path )
336-
337- @property
338- def project_id (self ):
339- return self ._project_id
340-
341- @property
342- def signer (self ):
343- return self ._signer
344-
345- @property
346- def service_account_email (self ):
347- return self ._service_account_email
348-
349- def get_access_token (self , force_refresh = False ):
350- if force_refresh :
351- self ._g_credential .refresh (httplib2 .Http ())
352- token_info = self ._g_credential .get_access_token ()
353- return token_info .access_token
354-
355- def get_credential (self ):
356- return self ._g_credential
0 commit comments