Navigating AngularJS for User Authorization_REDIRECT

I've developed a login system using angularfire and firebase.

Within this system, I have implemented a function that checks for the existence of authData when a user logs in or at other points in the application's flow. If authData is present, the user is registered as logged in.

fbRef.onAuth(authDataCallback);
function authDataCallback(authData) {
    if (authData) {
        $scope.loggedIn = true;
    } else {
        $scope.loggedIn = false;
    }
}

In addition to this, I have defined various routes:

.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        controller: '',
        templateUrl: '/company/pages/account/pages/dashboard.php',
    })
    .when('/dashboard', {
        controller: '',
        templateUrl: '/company/pages/account/pages/dashboard.php',
    })
    .when('/login', {
        controller: 'Authorization',
        templateUrl: '/company/pages/account/pages/login.php',
    })
    .when('/register', {
        controller: 'Authorization',
        templateUrl: '/company/pages/account/pages/register.php',
    })
})

The goal is to restrict access only to logged-in users on all pages except for the login and register pages. If $scope.loggedIn is false, the user should be redirected back to the login page.

Despite trying multiple solutions found online, none have successfully resolved my issue. Instead, I encountered limit exceeded errors in most cases.

Seeking advice on how to effectively restrict access in this scenario.

Answer №1

To determine if the "loggedIn" variable has been changed, you can implement the following code snippet:

    app.controller('MyCtrl', ['$scope', '$location', function($scope, $location){

        fbRef.onAuth(authDataCallback);

        $scope.loggedIn = null;

        function authDataCallback(authData) {
            $scope.loggedIn = authData ? true : false
        }

        $scope.$watch("loggedIn", function(val){

            val === false && $location.path("/login");

        });

    });

Answer №2

Make sure to verify authentication status in the controller callback and redirect as needed.

app.controller('MyCtrl', ['$scope', '$location', function($scope, $location) {

  fbRef.onAuth(authDataCallback);

  function authDataCallback(authData) {
      authData ? $location.path("/dashboard") : $location.path("/login");
  }

}]);

Answer №3

The game plan:

One potential approach involves creating a variable called loginRequired within the $routeProvider, and then checking this variable against $rootScope.loggedIn during $routeChangeStart.

However, it appears that you must transfer $scope.loggedIn to $rootScope.loggedIn.

A suggested course of action:

In the router:

.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            controller: '',
            templateUrl: '/company/pages/account/pages/dashboard.php',
            loginRequired: true
        })
        .when('/dashboard', {
            controller: '',
            templateUrl: '/company/pages/account/pages/dashboard.php',
            loginRequired: true
        })
        .when('/login', {
            controller: 'Authorization',
            templateUrl: '/company/pages/account/pages/login.php',
            loginRequired: false
        })
        .when('/register', {
            controller: 'Authorization',
            templateUrl: '/company/pages/account/pages/register.php',
            loginRequired: true
        })
    })

In app.run:

app.run(
    ['$rootScope', '$location', function($rootScope, $location) {

        $rootScope.$on('$routeChangeStart', function() {
            if ($rootScope.loginRequired && !$rootScope.loggedIn) {
                $location.path("/login");
            }
        });

    }]);

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

methods for deleting an object from a AngularJS $scope variable

Looking for assistance in removing a single object from the $scope.Profile.address object. Below is the code and image for reference: <tr ng-repeat="x in Profile.addresses"> <td><input type="text" class="form-control" id="inputDefault" ...

Could the jQuery not be running due to the .htaccess file? How can I resolve this issue?

Good Day, I am encountering a persistent pop-up issue with my Joomla! template, displaying only the word "here" in the browser as shown in this Screenshot After investigating, it was suggested that the .htaccess file may be responsible for this behavior. ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

PHP mistakenly outputs content that is not enclosed within tags

After discovering StackOverflow, I couldn't resist sharing my PHP code conundrum with the incredible community here! So, in a WordPress template, I have this chunk of PHP: echo '<div class="thumbnail">'; echo the_post_thumbnail(); ec ...

Broaden the capabilities of Kendo MultiSelect

I am currently working on creating a customized kendo multi-select widget by extending the existing one. The aim is to display the tag list in a div below the input field. My objective with this code is to show the tag list in a separate div upon the sele ...

Determine if a specific value is present in an array of objects using AngularJS

var arr = [ { id:1}, {id:2} ]; var obj = {id:1}; var result = arr.indexOf(obj.id) == -1; console.log(result); I am trying to determine if obj.id exists in the array arr[]. Please note: arr[] is an array of objects ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

Creating a unique WooCommerce product category dropdown shortcode for your website

I am having trouble implementing a WooCommerce categories dropdown shortcode. Although I can see the drop-down menu, selecting a category does not seem to trigger any action. Shortcode: [product_categories_dropdown orderby="title" count="0" hierarchical=" ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Issue: unable to inject ngAnimate due to uncaught object error

Whenever I attempt to inject 'ngAnimate' into my app, I encounter issues with instantiation. Here is the code snippet in question: var app = angular.module('musicsa', [ 'ngCookies', 'ngResource', 'ngSanit ...

Ways to easily modify images using a single button with the help of jq

I am new to programming and eager to learn... Currently, I am facing the following problem: I would like to create a functionality where three images can be changed using one button and incorporating fadeIn and fadeOut animations. Essentially, all images ...

Using jQuery, you can easily set the value of a datetime picker to "

In my pursuit to implement Php, I came to the conclusion that the functionality needed to be executed on the client side. The "ready" function is successfully functioning. //fechaMin and fechaMax are inputs of type "datetime" $(document).ready(function( ...

Avoiding the use of a particular URL when using this.router.navigate() in AngularJs

In my angularJS registration form, I am using a bootstrap template for the design. The URL path to access the form page is http://localhost:4200/signup <form method="post" (submit)='register(username.value,email.value,password.value)'> ...

Using AngularJS to iterate through a nested array with ng-repeat

Hey everyone, I've been working on a project where I have an array called menu[] with nested arrays called flavors[] within it. My goal is to calculate the total price of all active items and flavors in the menu. While I was able to successfully calcu ...

Generating JSON objects within the Ionic SQLite framework

I am new to Ionic development and I'm looking for a way to convert a JSON string into a JSON object in Ionic, as well as how to access this JSON data on an HTML page. controller.js app.controller('OilTrackerListingCntrl', function($scope, ...

Enabling Cross-Origin Resource Sharing in Java Playframework 2.4.x with AngularJS

I've been struggling to configure CORS in my Java Playframework 2.4.x setup with no luck. The frontend application I'm using is built on AngularJS 1.3.x. Following the instructions from the official documentation, I implemented the Filters class ...

Using jQuery to Convert CSV Data into an HTML Table

I've been exploring the incredible jquery.csvtotable.js plugin for converting csv files to html tables. One question that has been on my mind is how can I allow users to select a .csv file using a browse button that isn't a server-side control? ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

Switch between showing and hiding a div by clicking on an image

Currently, I am experimenting with the toggle div function and utilizing images as triggers for toggling. For instance, when a div is closed, an image of a "plus" sign indicates to the user that it can be expanded, and vice versa for compressing the div. T ...

Optimal method for defining controllers in AngularJS

As a newcomer to AngularJS, I find myself faced with the dilemma of determining the best approach for creating a controller within the ng-app="mainApp". In traditional programming languages, it is common practice to keep related data together. However, in ...