Firebase kicks out current user

前端 未结 14 1778
一个人的身影
一个人的身影 2020-11-22 01:42

So I have this issue where every time I add a new user account, it kicks out the current user that is already signed in. I read the firebase api and it said that \"I

相关标签:
14条回答
  • 2020-11-22 02:00

    Here is a Swift 3 adaptaion of Jcabrera's answer :

    let bundle = Bundle.main
            let path = bundle.path(forResource: "GoogleService-Info", ofType: "plist")!
            let options = FIROptions.init(contentsOfFile: path)
            FIRApp.configure(withName: "Secondary", options: options!)
            let secondary_app = FIRApp.init(named: "Secondary")
            let second_auth = FIRAuth(app : secondary_app!)
            second_auth?.createUser(withEmail: self.username.text!, password: self.password.text!)
            {
                (user,error) in
                print(user!.email!)
                print(FIRAuth.auth()?.currentUser?.email ?? "default")
            }
    
    0 讨论(0)
  • 2020-11-22 02:02

    You can use firebase function for add users.

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    const cors = require('cors')({
    origin: true,
    });
    exports.AddUser = functions.https.onRequest(( req, res ) => {
    // Grab the text parameter.
    
    cors( req, res, ()  => {
        let email  = req.body.email;
        let passwd = req.body.passwd;
        let role   = req.body.role;
        const token = req.get('Authorization').split('Bearer ')[1];
    
        admin.auth().verifyIdToken(token)
        .then(
                (decoded) => { 
                 // return res.status(200).send(  decoded )
                 return creatUser(decoded);
                })
        .catch((err) => {
                return res.status(401).send(err) 
         });
    
        function creatUser(user){
          admin.auth().createUser({
              email: email,
              emailVerified: false,
              password: passwd,
              disabled: false
            })
            .then((result) => {
              console.log('result',result);
               return res.status(200).send(result);
            }).catch((error) => {
               console.log(error.message);
               return res.status(400).send(error.message);
           })
         }
    
       }); 
     });
    
    0 讨论(0)
  • 2020-11-22 02:05

    I just created a Firebase Function that triggers when a Firestore document is Created (with rules write-only to admin user). Then use admin.auth().createUser() to create the new user properly.

    export const createUser = functions.firestore
    .document('newUsers/{userId}')
    .onCreate(async (snap, context) => {
        const userId = context.params.userId;
        const newUser = await admin.auth().createUser({
            disabled: false,
            displayName: snap.get('displayName'),
            email: snap.get('email'),
            password: snap.get('password'),
            phoneNumber: snap.get('phoneNumber')
        });
        // You can also store the new user in another collection with extra fields
        await admin.firestore().collection('users').doc(newUser.uid).set({
            uid: newUser.uid,
            email: newUser.email,
            name: newUser.displayName,
            phoneNumber: newUser.phoneNumber,
            otherfield: snap.get('otherfield'),
            anotherfield: snap.get('anotherfield')
        });
        // Delete the temp document
        return admin.firestore().collection('newUsers').doc(userId).delete();
    });
    

    You can Algo use functions.https.onCall()

    exports.createUser= functions.https.onCall((data, context) => {
        const uid = context.auth.uid; // Authorize as you want
        // ... do the same logic as above
    });
    

    calling it.

    const createUser = firebase.functions().httpsCallable('createUser');
    createUser({userData: data}).then(result => {
        // success or error handling
    });
    
    0 讨论(0)
  • 2020-11-22 02:05

    Swift 5: Simple Solution

    First store the current user in a variable called originalUser

    let originalUser = Auth.auth().currentUser
    

    Then, in the completion handler of creating a new user, use the updateCurrentUser method to restore the original user

    Auth.auth().updateCurrentUser(originalUser, completion: nil)
    
    0 讨论(0)
  • 2020-11-22 02:07

    Update 20161110 - original answer below

    Also, check out this answer for a different approach.

    Original answer

    This is actually possible.

    But not directly, the way to do it is to create a second auth reference and use that to create users:

    var config = {apiKey: "apiKey",
        authDomain: "projectId.firebaseapp.com",
        databaseURL: "https://databaseName.firebaseio.com"};
    var secondaryApp = firebase.initializeApp(config, "Secondary");
    
    secondaryApp.auth().createUserWithEmailAndPassword(em, pwd).then(function(firebaseUser) {
        console.log("User " + firebaseUser.uid + " created successfully!");
        //I don't know if the next statement is necessary 
        secondaryApp.auth().signOut();
    });
    

    If you don't specify which firebase connection you use for an operation it will use the first one by default.

    Source for multiple app references.

    EDIT

    For the actual creation of a new user, it doesn't matter that there is nobody or someone else than the admin, authenticated on the second auth reference because for creating an account all you need is the auth reference itself.

    The following hasn't been tested but it is something to think about

    The thing you do have to think about is writing data to firebase. Common practice is that users can edit/update their own user info so when you use the second auth reference for writing this should work. But if you have something like roles or permissions for that user make sure you write that with the auth reference that has the right permissions. In this case, the main auth is the admin and the second auth is the newly created user.

    0 讨论(0)
  • 2020-11-22 02:07

    Update for Swift 4

    I have tried a few different options to create multiple users from a single account, but this is by far the best and easiest solution.

    Original answer by Nico

    First Configure firebase in your AppDelegate.swift file

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        FirebaseApp.configure(name: "CreatingUsersApp", options: FirebaseApp.app()!.options)
    
        return true
    }
    

    Add the following code to action where you are creating the accounts.

                if let secondaryApp = FirebaseApp.app(name: "CreatingUsersApp") {
                    let secondaryAppAuth = Auth.auth(app: secondaryApp)
                    
                    // Create user in secondary app.
                    secondaryAppAuth.createUser(withEmail: email, password: password) { (user, error) in
                        if error != nil {
                            print(error!)
                        } else {
                            //Print created users email.
                            print(user!.email!)
                            
                            //Print current logged in users email.
                            print(Auth.auth().currentUser?.email ?? "default")
                            
                            try! secondaryAppAuth.signOut()
                            
                        }
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题