Facebook And Twitter Login In Electron

How to do social media login in electron
May 27 2021 · 4 min read

Introduction

The apps built with Electron can support all three platforms Windows, macOS, and Linux.

Very popular apps like Skype, Slack, Atom, and many more are built using electron.

As Electron has this much popularity, there is an obvious requirement to provide social logins and authenticate your apps using user’s Facebook or Twitter accounts for simplicity and flexible user experience of the app.

Let’s see how to implement Facebook and Twitter logins in the Electron app.

We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!

The Electron login flow for Twitter and Facebook login is the same.

We use IPC (Inter-Process Communication), where the renderer process sends an event to do social logins, and the main process handles those events and passes an Auth token to the renderer process, which then authenticates our users with their social accounts.

Electron Login flow :

  1. Create an index.html file and add a login button to initiate social logins.
  2. On the button click, send an event to the main process.
ipcRenderer.send("do-login");

    3. The main process handles the login event, gets the Auth token, and passes it to the renderer process.

As electron provides a non-browser environment, we have to create a login window for open Auth URL, that will provide an interface to do logins.

ipcMain.on("do-login", (event) => {
     let loginWindow = new BrowserWindow({
            width: 650,
            height: 800,
            show: false,
      });
})

      4. In the renderer process, authenticate the user with that token.


Facebook Login

Using an FB developer account, we will do a Facebook login in Electron.

Facebook provides two ways of logging in with JavaScript SDK or using manual login flow.

As JavaScript SDK will not work in the non-browsing environment, we have to build the login flow manually.

Let’s start it.

In the main process, initialize the app using the following code.

const options = {
  client_id: facebookClientId,
  scopes: "email",
  redirect_uri: "https://www.facebook.com/connect/login_success.html,
};

After successful login, we will redirect to redirect_uri, so it is required for Facebook login.

you can take fields as per your requirements in scopes like name, email etc.

let facebookAuthURL = `https://www.facebook.com/v9.0/dialog/oauth?client_id=${options.client_id}&redirect_uri=${options.redirect_uri}&response_type=token,granted_scopes&scope=${options.scopes}&display=popup`;

facebookAuthURL will pop up loginWindow with Facebook login UI.

When the electron’s will-navigate event is called, we will parse that Auth URL and get an Access Token.

This Access Token will be used to verify the user’s email and authenticate the user with a Facebook account.

Set that Access Token globally to your app as below,

const FB = require("fb");
FB.setAccessToken(access_token);

FB.api uses an Access Token and will return the user’s email.

FB.api(
  "/me",
  {
    fields: ["email"],
  },
  function (res) {
    let data = { access_token, res.email};
    event.sender.send("facebook-login", data);
  }
);

Here is easy to use example of Facebook Login using electron, using that example, I have implemented Twitter login too.

You can get more about Facebook's Manual login flow from FB’s developer account docs.

Now it’s time to implement Twitter login.

Twitter Login With Firebase

You can authenticate your users with Firebase using their Twitter accounts by integrating Twitter authentication into your application.

Firebase provides two types of login similar to Facebook, first using Firebase SDK and the other handling sign-in flow manually.

Firebase also does not support login with Firebase SDK in nonbrowsing environments, so we have to use a manual sign-in flow for Twitter login.

Twitter login takes too many steps to complete sign in mentioned below,

  1. Getting Request token
  2. Redirect the user
  3. Getting access-token
  4. Login with firebase

We are using the node-twitter-api package for Twitter login.

Assuming that you have initialized Twitter authentication in Firebase, if not then follow the steps given here.

After doing that, you will get the Twitter consumer key, consumer secret, and a callback URL, and save it for future requirements.

In ipcMain, Initialise the app using Twitter API.

const twitter = new twitterAPI({
  consumerKey: consumerKey,
  consumerSecret: consumerSecret,
  callback: callbackURL,
});

Now Let’s start it step by step.

1. Getting Request token

To start the sign-in flow, the App must obtain the request token by requesting on oauth/request_token, it will take the callback URL as a parameter.

In response, it will send a request token, request secret, and oauth_callback_confirmed = true.

node-twitter-api provides twitter.getRequestToken() method for this.

2. Redirect the user

Redirect the user to the oauth/authenticate URL by passing the request token, obtained in step 1.

twitter.getRequestToken((error, requestToken, requestTokenSecret) => {
  if (!error) {
      twitterWindow.loadURL("https://twitter.com/oauth/authenticate?oauth_token=" + requestToken);
  } 
});

3. Getting access-token

Then on rendering of that URL, it will give oauth-verifier, and using that verifier, we will get access-token as below,

twitter.getAccessToken(
  requestToken,
  requestTokenSecret,
  auth_verifier,
  (error, accessToken, accessTokenSecret) => {
    if (!error) {
      //send access token to renderer process
      event.sender.send("twitter-login", {
              accessToken,
              accessTokenSecret,
              error,
       });
  }
);

4. Login with Firebase

In the renderer process, initialize Firebase with the following config,

import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
  apiKey: firebaseApiKey,
  appId: fireBaseAppId,
};
firebase.initializeApp(firebaseConfig);

Then, handle twitter-login.

Firebase provides a TwitterAuthProvider method that provides firebase credentials from Access Token, that are retrieved in the main process.

signInWithCredential uses those credentials and authenticates the user with their Twitter account.

ipcRenderer.on("twitter-login", (event, response) => {
  if (!response.error) {
    var credential =                firebase.auth.TwitterAuthProvider.credential(
      response.accessToken,
      response.accessTokenSecret
    );
    firebase.auth().signInWithCredential(credential)
      .then((result) => {
        console.log(result.user);
      })
      .catch((error) => {
        console.log(error);
        });
  } 
});

So, that’s it.

You can get full source code in electron HERE!!.

You can get more about Twitter and Firebase login from the Firebase console.

Similar Useful Articles


sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.


sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.


Talk to an expert
get intouch
Our team is happy to answer your questions. Fill out the form and we’ll get back to you as soon as possible
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.