siderra
siderra

Reputation: 301

Add users on local db on user creation in firebase python django

I have been using the django default auth backend for my authentication.Recently I decided to use firebase for my authentication while maintaining my users in my postgres db. I have used Pyrebase to do user creation and sign in on firebase from my django backend.This works well.But now I need to create the users on my local db as they get created on firebase, since I do not want to have two different sets of users on firebase and on my db .What is the best way to achieve this or can someone point me in the right direction?

Views.py

 "apiKey": "AIzaSyBAfh2M6EOkXfRXBT1BVMxIET6iQzCOn1Y",
 "authDomain": "finance-web-auth.firebaseapp.com",
 "databaseURL": "https://finance-web-auth-default-rtdb.firebaseio.com",
 "storageBucket": "finance-web-auth.appspot.com",
}

firebase = pyrebase.initialize_app(config)

auth = firebase.auth() 

class AuthCreate(APIView):
   permission_classes = [AllowAny]
   def post(self, request, format=None):
       
       email = request.POST.get("email")
       password = request.POST.get("password")
   
       user = auth.create_user_with_email_and_password(email, password)
       auth.send_email_verification(user['idToken'])

       return Response(user)        

This is the response I get once a user gets created

    "kind": "identitytoolkit#SignupNewUserResponse",
    "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg4ZGYxMz",
    "email": "[email protected]",
    "refreshToken": "AGEha4v_rqVydtffrhjizMtqkQaOJz5_gW4aAb9J-xqY6WL_tDMBX_kQA",
    "expiresIn": "3600",
    "localId": "vasavF3"
}

Upvotes: 1

Views: 633

Answers (1)

Alexandr Tatarinov
Alexandr Tatarinov

Reputation: 4034

All you need is simply create a User the same way as you create any other model

def post(self, request, format=None):   
   email = request.POST.get("email")
   password = request.POST.get("password")

   user = auth.create_user_with_email_and_password(email, password)
   auth.send_email_verification(user['idToken'])

   django_user, _ = User.objects.get_or_create(email=email)
   # If you want to copy the password from firebase
   if not django_user.check_password(password):
       django_user.set_password(password)
       django_user.save()

   # Pass the token to the client to make authenticated requests
   token, _ = Token.objects.get_or_create(user=django_user))
   user['token'] = token.key
   return Response(user)   

Upvotes: 1

Related Questions