我在 mean.io 应用中有一些需要登录的路由,我使用
resolve: {loggedIn: checkLoggedin}.
当用户通过身份验证时,如何重定向回该路由,以便用户不会最终回到主“/”网址。
我这样做的方法是修改checkLoggedIn
函数,以便当它重定向到时/login
,它会传递一个查询字符串参数,该参数redirect
使用重定向到的路径调用。然后,在/login
路由中,添加以下函数:
app.route('/login')
.all(passport.authenticate('basic'), function(req, res) {
res.redirect(req.query.redirect);
});
填写来自 taylorthomas 的答案
在我的包裹路线中,将查询字符串添加到 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;
};
在 packages/users/public/controllers/meanUser.js 中添加重定向到对服务器的调用 /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.';
});
};
}
])
在 packages/users/server/routes/users.js 添加 /#! 到重定向查询
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
});
}
});