Access to an angular view in AngularJS and Django is restricted to authenticated users only

I am currently using AngularJS, Django Rest Framework, and Django in my project. I want to prevent anonymous users from accessing a specific view in AngularJS. While the rest framework restricts anon user actions in the AngularJS view, it still allows access, which I want to avoid. Essentially, I need to implement login_required functionality similar to Django in my AngularJS routes.

var app = angular.module('mostAwesomeApp', ['restangular', 'ngRoute'])

app.config(function($routeProvider){
    var base_dir = STATIC_URL + 'js/ng-coolest-app-ever/templates/';

    $routeProvider.when('/',
        {
            templateUrl: base_dir + 'list.html',
            controller: 'listViewCtrl'
        })
        .when('/edit/:pk',{
            templateUrl: base_dir + 'update.html',
            controller: 'editCtrl'
        })
})

// Any user can access this controller/view
app.controller('listViewCtrl', function($scope){
    $scope.doSomethingAwesome = function(){//doing something awesome}
})
// Only authenticated users should be able to access this controller and its view
app.controller('editCtrl', function($scope){
    $scope.onlyAuthedUsersCanDoAndSee = function(){ 
        // doing something awesome for authed peeps}
    }
})
<div ng-app='mostAwesomeApp'>
    // The problem lies here. If using ng-view, I cannot simply use Django's if user.auth... statements to control what an anonymous user can or cannot see 
    <ng-view></ng-view>
</div>

I have been considering passing the user status into a JavaScript variable and making it global for all my apps. Then, I would just check this variable for any application that requires special treatment. It works, but doesn't seem like the most elegant solution.

Answer №1

To ensure that only authenticated users can access certain views, you can utilize the resolve method of $routeProvider in AngularJS. By checking for a logged-in user before the view is loaded, you can trigger an event that redirects unauthenticated users to a login page.

$routeProvider.when('/edit/:pk',{
        templateUrl: base_dir + 'update.html',
        controller: 'editCtrl',
        resolve: {
             currentUser: function(MyUserAuthService, $rootScope) {
                 var u = MyUserAuthService.getCurrentUser();
                 if (u === null) $rootScope.$broadcast('noauth');
                 return u;
             }
        }
    })

app.run(function($rootScope, $location) {
    $rootScope.$on('noauth', function() {
         $location.path('/loginpage');
    });
});

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

Calculate the percentage using JavaScript, then convert the percentage back to the target value

In one place, I am determining the percentageDifference by adding the baseValue and targetValue. However, in another location, I am calculating the targetValue using the baseValue and percentageDifference. The problem I encounter is that the result of the ...

"Mastering the art of patience: Delaying execution until an animation completes using

When attempting to create an infinite loop for a carousel with a click event on a specific div to center it at a desired position, I encountered an issue. If the clicked item is more than one position away from the center, an unexpected effect occurs that ...

jQuery Issue - Clash between multiple menus sharing the same class

Hey there! I'm currently diving into the world of jQuery and encountering an issue with my menu. Whenever I click on a menu item with either the "tm-nav-vertical" or "tm-nav-horizontal" class, it removes the .active class from the initial menu item. I ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Preventing Copy and Paste function in WKWebView - A Guide

I am seeking a solution to deactivate the callout menu that appears when an element is long-tapped in a web view: https://i.sstatic.net/TiWsY.png Despite various answers available, like this one, none seem to be effective. It's unclear whether the t ...

Troubleshooting: CakePHP 3 beforeRender() function causing conflicts with global variables in JSON view

I'm facing an issue with my CakePHP 3.3.9 application. The problem arises when I try to send an ajax get request to the action, it simply doesn't work. I am utilizing a "prefix route" in this case. Despite going through numerous posts on handling ...

Encountered issue while initializing object from controller in AngularJS

Here is the demonstration on how the fiddle appears: var app = angular.module('testApp', []); app.controller = angular.('testAppCtrl', function ($scope) { $scope.vehicle = { type: 'car', color: 're ...

Is it possible for me to determine the quantity of lines present in the text without any

I have a user-input field where individuals can enter information. The input can range from no information at all to as little as a single word or unlimited characters. However, my focus is on handling cases where the text exceeds three lines. To address ...

What is the best way to retrieve attributes from a through table using a query?

I am in the process of creating a straightforward shopping cart system. My structure includes a Cart model, a Product model, and a connection table called CartItems. Here are the associations: models.Cart.belongsToMany(models.Product, { through: 'Car ...

Function not executed right away

One of the functions I have is called showLoading(). This function is responsible for displaying a spinner by adding a specific class to the body: function showLoading(){ //console.log("show loading"); loading = true; $("body").addClass("loadi ...

The cookie's expiration time is being set to 1 hour, rather than the specified maxAge duration

My file contains a cookie that consistently sets to 1 hour as the default, even when I specify a maxAge of 12 seconds. res.cookie("my-cookies", req.body.id_token, {maxAge: 12000, httpOnly: false}); ...

How can HTML5 geolocation be utilized to provide real-time latitude and longitude coordinates for integration with the Google Maps API?

I am currently working on a project where I need to dynamically fetch longitude and latitude values from the browser geolocation and then include them in the options array for the Google Maps API. Here is the code snippet I am using: function initMap(){ ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

The issue of AngularJS routeProvider not redirecting properly

On my index page, I have the following code: <!DOCTYPE html> <html ng-app="libraryApp"> <head> <meta charset="UTF-8"> <title>Angular Library</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1. ...

What are the best scenarios to utilize objects.raw() in Django?

As someone who is still relatively new to Python, I have noticed that both Entries.objects.raw("SELECT * FROM register_entries") and Entries.objects.filter() perform the same query. When would it be more advantageous to use one approach over the other ...

The MomentJS .format() function accurately displays the date as one day in the past in my local time

After using momentJs to display a date in a specific format in my UTC-4:30 timezone, I noticed that it skips a day. I am currently in the UTC-4:30 timezone. This issue does not occur in all timezones; it works correctly in the UTC-5:00 timezone. The fol ...

Using Bootstrap CSS and JavaScript specifically for carousel functionality

Custom Styles and Scripts for Bootstrap Carousel Using Carousel with Controls https://getbootstrap.com/docs/4.0/components/carousel/ <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner ...

How to Utilize useRef in React Hooks Without Direct Access to HTML Elements?

When working with React, I find myself in a situation where the HTML elements are being loaded from a separate repository that I monitor using pageLoaded. The updateHeader function contains more code for selecting HTML elements and manipulating attributes/ ...

How does an arrow function access parameters even when they have not been explicitly passed in?

The PhotosPage component is being rendered with the following route: <Route path="/settings/photos" component={PhotosPage} /> The component's signature includes: const PhotosPage = ({ uploadProfileImage, photos, profile, deletePhoto, ...

Styling in CSS is being applied to a button element within a React component,

Having trouble with a button styled with the className 'actions' The button displays the CSS styling from '.actions', but not '.actions button'. Both should be applied. This code snippet works for all elements ...