Only grant access to Angular view if user possesses the necessary cookie

How can I restrict access to a view in angular ui-router only if a cookie is active with the user's email address?

I am currently setting the cookie in a post request where I assign the cookie value to the user's email address.

Now, I want to ensure that users can only access a specific view if they have a cookie containing their username. How should I implement this restriction?

Here is how I set the cookie:

 FirstModule.controller('LoginController', function ($scope, $http, $cookies, $location) {
    $scope.sometext = {};

    $scope.LoginForm = function () {
        var data = {
            LoginEmail: $scope.sometext.LoginEmail
        };

        $http({
            url: 'http://localhost:8080/back-end/controller',
            method: "POST",
            data: data,
            headers: {'Content-Type': 'application/json'}

        }).then(function (response) {

            if (response.status === 200)
            //     $scope.sometext = "You are a valid member, please proceed to Mock Up Maker";
            $cookies.put('UserName', $scope.sometext.LoginEmail);
            $location.path('/download');
            // console.log($cookies);
        }).catch(function (response) {
            if (response.status === 400)
                $scope.sometext = "Hmm, it seems you are not registered, try again or register";
            else if (response.status === 404)
                $scope.sometext = "this is non a valid email address, please check email";
            else if (response.status === 500)
                $scope.sometext = "No API connection. Server side fail ";

            else $scope.sometext = "Server connection error, give it a second to establish connection then try again";
        });
    }
});

Setting up the router:

FirstModule.config(function ($stateProvider, $urlRouterProvider) {

    $stateProvider

    // route to show our basic form (/form)
        .state('form', {
            url: '/form',
            templateUrl: 'views/form.html',
            controller: 'formController'
        })

        // nested states
        // each of these sections will have their own view
        // url will be nested (/form/signup)
        .state('form.signup', {
            url: '/signup',
            templateUrl: 'views/form-signup.html'
        })

        // url will be /form/select
        .state('form.select', {
            url: '/select',
            templateUrl: 'views/form-select.html'
        })

        // url will be /form/type
        .state('form.type', {
            url: '/type',
            templateUrl: 'views/form-type.html'
        })


    // catch all route
    // send users to the form page
    $urlRouterProvider.otherwise('/form/signup');
});

Answer №1

To implement redirection based on a condition in your Angular application using ui-router, you can utilize the resolve property. Simply include the resolve field in your state definition and specify the condition that should be met. If the condition is not satisfied, you can redirect the user to a different state, such as the login state.

state('user', {
  url: '/',
  templateUrl: 'UserView.html',
  controller: 'UserViewController',
  resolve: {
    check: function($q, $cookies) {
      if ($cookies.get('UserName')){ //cookie to check
        return $q.resolve({});
      } else{
        return $q.reject({redirectState: 'loginState'}); 
      }
    }
  }
});

Add an error handler to capture any errors that occur during state transitions.

$rootScope.$on('$stateChangeError', function(evt, to, toParams, from, fromParams, error) {
  if (error.redirectState) {
    $state.go(error.redirectState);
  } 
})

Answer №2

Karim provided a solid answer that should be effective. However, it may be more beneficial to consider this as an intermediate step in the process.

An ideal solution would involve offering users a way to access the URL only if they have the necessary cookie set. This could mean deactivating the link or concealing it entirely. In my opinion, this is a more optimal approach.

To ensure the security and reliability of my application, I would prefer to implement both options. By disabling or removing the link/button, users will be unable to access the URL altogether. Additionally, using Router-Resolve can protect against savvy users who might attempt to access the link through alternative means. :)

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

Issue a cautionary alert to the user before finalizing an API project in Node.js

Consider the following scenario: A user calls an API. The API realizes it needs to overwrite something that was previously saved. To proceed and complete the operation, the user must confirm whether they want to overwrite with a 'yes' or &apos ...

Can you explain the purpose of using double colons before an expression variable in AngularJS?

Can you explain the use of double colons :: preceding an expression variable in AngularJS? Additionally, how does {{ firstName }} differ from {{ ::firstName }}? ...

Resolving the CORS preflight issue with Loopback API in Redux

My current setup involves a client application running on React-Redux and an API app on Loopback. During local testing, I have the client app on port 8080 and the server app on port 3000. While attempting to test Google OAuth (using the loopback-passport ...

.Internet Explorer text update problem

Encountering a problem specifically in IE (like always). I've managed to narrow down the issue I'm facing to a recursive script responsible for updating a tweet's timestamp. The script functions correctly, identifying all the date/time sta ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

Using a JavaScript file within a webpage that has already been loaded

Seeking assistance as I encounter a dilemma: providing code would be overwhelming, but perhaps someone can assist me in brainstorming a solution. Here's the issue: I have an index.php file with a div that dynamically loads (via jQuery .load()) another ...

Is the `ng-model` for the AngularStrap `bs-typeahead` component not accessible in the current scope?

I am encountering a problem with the ng-model value in an element that uses AngularStrap's bs-typeahead. It seems to not be accessible within the scope, but it works fine when accessed using {{ var }} in the HTML. Here is the HTML code: <input ty ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Experience screen sharing through WEBRTC without the need for any additional browser extensions

One question that I have is: Is it possible to implement screen sharing that works on a wide range of devices and browsers without the need for plugins or experimental settings? I have searched online and come across some plugins for Chrome, but I am look ...

What is the reasoning behind an empty input value being considered as true?

I am facing an issue with the following code that is supposed to execute oninput if the input matches the answer. However, when dealing with a multiplication problem that equals 0, deleting the answer from the previous calculation (leaving the input empt ...

Tips for extracting specific values from JavaScript using jQuery in ASP to be utilized in the C# code behind section

I want to extract the selected values from a multiselect jQuery and use them in the code behind in C#. The script sources can be found at the following link: https://github.com/nobleclem/jQuery-MultiSelect Below is the ASP code I am using: <div class ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

The window.onload event is failing to trigger on mobile devices, although it is functioning properly on desktop. (using react js

Thank you for taking the time. Now, let's dive into the main topic: I have a scenario where I need to execute one of two functions based on a boolean value at the start. The decision is made using window.onload. This code works perfectly on desktop b ...

Executing jQuery when the DOM is loaded in Angularjs

Seeking assistance with integrating jQuery into AngularJS for a project. I am relatively new to AngularJS and experiencing difficulty in firing jQuery on Dom Ready. Despite various attempts, the code does not seem to work as expected. I am currently using ...

Understanding the request URL in Ajax when receiving a response

How can the URL of a jQuery request be retrieved from the response received? Perhaps something like this: function retrieveUrlFromResponse(response, url){ requestUrl = url; } ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

When using ng-repeat with Angular ui-bootstrap and tabs, the new tab will not be selected if there are no existing tabs present

To showcase the problem I'm facing, please refer to this link: http://codepen.io/pietrofxq/pen/ZLLJdr?editors=1010 Click on "remove tabs" and then on "add tab" The challenge at hand involves using a loop with ng-repeat to display tabs. At times, the ...

The breeze is puzzled by the altered being, unable to identify it

I am currently working on a breeze implementation that involves displaying properties from a location object on the UI. However, when I make changes to some properties and attempt to save them, breeze does not recognize the entity as being changed. Here is ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

Issue with new Cookie not functioning properly when using Response.Redirect

When updating the cookie, the code is as follows: if (Request.Cookies["SSOPortalUser"] == null) { HttpCookie myCookieSSOPortalUser = new HttpCookie("SSOPortalUser"); // Set the cookie value. ...