剛開始使用角度,我試圖儘可能快地學習。我對SPA很新,所以請耐心等待,並隨時告訴我,我想做什麼是不可行的。我現在堅持的是,如何在使用ui路由器時保護我的路線?如何使用ui路由器保護/處理認證路線?
我想要做什麼?
有些路線我不希望未登錄的用戶訪問。 例如,/家和/登錄都還好了匿名用戶。
/儀表板應該只對那些登錄。
我想它,如果用戶試圖訪問/儀表板在未來沒有被登錄,他們不能。
我已經試過了什麼?
我已經用在這裏發現了角,許可模塊嘗試:https://github.com/Narzerus/angular-permission 問題is..I'm不太清楚如何使用它(也不如果我使用它正確)。
目前發生了什麼?
在我的登錄控制器中,一旦用戶提交了他們的用戶名和密碼,它會向我的網絡服務器發送/ 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'
}
}
});
});