0

How to prevent direct HTML access in Angularjs 1.x?

code:

$stateProvider.state('home', {
   url: "/",
   templateUrl: 'views/home.html',
   title: 'Home',
   controller: 'homeCtrl as home',
})

In browser

http://example.com/views/home.html in this case, my HTML file rendered in the browser

4
  • why do you need that? Commented Dec 16, 2017 at 7:43
  • 3
    Developers! ... flag instead vote down for new users let them improve the questions please, they need to help voting not help at all! Commented Dec 16, 2017 at 7:44
  • Hi, welcome to stack overflow. Please refer the How to Ask link for more details on how to ask a question and update your question accordingly. Commented Dec 16, 2017 at 8:05
  • if you can improve the question you can either ask OP or do it yourself, closing is only when a post breaks site guidelines Commented Dec 16, 2017 at 8:06

2 Answers 2

1

From a .state, you can only prevent the user from accessing your state by using resolve and rejecting the promise

.state('home', {
        url: "/",
        templateUrl: 'views/home.html',
        title: 'Home',
        controller: 'homeCtrl as home',
        resolve: {
            isAutherized: function($q) {
                 // some logic goes here i guess...
                 return $q.reject("You shell not pass");
            }
        }
    })

This will fail transition, and by result will not access that specific HTML

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a good solution https://solidfoundationwebdev.com/blog/posts/require-authentication-for-certain-routes-with-ui-router-in-angularjs

In general you should listen to $stateChangeStart event and check whether you got specific privileges to your destination or not and prevent it from change by for example making redirect.

angular.module("myApp").run(function ($rootScope, $state, AuthService) {
  $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
    if (toState.authenticate && !AuthService.isAuthenticated()){
      // User isn’t authenticated
      $state.transitionTo("login");
      event.preventDefault(); 
    }
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.