Reputation: 1323
I have some routes in a mean.io app that require login and I use the
resolve: {loggedIn: checkLoggedin}.
How do I redirect back to that route when the user is authenticated, so that the user don't end up back at the home '/' url.
Upvotes: 0
Views: 1355
Reputation: 1323
To fill out on the answer from taylorthomas
In my package routes, add a query string to the url
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
var path = $location.path();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
// $location.url('/auth/login'+'?redirect='+path);
$location.url('/auth/login').search('redirect', path);
}
});
return deferred.promise;
};
in packages/users/public/controllers/meanUser.js add the redirect to the call to the servers /login
angular.module('mean.users')
.controller('LoginCtrl', ['$scope', '$rootScope', '$http', '$location',
function($scope, $rootScope, $http, $location) {
// This object will be filled by the form
$scope.user = {};
var query = $location.search();
// Register the login() function
$scope.login = function() {
var url = '/login';
if (query.redirect) {
url = '/login?redirect=' + query.redirect;
}
$http.post(url, {
email: $scope.user.email,
password: $scope.user.password
})
.success(function(response) {
// authentication OK
$scope.loginError = 0;
$rootScope.user = response.user;
$rootScope.$emit('loggedin');
if (response.redirect) {
if (window.location.href === response.redirect) {
//This is so an admin user will get full admin page
window.location.reload();
} else {
window.location = response.redirect;
}
} else {
$location.url('/');
}
})
.error(function() {
$scope.loginerror = 'Authentication failed.';
});
};
}
])
in packages/users/server/routes/users.js add /#! to the redirect query
app.route('/login')
.post(passport.authenticate('local', {
failureFlash: true
}), function(req, res) {
if (req.query.hasOwnProperty('redirect')) {
// res.redirect(req.query.redirect);
var redirect = '/#!' + req.query.redirect;
res.send({
user: req.user,
redirect: redirect
});
} else {
res.send({
user: req.user,
redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false
});
}
});
Upvotes: 0
Reputation: 91
The way I did it was to modify the checkLoggedIn
function so that when it redirects to /login
, it passes a query string parameter called redirect
with the path to redirect to. Then, in the /login
route, add the following function:
app.route('/login')
.all(passport.authenticate('basic'), function(req, res) {
res.redirect(req.query.redirect);
});
Upvotes: 1