Utilizing Angularfire OAuth for Facebook authentication in login strategy

After successfully implementing the code below in the loginCtrl controller and login.html, I encountered some issues with setting up the workflow correctly. My goal is to achieve something like this:

//check if the current $scope has authData
 //if so redirect to (or render) home.html
//if not stay on the login page.

I am new to Angular and still trying to figure things out. In Node.js with Express, it was clear to me that I just needed to render or redirect when the received data was good. But handling this in Angular seems confusing.

Javascript

.controller('loginCtrl', function ($scope, Auth, Login) {


  $scope.login = function() {
    Auth.$authWithOAuthPopup("facebook")
        .then(function(authData){
          console.log(authData);
        })
        .catch(function(err){
          if(err) {
           console.log("Authentication failed!!", err);
          }
        })
  };
})

.factory('Auth', function($firebaseAuth){
  var usersRef = new Firebase("https://dazzling-heat-4971.firebaseio.com/users");
  return $firebaseAuth(usersRef);
})

HTML

<ion-content class="padding loginbox">
  <div ng-hide="!authData" ng-click="login('facebook')">  
    <!-- <a ui-sref="home" ng-if="verifyLogin()"> -->
      <button class="button button-positive icon ion-social-facebook">
        Login with Facebook
      </button>
    <!-- </a> -->
  </div>
</ion-content>

Answer №1

One of the great features of AngularFire is its built-in support for simplifying routing and authentication.

Instead of having to constantly check for an authenticated user in your controller, you have the ability to simply inject the currently authenticated user.

This eliminates the need for any cumbersome if else checks in your controller or view, making the code much cleaner and easier to maintain.

You can achieve this by injecting the user through the resolve() function in the router. If you're working with Ionic, remember that it uses ui-router. After successfully logging in the user, don't forget to call $state.$go() with the appropriate route name. This will smoothly transition to the desired view and trigger the associated controller.

The code style shown below conforms to the Angular Style Guide. While it may look different at first glance, it's just another approach to writing Angular code - so don't get too hung up on the details.

angular.module('app', ['firebase'])
   .run(ApplicationRunSettings)
   .config(ApplicationConfig)
   .controller('loginCtrl', LoginCtrl);

// The authData parameter is injected from the router
function UserProfileCtrl($scope, authData) {
  $scope.user = authData;
}

function LoginCtrl($scope, Auth) {
   Auth.$authWithOAuthPopup("facebook")
    .then(function(authData){
      $state.go('userProfile');
    })
    .catch(function(err){
      if(err) {
       console.log("Authentication failed!!", err);
      }
    })
}

// Configure the router to resolve authenticated users
function ApplicationConfig($stateConfig) {
   $stateProvider
     .state("home", {
       controller: "UserProfileCtrl",
       templateUrl: "views/userProfile.html",
       resolve: {
        // Controller will only load once $waitForAuth resolves
        "currentAuth": ["Auth", function(Auth) {
        // $waitForAuth returns a promise, allowing the resolve to wait for completion
           return Auth.$waitForAuth();
        }]
      }
   }
}

// In case of an error, redirect to the home view
function ApplicationRunSettings($rootScope, $state) {
  $rootScope.$on("$stateChangeError", function(event) {
  // If there is an error thrown when the $requireAuth promise fails, redirect back to the home page
  if (error === "AUTH_REQUIRED") {
    $state.go("home");
  }
}

For more information on authenticating with routers using AngularFire, be sure to check out the AngularFire documentation.

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

Changing the color of a placeholder using Javascript: A step-by-step guide

I've been searching online without any luck so far. I'm attempting to change the placeholder color of a text box using JavaScript, but I'm not sure how to go about it. I already have a color picker that changes colors. If my CSS looks somet ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Performing web scraping on a page rendered with Javascript in Python 3.5

I'm currently working on a project that involves extracting a dynamically rendered table using Python 3 and a webdriver. Below is the code I have implemented: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait fro ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

Tips for using jQuery to verify the most recent entry in a form

Struggling with this issue - I can't seem to get jquery to function the way I need it to: Essentially, when a user exits a text field, jquery is supposed to capture the input value and respond accordingly: for example, if the user types 'value& ...

Ways to set the input=text field as read-only in JSP when receiving information from the backend

For a project I am working on, I need to implement a feature where users can view and edit their personal details on a JSP page. If a user is logged in, their information should be fetched from the session and displayed automatically. However, even if they ...

"Could you please provide me with further details on how to use sequelize

I recently started working with node js and I used sequelize-auto to generate the models. However, I encountered an error when following the guidance provided in this link https://github.com/sequelize/sequelize-auto. If you need further clarification on th ...

Using Node.js and MongoDB to filter a sub array within an array of objects

Hello everyone, I currently have an array of objects containing some populated fields. Below is the product schema: import mongoose, { Schema } from 'mongoose'; const productSchema = new mongoose.Schema( { name: String, description: S ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Tips for adjusting the size of an imported item in Three.js?

Currently, I am utilizing Three.js for my project and I am importing .OBJ file using OBJ LOADER () Everything has been working smoothly thus far, but I have come across an issue that has me stumped. I am trying to figure out how to change the width and he ...

Navigating within an entity

Currently working on coding with javascript & react. There is a specific object called "rates" that I am attempting to iterate through: { "M": { "lab": { "S": "50%" }, "dme": { "S": "75%" }, ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Reveal concealed content when a responsive table becomes scrollable on a mobile device

I recently completed a project that was overloaded with tables. I made all the tables responsive, but they still take vertical scroll if they don't fit on certain devices due to their varying widths. For instance, Table A requires vertical scroll o ...