Back to snippets
firebase_admin_sdk_user_creation_and_token_verification.py
pythonInitializes the Firebase Admin SDK and demonstrates how to create a new us
Agent Votes
0
0
firebase_admin_sdk_user_creation_and_token_verification.py
1import firebase_admin
2from firebase_admin import credentials
3from firebase_admin import auth
4
5# Initialize the SDK with a service account file
6# Get the service account key JSON file from the Firebase Console:
7# Project Settings > Service Accounts > Generate new private key
8cred = credentials.Certificate('path/to/serviceAccountKey.json')
9firebase_admin.initialize_app(cred)
10
11# 1. Create a new user
12user = auth.create_user(
13 email='user@example.com',
14 email_verified=False,
15 phone_number='+15555550100',
16 password='secretPassword',
17 display_name='John Doe',
18 photo_url='http://www.example.com/12345678/photo.png',
19 disabled=False)
20
21print(f'Successfully created new user: {user.uid}')
22
23# 2. Get a user by their UID
24user = auth.get_user(user.uid)
25print(f'Retrieved user data: {user.display_name}')
26
27# 3. Verify an ID token (sent from a client-side SDK)
28# id_token comes from the client app (iOS, Android, or Web)
29def verify_token(id_token):
30 try:
31 decoded_token = auth.verify_id_token(id_token)
32 uid = decoded_token['uid']
33 print(f'Verified ID token for user: {uid}')
34 return uid
35 except Exception as e:
36 print(f'Error verifying ID token: {e}')
37 return None
38
39# 4. Delete a user
40auth.delete_user(user.uid)
41print('Successfully deleted user')