What is the best location for implementing role-based authentication in a MeanJS application?

I am working with a meanJS starter template that includes a yeoman generator. I'm trying to figure out where I can add specific permissions to my modules. For example,

'use strict';

// Configuring the Articles module
angular.module('adminpanel').run(['Menus',
    function(Menus) {
        // Set top bar menu items
        //Menus.addMenuItem('topbar', 'admin panel', 'adminpanel/', 'adminpanel');

        Menus.addMenuItem('topbar', 'Admin Panel', 'adminpanel', 'dropdown', '/buildings(/create)?');
        Menus.addSubMenuItem('topbar', 'adminpanel', 'List Collections', 'adminpanel/collections');
    }
]);

and when it comes to routes: 'use strict';

//Setting up route
angular.module('adminpanel').config(['$stateProvider',
    function($stateProvider) {
        // Admin panels state routing
        $stateProvider.
        state('listCollections', {
            url: '/adminpanel/collections',
            templateUrl: 'modules/adminpanels/views/list-collections.client.view.html'
        }).
        state('showCollection', {
            url: '/adminpanel/collections/:collectionName',
            templateUrl: 'modules/adminpanels/views/show-collection.client.view.html'
        }).
        state('showCollectionItem', {
            url: '/adminpanel/collections/:collectionName/:itemId',
            templateUrl: 'modules/adminpanels/views/show-item.client.view.html'
        });
    }
]);

Are these the appropriate places to implement role-based authentication on the client side, while also taking measures on the server-side (which I have already done)?

Does anyone know how I can incorporate an option like 'admin.hasPermission' into the Menus.(some function) without causing any issues? Any recommended resources for this type of customization?

Thank you for your assistance!

Answer №1

In my opinion, it is not wise to have authentication and authorization code on both the client side and server side. It is best practice to keep them only on the server side.

By having your authentication and authorization code on the client side as well, you are essentially exposing your mechanisms to anyone who can access the client. This could potentially lead to security vulnerabilities that attackers could exploit on both the client and server sides.

I strongly believe that authentication and authorization logic should be strictly limited to the server side. This way, if I were to go up against a skilled individual, it would at least make their task more challenging.

If you absolutely must have some form of validation on the client side, one approach could be to create a wrapper around the $http service. This wrapper could maintain a list of permissions for different roles, and all AJAX requests would need to go through this wrapper where you can check if they are allowed. If the request is permitted, you can proceed with the $http call, otherwise, an error can be thrown.

Answer №2

If you are using version 0.4.0, there is a new feature in the client config that allows you to control the visibility of menu entries:

By setting isPublic: false and defining a specific roles array, you can restrict access to certain users:

    // Example of adding a dropdown listCollections item
    Menus.addSubMenuItem('topbar', 'adminpanel', {
        title: 'listCollections',
        isPublic: false,
        roles:['admin'],
        state: 'adminpanel.listCollections'
    });

The logic for this implementation can be found in the core module (menu.client.services.js):

// Function for determining rendering decision 
    var shouldRender = function(user) {
        if (user) {
            if (!!~this.roles.indexOf('*')) {
                return true;
            } else {
                for (var userRoleIndex in user.roles) {
                    for (var roleIndex in this.roles) {
                        if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
                            return true;
                        }
                    }
                }
            }
        } else {
            return this.isPublic;
        }

        return false;
    };

You may want to explore version 0.4.0 or take a closer look at the code to implement this feature yourself.

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

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...

Creating an array of a specific field within a JSON string using the collect() method of objx is a straightforward process

Here is the JSON string I am working with: var data = [{"first":"3","second":"1"},{"first":"5","second":"5"},{"first":"7","second":"1"}]; Currently, I am using the following code - objx(data).collect("first") I am expecting to receive an array like [3 ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

What is the procedure for modifying the filter column position within a ui-grid interface?

Currently utilizing ui-grid in my ongoing project. Trying to relocate the filtering field above the ui-grid, similar to this example: https://i.sstatic.net/hRmIX.png Wondering if it is feasible to achieve this layout? ...

Implementing Dropzone in an Angular MVC5 project

For more information about dropzone, visit this link I am currently implementing dropzone as my file upload handler with the combination of angularjs and MVC5. The challenge I'm facing is getting the Http post request to go from the angularjs servic ...

Retrieve the value within the $scope when making an HTTP get request, but ensure it is only called once the client code has

On the controller page Expense.js: $scope.getPagedDataAsync = function (pageSize, page) { $scope.largeLoad = todoService.initialize(); todoService.getDataAsync(); $scope.setPagingData($scope.largeLoad, page, pageSize) ...

Ways to eliminate a specific Chip from Autocomplete outside of material UI

Seeking assistance with displaying selected values as <Chip /> outside of the <TextField /> in <Autocomplete />. The issue lies in deleting these chips and updating the selected prop within <Autocomplete />. Any suggestions or solut ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

PHP: variables malfunctioning post implementation of "if" statement

Recently, I encountered a strange issue while working on a database processor. After processing the login information, the variables containing the data seemed to disappear and any subsequent actions within the "if" statement, which verified the login info ...

Issue with ng-repeat causing input inside repeater to become blurry in AngularJS

I'm facing a similar issue as the one discussed here: https://groups.google.com/forum/#!msg/angular/eB19TlFHFVE/Rlh--XImXeYJ Here's the fiddle link: http://jsfiddle.net/KGu9n/25/ The problem I'm encountering is that my save function is tri ...

Using jQuery to assign a specific value to all select boxes

I am facing a challenge where I need to change the values of all select boxes on my page to a specific number. Here is the HTML structure: <select> <option value="-1" <option value="55">ENABLE</option> <option value= ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

What is the best way to integrate JavaScript with my HTML command box?

I'm having some trouble with an HTML command box that is supposed to execute commands like changing stylesheets and other tasks. I thought I had everything set up correctly, but it doesn't seem to be working at all. Below is the HTML code with th ...

Animating Page Transitions using Angular 2.0 Router

Seeking to implement animated transitions for new components using the onActivate method in Angular 2. A Plunk has been set up to demonstrate the issue at hand: http://plnkr.co/FikHIEPONMYhr6COD9Ou Here is an example of the onActivate method within a pag ...

trouble concerning the responsiveness of a jQuery popup

Hello, I am trying to create a responsive login popup using jQuery but have been struggling for a week. Below is the code snippet that I have been working on. Any help or guidance would be greatly appreciated. //scriptLogin.js archive $(document).ready ...

Vue.js and axios causing an empty array after the page is refreshed

As a newcomer to coding and using vue cli, along with my limited English skills, I apologize if I am unable to articulate the issue clearly. However, I am reaching out to the community for assistance. The code snippet below is from store.js where I fetch ...

Exploring component method variables with Jest testing

Imagine a scenario where there is a class component with the following structure: export class Math extends React.Component { ... someComponentMethod = numb => { const sample = numb * 10 ... const result = numb -5 ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Tips for concealing a tab upon selecting an option from a dropdown menu

<ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#song">Song</a></li> <li id="image-tab"><a href="#image" data-toggle="tab">Image</a></li> </ul> <div class="tab-cont ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...