Connecting multiple providers to Firebase using JavaScript

I have successfully implemented authentication for Email/Password and social login with Facebook/Google. Now, my goal is to link the user's account on Firebase if they sign up with Facebook/Google after previously signing up with either Facebook/Google or Email.

Currently, I am handling the 'auth/email-already-in-use' error code.

Although I have managed the separate parts, I am facing issues linking accounts. Despite using the provided code, nothing seems to get linked on Firebase.

I am utilizing Vue.js for the Frontend, but the authentication process is primarily JavaScript-based. Feel free to ask for further clarification if needed.

An error I encounter when clicking the signup button for Email/Password is:

TypeError: self.googleSignin(...) is undefined

Below is a portion of the code:

<template>
    <div class="row">
        <div class="display-block">
            <div class="row">
                <div class="input-field col s12">
                    <input id="email" type="email" v-model="email" class="validate email-input-field" placeholder="Email Address">
                    <i class="material-icons prefix">email</i>
                </div>
            </div>
            // More HTML Code...
        </div>
        <!-- end display block -->
    </div>
</template>

// Javascript Code ...

Answer №1

Consider removing the self references in your code. Here's an alternative approach:

var googleProvider = new firebase.auth.GoogleAuthProvider();
var facebookProvider = new firebase.auth.FacebookAuthProvider();

var app = {}

app.data = function() {
    return {
        email: '',
        password: '',
        credential: {}
    };
};

app.signup = function(provider) {
    firebase.auth().createUserWithEmailAndPassword(app.data.email, app.data.password).then(
        (user) => {
            self.registerProfile()
            user.sendEmailVerification()
            Materialize.toast('Email verification sent to: ' + app.data.email, 5000)
        },
        (err) => {
            console.log("Error Code: " + err.code)
            if (err.code == 'auth/email-already-in-use') {
                var credential = firebase.auth.EmailAuthProvider.credential(app.data.email, app.data.password)
                app.data.credential = credential
                //check if google-link with facebook or if facebook link with google
                app.googleSignin().then(function() {
                    firebase.auth().currentUser.link(app.data.credential).then(function(user) {
                        console.log("Account Linking success: " + user)
                    }, function(error) {
                        console.log("Error on linking accounts" + error)
                    })
                })
            } else {
                Materialize.toast('Uppss: ' + err.message, 5000)
                user.sendEmailVerification()
            }
        }
    );
};

app.googleSignin = function() {
    firebase.auth().signInWithPopup(googleProvider).then(function(result) {
        var token = result.credential.accessToken;
        var user = result.user;
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log(error.code)
        console.log(error.message)
    });
};

app.facebookSignin = function() {
    firebase.auth().signInWithPopup(facebookProvider).then(function(result) {
        var token = result.credential.accessToken;
        var user = result.user;
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log("error code:" + error.code)
        console.log("error msg:" + error.message)
    });
};

export default {
    name: 'signUp',
    data: app.data,
    methods: {
        signUp: app.signup,
        googleSignin: app.googleSignin,
        facebookSignin: app.facebookSignin,
    }
}

Some observations:

  • The call to self.registerProfile() is present but the function is not defined in the code.
  • You directly reference data in the signup method, consider passing it as a parameter instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

Utilizing node-gcm with a proxy configuration

I am facing an issue with node-gcm while trying to send push notifications to Android devices behind a proxy. It seems that the GCM stops functioning when Node.js is running behind a proxy server. How can I configure GCM to work with the proxy settings? v ...

Clicking on a link to submit a form and passing a POST variable

Hey there, I'm trying to figure out how to use an anchor tag to submit a form. My form originally had an input button that passed a post variable for me to check in my php script. How can I replicate this functionality with an anchor tag? Here's ...

Comparing AJAX to a source script request

As I was exploring the Google API today, I came across their sample code where they simply request a URL using: <script src="src="https://www.googleapis.com/customsearch/v1?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1.."></script> Before seeing this, I ha ...

Remove bulleted list from HTML using JavaScript DOM

My task involved deleting the entire "agent" array using the removeChild() function, requiring the id of a <ul> element. However, I faced an issue as I couldn't set the id for the "ul" due to using the createElement() function. //old code < ...

Creating a Dynamic Controller with Dynamic Parameters in AngularJS

For my project, I am using requirejs, angularamd, and ui.bootstrap. When working with a popup form, I utilize $uibModal from ui.bootstrap. However, I am facing an issue where I cannot pass a parameter "items" from resolve. How can I dynamically inject para ...

Why do variables maintain the same value across modules when using the require function in Node.js?

We have a scenario where we have multiple files in the same directory: data.js var anArray = [1,2]; module.exports = anArray; mod1.js var data = require('./data'); module.exports = data; mod2.js var data = require('./data'); modul ...

Converting uploaded file data into JSON format using JavaScript

I am currently loading a JSON data file, however the data is being read as a string. I am attempting to convert this string into a JSON object using JSON.parse, but it still remains as a string. Here is the content of the JSON file: { "annotations": ...

Angular-nvd3: maintaining consistent spacing between data points along the x-axis

By default, the scale of the x-axis is calculated from values, resulting in uneven distances between two adjacent points. For example, with an array of values like [1,2,5], there will be different distances on the x-axis for each point, and the x-axis labe ...

Error: The type 'Element[]' cannot be assigned to the type 'ReactElement<any, string | JSXElementConstructor<any>>'

Here is a declaration for a component I'm working on: const CustomWrapper = ({children}: {children: ReactElement[]}): ReactElement => { return ( <div className="custom-wrapper"> {children} </div> ); }; This ...

Designing a web application with Angular2

As a newcomer to Angular2, I have recently started working on creating a simple hello world application. I have come across the concept of Modules and Components in Angular2. My main source of confusion lies in how to properly design an Angular2 applicat ...

Creating a custom color palette with Material UI using ThemeProvider

Attempting to set a custom color for a Button using createMuiTheme and ThemeProvider has been successful with the primary and secondary palettes. However, when trying to utilize an alternate color such as "info", it does not seem to work as expected: http ...

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

Real-time data updates using AJAX in Ruby on Rails

Currently, I am working with Rails and jquery to implement dynamic content using ajax. However, one issue I am facing is extracting the current user ID from the URL For instance, if the URL is www.mywebsite.com/users/20 In my javascript file, I require ...

What is the best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

The JavaScript submenu has ceased to function properly following the latest update to iPhone iOS 5

I am experiencing an issue with my javascript menu on iOS 5 update. It functions properly on Firefox, IE, Safari, and iPhone/iPad iOS 4. However, after the iOS 5 update, the submenu briefly appears and then disappears when a menu item is clicked. Can any ...

Encountering issues with styled component's flex not functioning as expected in React

I am currently working with styled-components, and I have been using "flex" for responsive design. However, I am facing some challenges in implementing it. The CSS defined within styled-components does not seem to be applying properly. The styles are not ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...