1
- """Firebase Authentication Library .
1
+ """Firebase Authentication module .
2
2
3
- This library contains helper methods and utilities for minting and verifying
3
+ This module contains helper methods and utilities for minting and verifying
4
4
JWTs used for authenticating against Firebase services.
5
5
"""
6
6
7
- import json
8
7
import os
9
- import sys
10
8
import threading
11
9
import time
12
10
13
- import httplib2
14
- from oauth2client import client
15
11
from oauth2client import crypt
16
12
17
- import firebase
18
- from firebase import jwt
13
+ import firebase_admin
14
+ from firebase_admin import credentials
15
+ from firebase_admin import jwt
19
16
20
17
_auth_lock = threading .Lock ()
21
18
30
27
31
28
def _get_initialized_app (app ):
32
29
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 )
36
33
if app is not initialized_app :
37
34
raise ValueError ('Illegal app argument. App instance not '
38
35
'initialized via the firebase module.' )
39
36
return app
40
37
else :
41
38
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 )))
43
40
44
41
45
42
def _get_token_generator (app ):
@@ -99,7 +96,7 @@ def verify_id_token(id_token, app=None):
99
96
100
97
Raises:
101
98
ValueError: If the input parameters are invalid, or if the App was not
102
- initialized with a CertificateCredential .
99
+ initialized with a credentials.Certificate .
103
100
AppIdenityError: The JWT was found to be invalid, the message will contain
104
101
details.
105
102
"""
@@ -147,10 +144,9 @@ def create_custom_token(self, uid, developer_claims=None):
147
144
Raises:
148
145
ValueError: If input parameters are invalid.
149
146
"""
150
- credential = self ._app .options .credential
151
- if not isinstance (credential , CertificateCredential ):
147
+ if not isinstance (self ._app .credential , credentials .Certificate ):
152
148
raise ValueError (
153
- 'Must initialize Firebase App with a certificate credential'
149
+ 'Must initialize Firebase App with a certificate credential '
154
150
'to call create_custom_token().' )
155
151
156
152
if developer_claims is not None :
@@ -176,8 +172,8 @@ def create_custom_token(self, uid, developer_claims=None):
176
172
177
173
now = int (time .time ())
178
174
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 ,
181
177
'aud' : self .FIREBASE_AUDIENCE ,
182
178
'uid' : uid ,
183
179
'iat' : now ,
@@ -187,7 +183,7 @@ def create_custom_token(self, uid, developer_claims=None):
187
183
if developer_claims is not None :
188
184
payload ['claims' ] = developer_claims
189
185
190
- return jwt .encode (payload , credential .signer )
186
+ return jwt .encode (payload , self . _app . credential .signer )
191
187
192
188
def verify_id_token (self , id_token ):
193
189
"""Verifies the signature and data for the provided JWT.
@@ -202,22 +198,21 @@ def verify_id_token(self, id_token):
202
198
A dict consisting of the key-value pairs parsed from the decoded JWT.
203
199
204
200
Raises:
205
- ValueError: The app was not initialized with a CertificateCredential
201
+ ValueError: The app was not initialized with a credentials.Certificate instance.
206
202
AppIdenityError: The JWT was found to be invalid, the message will
207
203
contain details.
208
204
"""
209
205
if not id_token or not isinstance (id_token , basestring ):
210
206
raise ValueError ('Illegal ID token provided: {0}. ID token '
211
207
'must be a non-empty string.' .format (id_token ))
212
208
213
- credential = self ._app .options .credential
214
209
try :
215
- project_id = credential .project_id
210
+ project_id = self . _app . credential .project_id
216
211
except AttributeError :
217
212
project_id = os .environ .get (GCLOUD_PROJECT_ENV_VAR )
218
213
219
214
if not project_id :
220
- raise ValueError ('Must initialize app with a CertificateCredential '
215
+ raise ValueError ('Must initialize app with a credentials.Certificate '
221
216
'or set your Firebase project ID as the '
222
217
'GCLOUD_PROJECT environment variable to call '
223
218
'verify_id_token().' )
@@ -281,76 +276,3 @@ def verify_id_token(self, id_token):
281
276
audience = project_id ,
282
277
kid = header .get ('kid' ),
283
278
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