Is there a way I can include an additional route in this code?

I am in need of adding an admin user to my application. I have read that I need to separate routes in my app.js file, but I am having trouble finding an example of how to do this. Can someone please assist me in resolving this issue?

(function () {
    'use strict';

    angular
        .module('app', ['ngRoute', 'ngCookies'])
        .config(config)
        .run(run);

    config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                controller: 'HomeController',
                templateUrl: 'home/home.view.html',
                controllerAs: 'vm'
            })

            .when('/login', {
                controller: 'LoginController',
                templateUrl: 'login/login.view.html',
                controllerAs: 'vm'
            })

            .when('/register', {
                controller: 'RegisterController',
                templateUrl: 'register/register.view.html',
                controllerAs: 'vm'
            })

            .when('/admin', {
                controller: 'AdminController',
                templateUrl: 'admin/admin.view.html',
                controllerAs: 'vm'
            })

            .otherwise({ redirectTo: '/login' });
    }

    run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
    function run($rootScope, $location, $cookies, $http) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookies.getObject('globals') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;
        }

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in and trying to access a restricted page
            var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            var loggedIn = $rootScope.globals.currentUser;
            if (restrictedPage && !loggedIn) {
                $location.path('/login');
            }
        });
    }

})();

Answer №1

Check out this gist

The key is to associate specific restrictions with your route and validate authorization during page transitions for redirection if needed.

An exclusive AuthService can manage user details and permission data in a more organized manner, rather than scattering it across the run block.

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

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

If the session cannot be located, users will be redirected to the sign-in page

I have a small application that utilizes next-auth to display a signin/signout button based on the user's sign-in status. The buttons function correctly and redirect me to the signin page when clicked. However, I am wondering how can I automatically ...

I was directed to https://code.angularjs.org/ due to an error in the AngularJS injector

Currently, I am utilizing angularjs and gulp for real-time updates when making changes. However, each time I encounter an error, I am redirected to https://code.angularjs.org/ to read about the specific error. Instead of having to constantly click on the ...

Having trouble retrieving AJAX JSON response even after configuring content type and datatype. Parsing JSON using parseJSON results in an error, yet the JSON is still considered 'valid'

Currently, I am utilizing Laravel 4 for backend operations (although it doesn't appear to be the root cause of the issue), and my objective is to implement AJAX validation (to maintain dynamically populated dropdowns). To initiate the AJAX request, h ...

Unable to utilize the "fs" module within a Three.js application

After utilizing this base code to create an app with Three.js, I attempted to incorporate node's fs module for filesystem interaction. Despite adding const fs = require("fs") in my app.js file, the module could not be located. The error mess ...

Loading images in advance before webpage loads

Welcome friends! This is my first time asking a question here, so I hope I'm doing it right :) I'm looking to preload 3 images before the webpage fully loads so that they all appear simultaneously. Currently, the images load one after another and ...

What is the best way to input multiple values in a selectize field?

I attempted various solutions, but they were unsuccessful. <input id="select1" name="select1" type="text" class="select1 demo-default"/> var $select = $("#select1").selectize(); var selectize = $select[0].selectize; selectize.setValue(["test1","t ...

Switching from Vanilla JS to Vue.js, dealing with querySelector problems

Seeking assistance with transforming the following CodePen example to a Vue.js component: https://codepen.io/kjbrum/pen/qooQJJ While attempting to incorporate this.$nextTick for handling DOM manipulation, I'm encountering challenges in making it func ...

What is the best way to exclude a run.js file from Angular/Karma unit testing?

I am encountering an issue with a file named run.js. The content of the file is as follows: window.map.run([ '$rootScope', '$location', 'cache', 'userCache', function($rootScope, $location, cache, userCache) ...

Executing the AngularJS GET method inside the run block following the config phase

To properly display the first page (home), I need to make a request inside the RUN method in order to retrieve user data from an API. Here is the sequence of dispatches in my console: CONFIG RUN INIT GET USER DATA SIDEBAR HOME SUCCESS GET USER ...

Creating URL query parameters for a nested REST API: A step-by-step guide

I am faced with the challenge of constructing a POST request for a nested REST API (json object) dedicated to search functionality. I am unsure about how to format the URL parameters due to its complex nesting structure. How should I include question marks ...

ReactJS Hook call is not valid

Currently, I am delving into learning ReactJS and went through a helpful tutorial that provided me with a solid foundation in utilizing firebase for authentication and authorization on a webpage. I am now incorporating a Sign-In page template from material ...

What is the best way to prevent clicking and scrolling on a webpage?

I have added a "more" button to the bottom left of my website to reveal a menu. Upon clicking the button, the plus sign changes to an x. I would like the page to disable click and scroll actions when the plus sign is clicked. <div class="dropup"> ...

SelectBoxIt jquery plugin can be applied after the completion of populating options in the select element with AngularJS

Utilizing AngularJS, I am dynamically populating a select box with the code below: <select ng-model="department" ng-options="dept as dept.name for dept in departmentList" class="fancy"> <option value="">-- select an optio ...

Utilizing onClick with material-ui button - functioning flawlessly for a single interaction

I have been attempting to encapsulate a Material-UI button within another component. Everything seems to be working well, except for when I try to handle the onClick event - it appears to only work once. Here is an example that demonstrates the issue: ht ...

When using the setTimeout function to update the state, React useContext appears to be ineffective

As a newcomer to React, I have a question about refreshing the score in my card game within a forEach loop using setTimeout. While the state appears to update correctly, the DOM (Component overarching) does not reflect these changes. export function Refill ...

What is the best method to incorporate a JavaScript object key's value into CSS styling?

I am currently working on a project in React where I'm iterating over an array of objects and displaying each object in its own card on the screen. Each object in the array has a unique hex color property, and my goal is to dynamically set the font co ...

Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint. Below is the code snippet from my API: app.get("/orderdetails/add", (req, res) => { const { item__, Qty_Ordered, Unit_Price, ...

Refresh information and establish connections between new objects - Sequelize

I have developed a function within my Express route that is responsible for updating user information as well as their assigned role. The role itself is represented by another Sequelize Object, and I have established a one-to-many relationship between the ...