後,我有需要登錄一個mean.io應用中的一些路線和我用的是Mean.io:重定向到所需的路由認證
resolve: {loggedIn: checkLoggedin}.
如何回重定向到該路由用戶時經過身份驗證,以便用戶不會回到主頁'/'網址。
後,我有需要登錄一個mean.io應用中的一些路線和我用的是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中添加重定向到服務器的呼叫/登錄
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.';
});
};
}
])
package/users/server/routes/users.js中的
add /#!到重定向查詢
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
});
}
});