I'm building a blog system using angularJS, and now trying to build a resource authorization flow that is simple to use for certain resources.
For example, I have the following states PROPOSALITEM
, PROPOSALITEM.VIEW
and PROPOSALITEM.EDIT
. PROPOSALITEM
is the parent states which resolve proposalItem by the provided :proposalId
for the child states. PROPOSALITEM.VIEW
is the view state which allows all users to access it, and PROPOSALITEM.EDIT
is the edit page which should allow only the proposal owner
to access.
I found that there's a beautiful structure to do the role
based authorization flow in angularJS from this article: Techniques for authentication in AngularJS applications. However what I need now is based on the ownership of the resource to decide if the user could access the route. And I have many resources like proposal
model which needs to be checked with owner authorization. All these models are provided with a owner
column. Is there any general solution to deal with this? (I don't want to put the authorization code for each model in its own resolve part because it's difficult to maintain)
/* Abstract states. Resolve proposalItem */
.state('PROPOSALITEM', {
abstract: true,
url: '/proposals/:proposalId',
template: '<ui-view/>',
resolve: {
proposalItem: function($stateParams, ProposalDataService) {
return ProposalDataService.getItem($stateParams.proposalId);
}
}
})
/* View states. Allows all users to access */
.state('PROPOSALITEM.VIEW', {
abstract: true,
url: '/view',
template: '...'
})
/* Edit states. Allows only the proposal owner */
.state('PROPOSALITEM.EDIT', {
url: '/edit',
template: '...',
resolve: {
proposalItem: function($q, proposalItem, UserDataService) {
var me = UserDataService.getMe();
// me: {
// _id: '1',
// name: '...'
// }
if (proposalItem.owner._id === me._id) {
// Authorized.
return proposalItem;
} else {
// Not authorized.
var deferred = $q.defer();
deferred.reject(ERROR_KEYS.NOT_AUTHORIZED);
return deferred.promise;
}
}
}
})