Javascript AngularJS-每个路由和控制器中的登录和身份验证
我有一个使用yeoman、grunt和bower创建的AngularJS应用程序 我有一个登录页面,其中有一个检查身份验证的控制器。如果凭据正确,我将重新路由到主页Javascript AngularJS-每个路由和控制器中的登录和身份验证,javascript,ruby-on-rails,angularjs,angularjs-authentication,Javascript,Ruby On Rails,Angularjs,Angularjs Authentication,我有一个使用yeoman、grunt和bower创建的AngularJS应用程序 我有一个登录页面,其中有一个检查身份验证的控制器。如果凭据正确,我将重新路由到主页 app.js 'use strict'; //Define Routing for app angular.module('myApp', []).config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider) {
app.js
'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/forgotPassword', {
templateUrl: 'forgotpassword.html',
controller: 'forgotController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController'
})
.otherwise({
redirectTo: '/login'
});
// $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);
angular.module('myApp').factory("page", function($rootScope){
var page={};
var user={};
page.setPage=function(title,bodyClass){
$rootScope.pageTitle = title;
$rootScope.bodylayout=bodyClass;
};
page.setUser=function(user){
$rootScope.user=user;
}
return page;
});
'use strict';
angular.module('myApp').controller('LoginController', function($scope, $location, $window,page) {
page.setPage("Login","login-layout");
$scope.user = {};
$scope.loginUser=function()
{
var username=$scope.user.name;
var password=$scope.user.password;
if(username=="admin" && password=="admin123")
{
page.setUser($scope.user);
$location.path( "/home" );
}
else
{
$scope.message="Error";
$scope.messagecolor="alert alert-danger";
}
}
});
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.run(function($rootScope, $location, loginService){
var routespermission=['/home']; //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});
'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}
else {
scope.msgtxt='incorrect information';
$location.path('/login');
}
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])
'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);
LoginControler.js
'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/forgotPassword', {
templateUrl: 'forgotpassword.html',
controller: 'forgotController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController'
})
.otherwise({
redirectTo: '/login'
});
// $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);
angular.module('myApp').factory("page", function($rootScope){
var page={};
var user={};
page.setPage=function(title,bodyClass){
$rootScope.pageTitle = title;
$rootScope.bodylayout=bodyClass;
};
page.setUser=function(user){
$rootScope.user=user;
}
return page;
});
'use strict';
angular.module('myApp').controller('LoginController', function($scope, $location, $window,page) {
page.setPage("Login","login-layout");
$scope.user = {};
$scope.loginUser=function()
{
var username=$scope.user.name;
var password=$scope.user.password;
if(username=="admin" && password=="admin123")
{
page.setUser($scope.user);
$location.path( "/home" );
}
else
{
$scope.message="Error";
$scope.messagecolor="alert alert-danger";
}
}
});
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.run(function($rootScope, $location, loginService){
var routespermission=['/home']; //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});
'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}
else {
scope.msgtxt='incorrect information';
$location.path('/login');
}
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])
'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);
在我的主页上
<span class="user-info">
<small>Welcome,</small>
{{user.name}}
</span>
<span class="logout"><a href="" ng-click="logoutUser()">Logout</a></span>
欢迎
{{user.name}
在loginController
中,我检查登录信息,如果成功,我在服务工厂中设置用户对象。我不知道这是否正确
我需要的是,当用户登录时,它在user对象中设置一些值,以便所有其他页面都可以获得该值
无论何时发生任何路由更改,控制器都应检查用户是否登录。如果没有,它应该重新路由到登录页面。此外,如果用户已经登录并返回页面,则应转到主页。控制器还应检查所有路由上的凭据
我听说过ng饼干,但我不知道如何使用它们
我看到的许多例子都不是很清楚,它们使用某种访问角色或其他东西。我不想那样。我只想要一个登录过滤器。
有人能给我一些想法吗?我的解决方案分为三个部分:用户的状态存储在服务中,在路由更改时观察运行方法,检查用户是否允许访问请求的页面,在主控制器中观察用户的状态是否更改
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
您应该创建一个服务(我将其命名为Auth
),它将处理用户对象,并有一个方法来知道用户是否已登录
服务:
.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})
.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
//submit
$scope.login = function () {
// Ask to the server, do your job and THEN set the user
Auth.setUser(user); //Update the state of the user in the app
};
}])
从应用程序.run
,您应该收听$routeChangeStart
事件。当路由改变时,它将检查用户是否已登录(isLoggedIn方法应处理此问题)。如果用户未登录,它将不会加载请求的路由,并将用户重定向到正确的页面(在您登录的情况下)
登录页面中应使用loginController
来处理登录。它应该只与Auth
服务交互,并将用户设置为已登录或未登录
登录控制器:
.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})
.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
//submit
$scope.login = function () {
// Ask to the server, do your job and THEN set the user
Auth.setUser(user); //Update the state of the user in the app
};
}])
从主控制器,您可以监听用户状态是否发生变化,并通过重定向作出反应
.controller('mainCtrl', ['$scope', 'Auth', '$location', function ($scope, Auth, $location) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);
您应该在两个主要站点中检查用户身份验证
- 当用户更改状态时,请使用
回调来检查它'$routeChangeStart'
- 当使用拦截器从angular发送$http请求时李>
resolve
属性。$stateProvider
示例:
.config([“$stateProvider”),函数($stateProvider){
$stateProvider
.国家(“禁止”{
/* ... */
})
.state(“签名”{
/* ... */
决心:{
access:[“access”,函数(access){return access.isAnonymous();}],
}
})
.州(“家”{
/* ... */
决心:{
access:[“access”,函数(access){return access.isAuthenticated();}],
}
})
.state(“管理员”{
/* ... */
决心:{
access:[“access”,函数(access){return access.hasRole(“ROLE_ADMIN”);},
}
});
}])
Access
根据当前用户权限解析或拒绝承诺:
.factory(“Access”、[“$q”、“UserProfile”、函数($q、UserProfile){
变量访问={
好:200,,
//“我们不知道你是谁,所以我们不能说你是否被授权访问
//无论此资源是否可用,请先登录“
未经授权:401,
//“我们知道您是谁,您的个人资料不允许您访问此资源”
禁区:403,
hasRole:功能(角色){
返回UserProfile.then(函数(UserProfile){
if(用户配置文件$hasRole(角色)){
返回Access.OK;
}else if(userProfile.$isAnonymous()){
返回$q.reject(访问权限未经授权);
}否则{
返回$q.reject(禁止访问);
}
});
},
hasAnyRole:函数(角色){
返回UserProfile.then(函数(UserProfile){
if(userProfile.$hasAnyRole(角色)){
返回Access.OK;
}else if(userProfile.$isAnonymous()){
返回$q.reject(访问权限未经授权);
}否则{
返回$q.reject(禁止访问);
}
});
},
isAnonymous:函数(){
返回UserProfile.then(函数(UserProfile){
if(userProfile.$isAnonymous()){
返回Access.OK;
}否则{
返回$q.reject(禁止访问);
}
});
},
isAuthenticated:函数(){
返回UserProfile.then(函数(UserProfile){
if(userProfile.$isAuthenticated()){
返回Access.OK;
}否则{
返回$q.reject(访问权限未经授权);
}
});
}
};
返回访问;
}])
UserProfile
复制当前用户属性,并实现$hasRole
、$hasAnyRole
、$isAnonymous
和$isAuthenticated
方法逻辑(加上$refresh
方法,稍后解释):
.factory(“用户配置文件”、[“身份验证”、函数(身份验证){
var userProfile={};
var clearUserProfile=函数(){
for(userProfile中的var prop){
if(userProfile.hasOwnProperty(prop)){
删除用户配置文件[prop];
}
}
};
var fetchUserProfile=函数(){
返回Auth.getProfile().then(函数(响应){
clearUserProfile();
返回angular.extend(userProfile、response.data、{
$refresh:fetchUserProfile,
$hasRole:函数(角色){
返回userProfile.roles.indexOf(role)>=0;
},
$hasAnyRole:函数(角色){
R
allowAnonymous: true
$stateProvider.state('login', {
url: '/login',
allowAnonymous: true, //if you move this, don't forget to update
//variable path in the force-page check.
views: {
root: {
templateUrl: "app/auth/login/login.html",
controller: 'LoginCtrl'
}
}
//Any other config
}
//I put it right after the main app module config. I.e. This thing:
angular.module('app', [ /* your dependencies*/ ])
.config(function (/* you injections */) { /* your config */ })
//Make sure there's no ';' ending the previous line. We're chaining. (or just use a variable)
//
//Then force the logon page
.run(function ($rootScope, $state, $location, User /* My custom session obj */) {
$rootScope.$on('$stateChangeStart', function(event, newState) {
if (!User.authenticated && newState.allowAnonymous != true) {
//Don't use: $state.go('login');
//Apparently you can't set the $state while in a $state event.
//It doesn't work properly. So we use the other way.
$location.path("/login");
}
});
});
angular.module('app',[])
.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl : 'app/views/login.html',
controller : 'YourController',
controllerAs : 'Your',
resolve: {
factory : checkLoginRedirect
}
})
}
function checkLoginRedirect($location){
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
if ($location.path() == "/"){
$location.path('dash');
}
return true;
}else{
// No user is signed in.
$location.path('/');
return false;
}
}
.run(function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User is signed in.');
} else {
console.log('No user is signed in.');
}
});
}