Deny access to the viewing feature for unauthorized users

Objective:

To restrict access to the profile page only for logged-in users. The authentication is done through mongodb and passport-local.

Existing Code:

Below is the express route used to verify if the request is authenticated.

app.get('/loggedin', function(req, res) { 
    res.send(req.isAuthenticated() ? req.user : '0'); 
});

A service named AuthService calls this route via $http and returns the result.

this.isLoggedIn = function(){
    var promise = $http.get('/loggedin');

    promise.then(function(user){
        if(user === 0 || user === '0'){
            //Not a valid request
            console.log('Not a valid request');
            return false;
        } else {
            //Valid request.
            return user;
        }
    });

    return promise;
};

Error handling code that should throw an error when the resolve promise returns false.

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/profile', {
    templateUrl: 'views/profile.html',
    controller: 'profileCtrl',
    resolve: {
      loggedIn: ['AuthService', function(AuthService){
        return AuthService.isLoggedIn();
      }]
    }

  });
}])

Error handling code to log the routing error.

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

  //Error thrown by a resolve dependency. Handle the error here.
  $rootScope.$on('$routeChangeError', function(event, curRoute, prevRoute, error){
    console.log("Routing error");
  }); 

}])

Problem:

The issue is that the Routing error message is not being displayed in the console (as mentioned above). While the service successfully logs Not a valid request, it's unclear why it's not triggering a $routeChangeError. Once this logging issue is resolved, further implementation of the resolve logic will allow secure access control to various pages as intended.

Answer №1

It seems like your code is in good shape overall, and you seem to have a solid grasp of the concept. The only issue is that $routeChangeError is not recognizing when something goes wrong because you are not properly rejecting the promise.

To fix this, consider wrapping your $http call with a promise using AngularJS' $q library. Make sure to reject the promise if the response is not what you expect:

this.isLoggedIn = function() {
        var deferred = $q.defer();
        var promise = $http.get('/loggedin');
        promise.then(function(user) {
            if(user === 0 || user === '0'){ 
                 deferred.reject(user);
            }
            deferred.resolve(data);
        },
        function(error) {
            deferred.reject(error);
        });

        return deferred.promise;
}

If you prefer, you can also choose to throw an error instead of rejecting the promise.

Answer №2

When you return false from a promise, it does not result in rejection. In such cases, the router assumes that the resolve was successful. To properly handle this scenario, you should reject the promise instead by throwing an error:

this.isLoggedIn = function(){
    var promise = $http.get('/loggedin');

    promise.then(function(user){
        if(user === 0 || user === '0'){
            //Invalid request
            console.log('Not a valid request');
            throw new Error('Not a valid request');
        } else {
            //Valid request.
            return user;
        }
    });

    return promise;
};

However, it is important to note that full security cannot be achieved in the browser. At best, you can only hide pages cosmetically. Users can always manipulate the browser using JavaScript directly. Therefore, avoid placing sensitive information on these pages and ensure that any data fetched is accessible only when the user is logged in.

Update

A more concise version of the solution utilizing promises rather than exceptions.

this.isLoggedIn = function(){
    return $http.get('/loggedin').then(function(user){
        if(user === 0 || user === '0'){
            //Invalid request
            console.log('Not a valid request');
            return $q.reject('Not a valid request');
        }
        return $q.resolve(user);
    });
};

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

Showing live JSON data in AngularJS

Receiving a JSON string from a web service, the content may differ depending on the request. Here are 2 JSON results: Result 1 [ { "Key": 1, "ID": 1, "applicationId": "1", "applicationName": "APP1" }, { "Key": 2, "ID": 1, ...

Having trouble selecting the clicked element after a successful Ajax call, especially when there are multiple elements with the same name

When dealing with multiple elements that share the same class name, I am attempting to target the 'clicked' element upon a successful Ajax return. <td data-name='tom' class="status"><a href="">click< ...

SPFx WebPart - Tabbed Interface

I am new to developing SPFX WebParts and currently working on creating a Tab WebPart. The HTML appears to be rendering correctly, but I'm facing issues with the Javascript functionality not firing as expected. Any assistance or guidance on how to prop ...

Guide on accessing the final value of a text file using JavaScript

My server side script outputs results in a txt file, where the values stored look like this: 1 2 5 7 10 In order to create a real-time progress bar, I need to fetch the last value from the file using an ajax request while updating the txt file with the l ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...

Initially receiving a 404 error, the GCloud AppEngine nodejs application eventually becomes successful with subsequent requests

While deploying a Node.js server (GraphQL) application on GCloud AppEngine standard environment, I am facing an issue where the first requests fail occasionally, but the subsequent ones (within 5 seconds) work fine. The configuration I am using is as follo ...

Tips for managing mouse over events in legends on highcharts

I have successfully implemented mouseover/mouseout event handling for donut slices. Please review my code below: http://jsfiddle.net/nyhmdtb8/6/ Currently, when I hover over a slice, it highlights that slice and greys out all others. Is it possible to ac ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

Mac terminal fails to recognize the given express command

Hi everyone, I'm fairly new to nodeJS and currently attempting to install express. I have successfully installed node and npm on my Max OSX(10.10.1) machine. However, I keep encountering the following error: -bash: express: command not found I' ...

SQL Example Demonstrating One to Many Relationship using UNION Clause

Currently working on a complex SQL query and need some assistance in constructing it all within a single SQL statement. The data is stored in a table with the following structure: +-----+-----+-----+-----+ | pid | did | src | val | +-----+-----+-----+--- ...

Is there a term in JavaScript that denotes an object that can be serialized into JSON format?

Can you help me find a term for basic objects that accentuates their simplicity? Particularly, objects that do not reference themselves and do not have any methods or bindings (i.e. JSON-serializable). The terms I am currently using are: "flat object" " ...

How to rotate text direction using JavaScript and CSS

Despite my extensive efforts, I have been unable to find a solution to a seemingly simple problem. In JavaScript, I have generated dynamic text using the following code: context.fillText('name', 10, 10, 20); Now, I need this text to be ori ...

Is it possible to insert HTML content as plain text into a div?

Currently, I have a code that extracts HTML stored in a string and places it into a div with the contenteditable attribute set to "true". However, I'm facing an issue where the HTML is being executed as part of the page instead of being treated as tex ...

Is it possible to utilize the `.apply()` function on the emit method within EventEmitter?

Attempting to accomplish the following task... EventEmitter = require('events').EventEmitter events = new EventEmitter() events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3']) However, it is ...

This error message 'React Native _this2.refs.myinput.focus is not a function' indicates that

When working with React-Native, I encountered a specific issue involving a custom component that extends from TextInput. The code snippet below demonstrates the relevant components: TextBox.js ... render() { return ( <TextInput {...this.props} ...

AngularJS application failing to initialize without a module being included

I'm feeling a bit lost when it comes to angularjs and I have a question about why my angularjs app is refusing to bootstrap without creating a module, even though egghead.io and other tutorials seem to suggest otherwise. Here's a snippet of my HT ...

The Angular controller fails to execute upon startup in the Ionic app

As a newbie to the Ionic Mobile Framework and Angular JS, I'm working on a login page for the first time. My goal is to navigate to the homepage only if the session has not expired when the login page launches. If the session has expired, then it shou ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

Customize your Bootstrap navbar dropdown to showcase menu items in a horizontal layout

I have been developing a new project that requires a navbar to be positioned at the center of the page, at the top. The current HTML code I am using is as follows... <div class="navbar navbar-inverse navbar-fixed-top center"> <div class="con ...