刚刚开始使用角度,我正尽力学习。我是SPA的新手,所以请耐心等待,并随时告诉我,我想做的事情是不可行的。我现在所困扰的是,在使用ui-router时如何保护我的路线?
我想做什么?
我不希望未登录用户访问的路由。
例如,
/ dashboard 应仅适用于 登录的用户。
我希望如此,如果用户未来登录时尝试访问/仪表板,他们就无法这样做。
我已经尝试了什么?
我尝试过使用此处的角度权限模块:https://github.com/Narzerus/angular-permission 问题是......我不太清楚如何使用它(也不是我正确使用它)。
目前发生了什么?
在我的登录控制器中,一旦用户提交了他们的用户名和密码,它就会对我的网络服务器进行/ POST。一旦得到结果,(无论目前是什么)我都将它重定向到/仪表板。
现在没有任何东西可以进入/仪表板,因为没有设置任何权限,但我(错误地)允许我看到仪表板。我可以(1)未经许可成功地重定向到仪表板,(2)未经许可访问/仪表板。
我的代码目前是什么样的?
controllers.js
var controllers = angular.module('controllers',[])
// Login Controller -- This handles the login page that the user can enter
// enter his username & password.
controllers.controller('loginController', function($scope, $state,$location, LoginService){
$scope.email = "";
$scope.password = ""
$scope.login = function(){
var data = ({email:"test", password: "ayylmao"})
LoginService.login(data).then(function(res){
console.log(res);
})
.catch(function(err){
console.log("ERROR!");
console.log(err);
$state.go('dashboard')
})
}
})
app.js
//Definition: The parent module
var myApp = angular.module('clipboardApp', ['services','controllers', 'permission','ui.router']);
//Code below taken from the angular-permission docs.
angular
.module('fooModule', ['permission', 'user'])
.run(function (PermissionStore, User) {
// Define anonymous permission)
PermissionStore
.definePermission('anonymous', function (stateParams) {
// If the returned value is *truthy* then the user has the permission, otherwise they don't.
//True indicates anonymous.
//Always returning true to indicate that it's anonymous
return true;
});
});
//This will be serving as the router.
myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
//By default go
$urlRouterProvider.otherwise('/home');
//Views are
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'loginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'views/dashboard.html',
controller: 'dashboardController',
data: {
permissions: {
except: ['anonymous'],
redirectTo: 'login'
}
}
});
});
答案 0 :(得分:1)
以下是安全路线的工作示例。在此示例中,任何状态都以app开头。将通过auth拦截器。 $ transitions.onBefore hook可以按如下方式使用以满足您的要求。
.run(($transitions, $state, $injector) => {
$transitions.onBefore({
to: 'app.**'
}, () => {
const $window = $injector.get('$window');
if (!$window.sessionStorage.getItem('user')) {
return $state.target('login', $state.transition.params());
}
return true
});
});