Enhance security in AngularJS by enabling data sharing between controllers and implementing callback functions for authentication

Currently, I am engaged in building an Angular front-end application, aiming to keep things simple without relying on tools like breeze or restangular while still maintaining code integrity. However, I have noticed that my code tends to become overly complex even with just a few lines written.

The main goal is to store user information in a cookie and retrieve it when someone logs in.

The Auth service implementation

var userResource = $resource('/users/:id');
var currentUser = $cookieStore.get("user") || {};
return {
    currentUser: currentUser,
    login: function(userId, type, callback) {
        var self = this;
        return userResource.save({id: userId}, {}, function(response) {
            response.then(function(result) {
                self.currentUser = result.data;
                $cookieStore.put("user", self.currentUser);
                if(callback) {
                    callback(self.currentUser);
                }
            });
        });
    },
    users: function() {
        return userResource.query();
    }
};

The AuthCtrl controller setup

$scope.login = function(userId, type) {
    Auth.login(userId, type, function(result) {
        $scope.user = result;
    });
};
Auth.login("someuser", 'basic', function(result) {
    $scope.user = result;
});
$scope.users = Auth.users();

In another controller:

$scope.user = Auth.currentUser;    
Snippets.query({user: $scope.user.id}, function(snippets) {
    $scope.snippets = snippets;
});

I have chosen to resolve the promise within the service to save the currentUser and store it in the cookieStore (although its availability on mobile devices may be limited).

However, this approach results in returning the resource instead of the promise, which necessitates passing a callback in all login calls.

Can you suggest a more efficient solution?

Answer №1

To handle the resource with a promise, encapsulate it in a promise and then return that promise. Here's how you can do it:

var userDataResource = $resource('/users/:id');
    var currentUserData = $cookieStore.get("user") || {};
    return {
        currentUserData: currentUserData,
        login: function(userId, userType, $q) {
            var self = this;
            var deferredPromise = $q.defer();
            
            if (this.currentUserData.id) {
              return $q.when(this.currentUserData);
            }
            
            userDataResource.save({id: userId}, {}, function(response) {
              if (!response.error) {
                self.currentUserData = response.data;
                $cookieStore.put("user", self.currentUserData);
                deferredPromise.resolve(self.currentUserData);
              } else {
                deferredPromise.reject(response.error);
              }
            });
          
          return deferredPromise.promise;
        },
        getUsers: function() {
            return userDataResource.query();
        }
    };

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

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

Exploring the power of Cucumber, Ruby, Capybara, and Selenium: Enhancing the 'visit' method to handle dynamic content delays

For weeks now, I've been dealing with an issue that seems to have no solution found online... like waiting for ajax, etc... Check out the versions of gems: capybara (2.10.1, 2.7.1) selenium-webdriver (3.0.1, 3.0.0) rspec (3.5.0) running ruby 2.2.5 ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

Utilizing ES6 array methods to convert multidimensional arrays into chart-ready data

Seeking help with converting an array to a specific data format for chart display. The chrart.js library requires data in the following format: dataset = [ { label: 'one', data: []}, {label: 'two', data: []} ]; I ...

What is the most efficient way to transform HTML into React components effortlessly?

I have been attempting to automate the process of converting HTML into React components. I followed the link below to automatically convert HTML into React components: https://www.npmjs.com/package/html-to-react-components However, I encountered an issue ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Locate and click on an item within a repeating element using Protractor

Can someone help me figure out why my attempt to locate a speaker by name in a repeater and then click the edit button is failing? Your input would be greatly appreciated! View: <div ng-repeat="speaker in $ctrl.speakers"> <div class="name" ng- ...

Has the binary search operation not been executed?

My attempt to implement the binary search algorithm in my code example is not producing the expected result. I'm unsure of the cause. Can someone please explain it to me? var array = [1, 4, 6, 8, 9, 12, 15, 17, 19, 34, 55, 78, 80]; function binarySe ...

When using jQuery's ajax() function, it is possible to pass HTML as data and change the ampersands in URLs to &amp;

I have encountered an issue where I am capturing the HTML content of a page and attempting to send it as a string to a PHP web service using jQuery's ajax() function. However, when I receive the parameter on the PHP side, the &s in the URLs present wi ...

What could be causing jQuery's Promise.reject to fail?

Currently, I'm dealing with a REST API that resembles this stub: Snippet 1 (example based on Ruby on Rails). I have some existing jQuery code using classic callbacks: Snippet 2 It's running with these logs: case 1: [INFO] /api/my/action1: rece ...

Is there a way to incorporate multer middleware into my express controller without using the router?

This is the structure I typically follow when writing controllers and routes using Express controller exports.postBlog = async (req, res, next) => {...} routes router.route("/post").post(onlyAdmin, postBlog); *onlyAdmin serves as a middlewa ...

Angular.js Integration for Custom Single Sign On

I currently have 3 websites built using Angular.js 1.5.8 and I want to integrate them with a single sign-on web application for centralized authentication management. How can I achieve this without relying on external libraries or frameworks? It seems ch ...

Tips for incorporating Javascript Object Literals into Python code

Using the Beautifulsoup module, I successfully extracted an HTML page and then proceeded to extract a Javascript script tag from that page. Within this script tag lies an object literal that I hope to manipulate. Here is what I am aiming for: <script&g ...

Can someone provide a sample using $httpBackend (ngMockE2E module service)?

Seeking the most straightforward method to integrate a mock backend service into my angular application. Any advice or pointers on creating a sample app that demonstrates how to implement this would be greatly appreciated. Thank you! ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

`What is the process for accessing page-specific data on Google Analytics using the analyticsreporting tool?`

I'm currently working on extracting specific analytics data using Google's analyticsreporting API v4. Below are the URLs of the pages I am analyzing: https://www.example.com/uiqueId1 https://www.example.com/uiqueId2 https://www.example.com/uiqu ...

Adjust the height of the list when including or excluding floated list items that are not in the final row

Within my ul are li elements with varying widths that wrap around inside a container into multiple rows. When removing an li element from the ul, I want the container's height to adjust dynamically in case a row is eliminated. If the removal happens ...

Ways to verify multiple radio groups to ensure none have been left unchecked

Is there a more elegant solution to check if either "salad" or "side dish" is left unchecked after submission? I currently have a working approach, but it feels overly complex for such a simple task. This is my current method: function radiosChecker(){ l ...

Avoiding repetitive rendering of child components in ReactJS

In my React project, I have a parent component that contains 3 children components, structured like this: var Parent = React.createClass({ render: function() { return (<div> <C1/> <C2/> <C3/> ...