Wednesday 6 March 2019

javascript - AngularJs and Angular-UI-Router routes permissions



I'm facing an issue on how to implement route restrictions based on remote data gotten from the server.



Suppose I have the following config file:



angular.module('myApp')
.config(['$stateProvider', function($stateProvider) {

$stateProvider
.state('post', {
url: '/post/:post_id',
abstract: true,
[...]
})
.state('post.view', {
url: '/view'
[...]
})
.state('post.edit', {
url: '/edit'
[...]
})

}]);


The requirements for my application are:




  • A post has an owner (creator of the post) and its domain may be public or private.


  • If the domain is public, every user will be able to see the post (entering state post.view), and, if not (domain is private), only the owner will be able to see it.


  • The post.edit state is only accessible to the owner.




To do this, what is the best approach?



I was thinking of having a resolve promise that fetches the data from the server (post's domain and correspondent user role), performs the required checks and returns accordingly (promise resolved or rejected).



But then, how would I redirect the user to a correct state if he is not authorized? For example, a common user trying to access the post.edit state should be redirected to the post.view state, if the post's domain is public... But if the post's domain is private, an unauthorized access page should be presented. Is it a good approach to do this directly on the resolve? What are the alternatives?


Answer



Have a look at this great tutorial on routing authorization based on roles:



role based authorization



Also have a look at this stackoverflow answer, here there is conditional routing based on login, you can use the same logic of roles for your purpose,



Ui-router, routes based on permission


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...