Steps to transfer the angularfire log in object to a service file

I am looking to enhance the usage of the logged-in object across my site. I am interested in moving this object to a service so that I can efficiently check for user authentication. Below is my login controller:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
     $scope.login = function() {
      $scope.authData = null;
      $scope.error = null;

      userAuth.$signInWithEmailAndPassword($scope.loginemail, $scope.loginpassword)
      .then(function(authData) {
        $scope.authData = authData;
        console.log(authData);
      }).catch(function(error) {
        $scope.error = error.message;
      });
    };

Here is my service code:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
    return $firebaseAuth();
  }

While logging in works successfully, my aim is to utilize the logged-in credentials globally. Additionally, I would like to restrict access to certain routes unless the user is authenticated.

If a route is accessible only to logged-in users, they should be redirected to the appropriate page upon attempting access. For instance: - Redirect them to the logged-in page if they try to visit a route reserved for logged-in users. - Log them out if they are already logged in and attempt to access the sign-up page. - Direct them to the profile page if they are logged in and try to visit the login page.

Answer №1

To enhance security, I recommend storing user data within the service itself rather than returning it to the caller. Here's an example of how you can implement this:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
    var userData;
    this.login = function(loginEmail, loginPassword){
       return $firebaseAuth
       .$signInWithEmailAndPassword(loginEmail, loginPassword)
       .then(function(authData) {
           userData = authData;
       });
    }
    this.getUserData = function(){
       return userData;
    }
  }

Then, utilize this in the controller:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
     $scope.login = function() {
      $scope.authData = null;
      $scope.error = null;

      userAuth.login($scope.loginemail, $scope.loginpassword)
      .then(function() {
        $scope.authData = userAuth.getUserData();
        console.log($scope.authData);
      }).catch(function(error) {
        $scope.error = error.message;
      });
    };

This approach offers several advantages:

  1. It encapsulates the login logic, making it easy to modify the login service without affecting other parts of the application.

  2. You can access user data from any part of the application by injecting the auth service and calling the getUserData function.

To restrict users from accessing specific routes, you can utilize the $routeChangeStart event to intercept route changes, prevent navigation, and redirect based on your business requirements.

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

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

What is the process for integrating personalized routes in angular.js?

Currently, I have set up a route as follows: .state('home.blog', { url: "/blog", templateUrl: "blog.html", controller: "BlogController" }) The current route is localhost:3000/home/blog, but I want to change it to localhost:3000/blog. Desp ...

Establishing default values for the Angular-UI Select2 multiple directive

Implementing a select2 directive for a multiple selection of countries with a custom query to fetch the data: // Directive <input ng-model="filters.countries" ui-select2="filters.countryOptions" data-placeholder="Choose a country..."> // filter ...

Obtaining the token using CURL with jhipster oauth: A step-by-step guide

Currently experimenting with jhipster to develop a new project featuring oauth2 authentication. The sample project is functioning smoothly, allowing me to log in using the angularjs interface. Struggling when attempting to fetch an access_token via CURL in ...

Angular's parent div height can be adjusted using CSS transitions

I have implemented a CSS transition to create a sliding effect in my pagination. However, I am facing an issue where the height of the containing div changes even when I set the position of the transitioned elements. Here is a snippet of my CSS: .slide { ...

What is the most effective method for sending Firestore data to React components?

Having trouble efficiently setting a user's profile and passing that data to other components? Below, I've shared my current approach, but the rendering process is not as smooth. Every time I interact with different parts of the app, the data fro ...

A step-by-step guide on effectively implementing express-session with firebase cloud functions

Hello, I am currently working on using express sessions for my backend deployed to Firebase cloud functions. I'm facing an issue where data related to the current session isn't being saved properly. When I try to save something using req.session. ...

Maintaining the order of elements in Angular's insertion process

I am currently facing an issue with my HTML fragment that iterates over a key and value collection. Everything works perfectly when I insert values into an object and iterate through it using the HTML fragment. However, in order to maintain a specific key ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Using the attribute to pass an object to a directive and including a variable inside

Is it possible to transfer $scope.data to a directive through its attribute in an Object, without using separate attributes? I would like to achieve the below format with any solution. <custom-directive detail="{index:1, data: {{data}}}"> </custo ...

Invoking a function within the directive's controller

How can I access and call the method defined within the directive controller externally? <div ng-controller="MyCtrl"> <map></map> <button ng-click="updateMap()">call updateMap()</button> </div> app.directive(&a ...

Why is it important to include a return statement within an angular.js controller?

Within my angular.js controller, I have an if statement that, when satisfied, changes the $state of my app. This is the specific line in question: if ($scope.cond1) $state.go(".main"); .. remainder of controller code When this if statement i ...

AngularJS is not displaying the full value of the model in the user interface

I have a technique for saving an object into an array after modifying some of its properties. However, I am facing an issue where not all the modified properties reflect in the user interface. Code : HomeController.js $scope.MainArray=[]; $scope.newIt ...

Values in AngularJS are essential components that allow data

What is the best way to access the value of FirstName in my directive? <hello-World value="{{item.FirstName}}"> </hello-World> app.directive('helloWorld', function() { return { restrict: 'AE', replace: 'true&apos ...

Guide to setting the ng-selected value within AngularJS

I am currently working on a project where I have a select element in my AngularJS application. I am populating the options using JSON values with ng-repeat, and I want to display the first value from the JSON as selected by default. I have tried two diffe ...

Show the value of one text box inside another text box by harnessing the power of AngularJs when a

I am new to AngularJs and finding it a bit complex. I have set up two text boxes and a button. My goal is to input text into the first text box, then click the button to display that value in the second text box. I've only written a small amount of co ...

The Angular downgradeComponent feature is experiencing difficulties in its creation process

I recently set up a hybrid application using AngularJS and Angular 5 with downgradeModule. I successfully converted a small component from AngularJS to Angular, but unfortunately, it is not being created. I've added console.logs in different parts of ...

Having trouble retrieving records using findOne() when using a custom ID for inserting records in mongoDB

After inserting records into my mongoDB schema with the command: > db.records.insert( { _id: "6", "name": "Ashish", "City": "Dallas" } ) When I attempt to retrieve them using http://localhost:6001/api/employees/, the response I receive is as follows: ...

What is the best way to determine if an item qualifies as an Angular $q promise?

In my project, I have an existing API library that is not Angular-based. This library contains a method called .request which returns promises using jQuery.Deferred. To integrate this with Angular, I created a simple service that wraps the .request method ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...