mellis481
mellis481

Reputation: 4148

AngularJS $location.path() not working for returnUrl

I have a SPA using AngularJS. I've just added security/authentication and everything appears to work nicely except redirecting after login if a returnUrl exists in the query string.

I have code in my app which will redirect to my login route if no user is authenticated. For example, if a user attempts to access http://localhost:55841/#/group/15 (which requires authentication), it will redirect to the login route with the following URL:

http://localhost:55841/#/login?returnUrl=%2Fgroup%2F15

Here is my login method which should redirect to the returnUrl route if it exists upon successful login:

var login = function (credentials) {
    return $http.post(baseUrl + 'api/login', credentials).then(function (response) {
        //do stuff
        var returnUrl = $location.search().returnUrl;
        if (returnUrl) {
            $location.path(returnUrl);
            //$location.path('/group/15');
        }
        $location.path('/');
    });
};

When I debug the login method, the value of returnUrl is /group/15 which is what I would expect, yet it navigates to the following URL:

http://localhost:55841/#/?returnUrl=%2Fgroup%2F15

Thanks in advance

Upvotes: 4

Views: 2457

Answers (1)

lin
lin

Reputation: 18392

Logical code error, check this solution and your branches.

var login = function (credentials) {
    return $http.post(baseUrl + 'api/login', credentials).then(function (response) {
        $rootScope.currentUser = response.data;
        $rootScope.$broadcast('currentUser', response.data);
        var returnUrl = $location.search().returnUrl;
        if (returnUrl) {
            console.log('Redirect to:' + returnUrl);
            $location.path(decodeURI(returnUrl)); // <- executed first, but not redirect directly.
            //$location.path('/group/15');
        } else { //else :)
           console.log('Redirect returnUrl not found. Directing to "/".');
           $location.path('/'); // <- only redirect if no returnUrl isset/true
       }
    }, function (response) {
        $rootScope.currentUser = null;
        $rootScope.$broadcast('currentUser', null);
        return $q.reject(response);
    });
};

Hint: You need to filter lot of URL in your "returnUrl". Think about a case where the last page was /. So its a endless loop.

Upvotes: 2

Related Questions