jonsamwell/blog_examples

User can still access a route even when he/she has no proper Permission

Opened this issue · 1 comments

Hi,

While going through the code, I noticed that the code written in the routeChangeStart is not enough to protect the routes.

For instance, if a user is not logged in, the authorization service returns "loginRequired". Then, after that, if the user login successfully, he/she is being redirected to the page requested. However, a second check is required to make sure the user has the proper permission.

Do you see this?

Best regards
Bilal Haidar

Maybe a possible solution could be as follows:

.run([
"$rootScope",
"$location",
"$state",
bh.modules.auth.services.authorization.name,
function ($rootScope, $location, $state, authorization) {
var redirectTo;

        function calculateAuthorize(access) {
            // checks the authorization access for the user
            return authorization.authorize(access.loginRequired, access.permissions, access.permissionCheckType);
        };

        $rootScope.$on("$stateChangeStart", function (event, toState, toParams) {
            var authorized;

            if (redirectTo && toState.name !== bh.modules.auth.states.login.name) { // user logged in already
                authorized = calculateAuthorize(redirectTo.state.access); // logged in already ==> use redirectTo safely 
            } else if (toState && toState.access) {
                authorized = calculateAuthorize(toState.state.access); // user is challenged / authorization
            }

            if (authorized) { // serves both states without access property and with authorization calculated
                if (authorized === bh.modules.auth.enums.authorized.loginRequired) { // first time access, user needs to login
                    redirectTo = {
                        state: toState,
                        stateParams: toParams
                    };

                    event.preventDefault(); // call first
                    $state.go(bh.modules.auth.states.login.name); // change state
                } else if (authorized === bh.modules.auth.enums.authorized.notAuthorized) { // user is not authorized to access state
                    event.preventDefault(); // call first
                    $state.go(bh.modules.auth.states.notAuthorized.name); // change state
                } else if (authorized === bh.modules.auth.enums.authorized.authorized) { // use reaches here only if she logged in before => use redirectTo safely
                    var redirectToCopy = angular.copy(redirectTo);

                    redirectTo = undefined; // reset returnTo

                    event.preventDefault(); // call first
                    $state.go(redirectToCopy.state, redirectTo.stateParams);
                }
            }

            // else do nothing, just go to the next state
        });
    }]);