Browse Source

拦截http请求

git-svn-id: svn+ssh://10.10.101.21/source/platform/platform-b2b@3095 f3bf4e98-0cf0-11e4-a00c-a99a8b9d557d
yingp 10 years ago
parent
commit
fcf49d05bd

+ 10 - 3
src/main/java/com/uas/platform/b2b/filter/SecurityInterceptor.java

@@ -118,8 +118,12 @@ public class SecurityInterceptor extends AbstractSecurityInterceptor implements
 		// 判断session的用户信息是否与Authentication一致
 		if (user == null) {// 未登录则要求登录
 			logoutSession();
-			if (!SecurityConstant.AUTHENTICATION_URL.equals(httpRequest.getServletPath()))
-				httpResponse.sendRedirect(httpRequest.getContextPath() + SecurityConstant.LOGIN_URL);
+			if (!SecurityConstant.AUTHENTICATION_URL.equals(httpRequest.getServletPath())) {
+				if (httpRequest.getHeader("Accept").contains("application/json"))
+					httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+				else
+					httpResponse.sendRedirect(httpRequest.getContextPath() + SecurityConstant.LOGIN_URL);
+			}
 			return;
 		}
 		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
@@ -128,7 +132,10 @@ public class SecurityInterceptor extends AbstractSecurityInterceptor implements
 			logger.error(String.format("用户信息%s@%s与Authentication信息%s@%s不一致", user.getUserUU(), user.getIp(), authentication.getName(),
 					AgentUtils.getIp(httpRequest)));
 			logoutSession();
-			httpResponse.sendRedirect(httpRequest.getContextPath() + SecurityConstant.LOGIN_URL);
+			if (httpRequest.getContentType().contains("application/json"))
+				httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+			else
+				httpResponse.sendRedirect(httpRequest.getContextPath() + SecurityConstant.LOGIN_URL);
 			return;
 		}
 		if (user.isSys()) {// 超级用户无需验证权限

+ 290 - 290
src/main/webapp/resources/js/common/services.js

@@ -1,297 +1,297 @@
-define([ 'angular', 'toaster'], function(angular) {
-	'use strict';
-	angular.module('common.services', ['toaster' ]).factory('SessionService', function() {
-		return {
-			get : function(key) {
-				var storage = window.sessionStorage;
-				if(storage)
-					return sessionStorage.getItem(key);
-				return null;
-			},
-			set : function(key, val) {
-				var storage = window.sessionStorage;
-				if(storage)
-					return sessionStorage.setItem(key, val);
-				return null;
-			},
-			unset : function(key) {
-				var storage = window.sessionStorage;
-				if(storage)
-					return sessionStorage.removeItem(key);
-				return null;
-			},
-			getCookie: function(key) {
-				var storage = window.localStorage;
-				if(storage)
-					return storage.getItem(key);
-				else {
-					var val = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
-					if (val != null) {
-						return unescape(val[2]);
-					}
-					return null
-				}
-			},
-			setCookie: function(key, val) {
-				var storage = window.localStorage;
-				if(storage)
-					storage.setItem(key, val);
-				else {
-					var date = new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000);
-					document.cookie = key + "=" + escape(val) + ";expires=" + date.toGMTString();
-				}
-			},
-			removeCookie: function(key) {
-				var storage = window.localStorage;
-				if(storage)
-					storage.removeItem(key);
-				else {
-					var val = this.getCookie(key);
-					if (val != null) {
-						var date = new Date(new Date().getTime() - 1);
-						document.cookie = key + "=" + val + ";expires=" + date.toGMTString()
-					}
-				}
-			}
-		};
-	}).factory('BaseService', function() {
-		return {
-			getRootPath : function() {
-				var fullPath = window.document.location.href;
-				var path = window.document.location.pathname;	//返回当前部分路径
-				var pos = fullPath.indexOf(path);
-				return fullPath.substring(0, pos) + path.substring(0, path.substr(1).indexOf('/') + 1);
-			},
-			isNumber: function(n) {
-		        return !isNaN(parseFloat(n)) && isFinite(n);
-		    },
-		    /**
+define(['angular', 'toaster'], function(angular) {
+    'use strict';
+    angular.module('common.services', ['toaster']).factory('SessionService', function() {
+        return {
+            get: function(key) {
+                var storage = window.sessionStorage;
+                if (storage) return sessionStorage.getItem(key);
+                return null;
+            },
+            set: function(key, val) {
+                var storage = window.sessionStorage;
+                if (storage) return sessionStorage.setItem(key, val);
+                return null;
+            },
+            unset: function(key) {
+                var storage = window.sessionStorage;
+                if (storage) return sessionStorage.removeItem(key);
+                return null;
+            },
+            getCookie: function(key) {
+                var storage = window.localStorage;
+                if (storage) return storage.getItem(key);
+                else {
+                    var val = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
+                    if (val != null) {
+                        return unescape(val[2]);
+                    }
+                    return null
+                }
+            },
+            setCookie: function(key, val) {
+                var storage = window.localStorage;
+                if (storage) storage.setItem(key, val);
+                else {
+                    var date = new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000);
+                    document.cookie = key + "=" + escape(val) + ";expires=" + date.toGMTString();
+                }
+            },
+            removeCookie: function(key) {
+                var storage = window.localStorage;
+                if (storage) storage.removeItem(key);
+                else {
+                    var val = this.getCookie(key);
+                    if (val != null) {
+                        var date = new Date(new Date().getTime() - 1);
+                        document.cookie = key + "=" + val + ";expires=" + date.toGMTString()
+                    }
+                }
+            }
+        };
+    }).factory('BaseService', function() {
+        return {
+            getRootPath: function() {
+                var fullPath = window.document.location.href;
+                var path = window.document.location.pathname; // 返回当前部分路径
+                var pos = fullPath.indexOf(path);
+                return fullPath.substring(0, pos) + path.substring(0, path.substr(1).indexOf('/') + 1);
+            },
+            isNumber: function(n) {
+                return ! isNaN(parseFloat(n)) && isFinite(n);
+            },
+            /**
 			 * parse url params
 			 */
-		    parseParams: function(requestParams) {
-		    	var me = this;
-		        for (var key in requestParams) {
-		            if (key.indexOf('[') >= 0) {
-		                var params = key.split(/\[(.*)\]/), value = requestParams[key], lastKey = '';
-		                angular.forEach(params.reverse(), function(name) {
-		                    if (name != '') {
-		                        var v = value;
-		                        value = {};
-		                        value[lastKey = name] = me.isNumber(v) ? parseFloat(v) : v;
-		                    }
-		                });
-		                requestParams[lastKey] = angular.extend(requestParams[lastKey] || {}, value[lastKey]);
-		                delete requestParams[key];
-		            } else {
-		                requestParams[key] = me.isNumber(requestParams[key]) ? parseFloat(requestParams[key]) : requestParams[key];
-		            }
-		        }
-		        return requestParams;
-			}
-		};
-	}).factory('AuthenticationService', ['$http', 'SessionService', 'BaseService', 'SerializerUtil', function($http, SessionService, BaseService, SerializerUtil) {
-		var cacheSession = function() {
-			SessionService.set('authenticated', true);
-		};
-		var uncacheSession = function() {
-			SessionService.unset('authenticated');
-		};
-		var rootPath = BaseService.getRootPath();
-		return {
-			root : function() {
-				return rootPath;	
-			},
-			login : function(user) {
-				var payload = SerializerUtil.param(user);
-				var config = {
-					headers : {
-						'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
-					}
-				};
-				var login = $http.post(rootPath + "/j_spring_security_check", payload, config);
-				login.success(cacheSession);
-				return login;
-			},
-			logout : function() {
-				var logout = $http.get(rootPath + "/j_spring_security_logout");
-				logout.success(uncacheSession);
-				return logout;
-			},
-			isAuthed : function() {
-				return SessionService.get('authenticated');
-			},
-			getAuthentication : function() {
-				var request = $http.get(rootPath + '/authentication');
-				request.success(function(data){
-					if(data)
-						cacheSession();
-					else
-						uncacheSession();
-				});
-				request.error(uncacheSession);
-				return request;
-			},
-			reSignin : function(enUU) {
-				return $http.get(rootPath + '/authentication/' + enUU);
-			}
-		};
-	}]).factory('SnapshotService', ['$http', 'BaseService', function($http, BaseService) {
-		var rootPath = BaseService.getRootPath();
-		return {
-			getTodo : function(success) {
-				var request = $http.get(rootPath + '/snapshot/todo');
-				request.success(function(data){
-					success.call(null, data);
-				});
-			},
-			getNotice : function(count, success) {
-				var request = $http.get(rootPath + '/public/notice?page=1&count='+count);	//NoticeController.java
-				request.success(function(data){
-					success.call(null, data.content);
-				});
-			}
-		};
-	}]).factory('SerializerUtil', function() {
-		return {
-			/**
+            parseParams: function(requestParams) {
+                var me = this;
+                for (var key in requestParams) {
+                    if (key.indexOf('[') >= 0) {
+                        var params = key.split(/\[(.*)\]/),
+                        value = requestParams[key],
+                        lastKey = '';
+                        angular.forEach(params.reverse(),
+                        function(name) {
+                            if (name != '') {
+                                var v = value;
+                                value = {};
+                                value[lastKey = name] = me.isNumber(v) ? parseFloat(v) : v;
+                            }
+                        });
+                        requestParams[lastKey] = angular.extend(requestParams[lastKey] || {},
+                        value[lastKey]);
+                        delete requestParams[key];
+                    } else {
+                        requestParams[key] = me.isNumber(requestParams[key]) ? parseFloat(requestParams[key]) : requestParams[key];
+                    }
+                }
+                return requestParams;
+            }
+        };
+    }).factory('AuthenticationService', ['$http', 'SessionService', 'BaseService', 'SerializerUtil', function($http, SessionService, BaseService, SerializerUtil) {
+        var cacheSession = function() {
+            SessionService.set('authenticated', true);
+        };
+        var uncacheSession = function() {
+            SessionService.unset('authenticated');
+        };
+        var rootPath = BaseService.getRootPath();
+        return {
+            root: function() {
+                return rootPath;
+            },
+            login: function(user) {
+                var payload = SerializerUtil.param(user);
+                var config = {
+                    headers: {
+                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
+                    }
+                };
+                var login = $http.post(rootPath + "/j_spring_security_check", payload, config);
+                login.success(cacheSession);
+                return login;
+            },
+            logout: function() {
+                var logout = $http.get(rootPath + "/j_spring_security_logout");
+                logout.success(uncacheSession);
+                return logout;
+            },
+            isAuthed: function() {
+                return SessionService.get('authenticated');
+            },
+            getAuthentication: function() {
+                var request = $http.get(rootPath + '/authentication');
+                request.success(function(data) {
+                    if (data) cacheSession();
+                    else uncacheSession();
+                });
+                request.error(uncacheSession);
+                return request;
+            },
+            reSignin: function(enUU) {
+                return $http.get(rootPath + '/authentication/' + enUU);
+            }
+        };
+    }]).factory('SnapshotService', ['$http', 'BaseService', function($http, BaseService) {
+        var rootPath = BaseService.getRootPath();
+        return {
+            getTodo: function(success) {
+                var request = $http.get(rootPath + '/snapshot/todo');
+                request.success(function(data) {
+                    success.call(null, data);
+                });
+            },
+            getNotice: function(count, success) {
+                var request = $http.get(rootPath + '/public/notice?page=1&count=' + count); // NoticeController.java
+                request.success(function(data) {
+                    success.call(null, data.content);
+                });
+            }
+        };
+    }]).factory('SerializerUtil', function() {
+        return {
+            /**
 			 * @description 将元素值转换为序列化的字符串表示
 			 */
-			param : function(obj) {
-				var query = '', name, value, fullSubName, subName, subValue, innerObj, i, me = this;
-				for (name in obj) {
-					value = obj[name];
-					if (value instanceof Array) {
-						for (i = 0; i < value.length; ++i) {
-							subValue = value[i];
-							fullSubName = name + '[' + i + ']';
-							innerObj = {};
-							innerObj[fullSubName] = subValue;
-							query += me.param(innerObj) + '&';
-						}
-					} else if (value instanceof Object) {
-						for (subName in value) {
-							subValue = value[subName];
-							fullSubName = name + '[' + subName + ']';
-							innerObj = {};
-							innerObj[fullSubName] = subValue;
-							query += me.param(innerObj) + '&';
-						}
-					} else if (value !== undefined && value !== null)
-						query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
-				}
-				return query.length ? query.substr(0, query.length - 1) : query;
-			}
-		};
-	}).factory('ReportService', ['$http', 'BaseService', 'toaster', function($http, BaseService, toaster) {
-		var rootPath = BaseService.getRootPath();
-		return {
-			/**
-			 * 打印方法
-			 * enuu 企业的UU号
-			 * pageName 打印页面的名称
-			 * condition 单据的条件(格式:{tableName.propertyName}=value;当tableName含有'$'符号时将其换成'_'符号)
+            param: function(obj) {
+                var query = '',
+                name, value, fullSubName, subName, subValue, innerObj, i, me = this;
+                for (name in obj) {
+                    value = obj[name];
+                    if (value instanceof Array) {
+                        for (i = 0; i < value.length; ++i) {
+                            subValue = value[i];
+                            fullSubName = name + '[' + i + ']';
+                            innerObj = {};
+                            innerObj[fullSubName] = subValue;
+                            query += me.param(innerObj) + '&';
+                        }
+                    } else if (value instanceof Object) {
+                        for (subName in value) {
+                            subValue = value[subName];
+                            fullSubName = name + '[' + subName + ']';
+                            innerObj = {};
+                            innerObj[fullSubName] = subValue;
+                            query += me.param(innerObj) + '&';
+                        }
+                    } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
+                }
+                return query.length ? query.substr(0, query.length - 1) : query;
+            }
+        };
+    }).factory('ReportService', ['$http', 'BaseService', 'toaster', function($http, BaseService, toaster) {
+        var rootPath = BaseService.getRootPath();
+        return {
+            /**
+			 * 打印方法 enuu 企业的UU号 pageName 打印页面的名称 condition
+			 * 单据的条件(格式:{tableName.propertyName}=value;当tableName含有'$'符号时将其换成'_'符号)
 			 * title 单据标题
 			 */
-			print: function(enuu, pageName, condition, title) {
-				$http.get(rootPath + '/reports/path', {params: {enuu: enuu, pagename: pageName}})
-					.success(function(data){
-						if(data) {
-							data = eval(data);
-							var url = 'http://report.ubtob.com/report/?reportfile=' + data + '&rcondition=' + condition+'&enuu='+enuu;		
-							window.open(url, title + '-打印', 'width=' + (window.screen.width-10) + ',height=' + (window.screen.height*0.87) + ',top=0,left=0,toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
-						} else {
-							toaster.pop('error', '系统错误', '没有设置相应的报表');
-						}
-					}).error(function() {
-						toaster.pop('error', '系统错误', '获取报表名称失败');
-					});
-			}
-		}
-	}]).factory('VendorService', ['$http', '$resource', 'BaseService', function($http, $resource, BaseService){
-		var rootPath = BaseService.getRootPath();
-		return {
-			getCount: function(success){
-				var request = $http.get(rootPath + '/vendor/count');
-				request.success(function(data){
-					success.call(null, data);
-				});
-			},
-			customer: $resource('vendor/customer/:id', {}),
-			vendor: $resource('vendor/:id', {}),
-			userInfo :  $resource('vendor/userInfo/:uu', {}),
-			user : $resource('vendor/user', {})
-		};
-	}]).factory('AccountUser', ['$resource', function($resource) {
-		return $resource('account/user/:uu', {}, {
-			findUsers: {
-				url: 'account/user/customer/:uu',
-				method: 'POST',
-				isArray: true
-			},
-			addUserToVendor: {
-				url: 'account/user/bindUserToVendor/:uu',
-				method: 'POST',
-			},
-			findDistribute: {
-				url: 'account/user/findDistribute/:uu',
-				method: 'GET',
-				isArray: true
-			},
-			findVendor: {
-				url: 'account/user/findVendor/:uu',
-				method: 'GET',
-				isArray: true
-			},
-			findChooseVendor: {
-				url: 'account/user/removeVendor/:uu',
-				method: 'GET',
-				isArray: true
-			},
-			removeChooseVendor: {
-				url: 'account/user/removeVendor/:uu',
-				method: 'POST',
-				isArray: true
-			},
-			addVendor: {
-				url: 'account/user/addVendor/:uu',
-				method: 'POST'
-			},
-			update: {
-				method: 'PUT'
-			},
-			checkPassword: {
-				url: 'account/user/checkPassword',
-				method: 'GET'
-			},
-			updatePassword: {
-				url: 'account/user/updatePassword',
-				method: 'POST'
-			},
-			telEnable: {
-				url: 'account/user/telEnable',
-				method: 'GET'
-			},
-			emailEnable: {
-				url: 'account/user/emailEnable',
-				method: 'GET'
-			}
-		});
-	}]).factory('FeedBackService',['$resource', 'BaseService', function($resource, BaseService){
-		var rootPath = BaseService.getRootPath();
-		return $resource('serve/question', {}, {
-			//反馈问题
-			feedBackQuestion: {
-				url: rootPath + '/serve/question/feedback',
-				method: 'POST'
-			}
-		});
-	}]).filter('currency', function(){// 币别符号表示
-		return function(cur) {
-			if(cur == 'RMB') return '¥';
-			else if(cur == 'USD') return '$';
-			else if(cur == 'EUR') return '€';
-			else if(cur == null || cur == '') return '¥';
-			else return cur; 
-		};
-	});
+            print: function(enuu, pageName, condition, title) {
+                $http.get(rootPath + '/reports/path', {
+                    params: {
+                        enuu: enuu,
+                        pagename: pageName
+                    }
+                }).success(function(data) {
+                    if (data) {
+                        data = eval(data);
+                        var url = 'http://report.ubtob.com/report/?reportfile=' + data + '&rcondition=' + condition + '&enuu=' + enuu;
+                        window.open(url, title + '-打印', 'width=' + (window.screen.width - 10) + ',height=' + (window.screen.height * 0.87) + ',top=0,left=0,toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
+                    } else {
+                        toaster.pop('error', '系统错误', '没有设置相应的报表');
+                    }
+                }).error(function() {
+                    toaster.pop('error', '系统错误', '获取报表名称失败');
+                });
+            }
+        }
+    }]).factory('VendorService', ['$http', '$resource', 'BaseService', function($http, $resource, BaseService) {
+        var rootPath = BaseService.getRootPath();
+        return {
+            getCount: function(success) {
+                var request = $http.get(rootPath + '/vendor/count');
+                request.success(function(data) {
+                    success.call(null, data);
+                });
+            },
+            customer: $resource('vendor/customer/:id', {}),
+            vendor: $resource('vendor/:id', {}),
+            userInfo: $resource('vendor/userInfo/:uu', {}),
+            user: $resource('vendor/user', {})
+        };
+    }]).factory('AccountUser', ['$resource', function($resource) {
+        return $resource('account/user/:uu', {},
+        {
+            findUsers: {
+                url: 'account/user/customer/:uu',
+                method: 'POST',
+                isArray: true
+            },
+            addUserToVendor: {
+                url: 'account/user/bindUserToVendor/:uu',
+                method: 'POST',
+            },
+            findDistribute: {
+                url: 'account/user/findDistribute/:uu',
+                method: 'GET',
+                isArray: true
+            },
+            findVendor: {
+                url: 'account/user/findVendor/:uu',
+                method: 'GET',
+                isArray: true
+            },
+            findChooseVendor: {
+                url: 'account/user/removeVendor/:uu',
+                method: 'GET',
+                isArray: true
+            },
+            removeChooseVendor: {
+                url: 'account/user/removeVendor/:uu',
+                method: 'POST',
+                isArray: true
+            },
+            addVendor: {
+                url: 'account/user/addVendor/:uu',
+                method: 'POST'
+            },
+            update: {
+                method: 'PUT'
+            },
+            checkPassword: {
+                url: 'account/user/checkPassword',
+                method: 'GET'
+            },
+            updatePassword: {
+                url: 'account/user/updatePassword',
+                method: 'POST'
+            },
+            telEnable: {
+                url: 'account/user/telEnable',
+                method: 'GET'
+            },
+            emailEnable: {
+                url: 'account/user/emailEnable',
+                method: 'GET'
+            }
+        });
+    }]).factory('FeedBackService', ['$resource', 'BaseService', function($resource, BaseService) {
+        var rootPath = BaseService.getRootPath();
+        return $resource('serve/question', {},
+        {
+            // 反馈问题
+            feedBackQuestion: {
+                url: rootPath + '/serve/question/feedback',
+                method: 'POST'
+            }
+        });
+    }]).filter('currency', function() { // 币别符号表示
+        return function(cur) {
+            if (cur == 'RMB') return '¥';
+            else if (cur == 'USD') return '$';
+            else if (cur == 'EUR') return '€';
+            else if (cur == null || cur == '') return '¥';
+            else return cur;
+        };
+    });
 });

+ 16 - 0
src/main/webapp/resources/js/index/app.js

@@ -4,6 +4,22 @@ define([ 'toaster', 'charts', 'ngTable', 'common/services', 'service/Purc', 'ser
 	app.init = function() {
 		angular.bootstrap(document, [ 'myApp' ]);
 	};
+	app.config([ '$httpProvider', function($httpProvider) {
+		// http拦截
+		$httpProvider.interceptors.push('httpInterceptor');
+	}]);
+	app.factory('httpInterceptor', ['$window', '$q', '$injector', 'BaseService', function($window, $q, $injector, BaseService) {
+	    var httpInterceptor = {
+	        'responseError': function(response) {
+	            if (response.status == 401) {// UNAUTHORIZED
+	            	$window.location.href = BaseService.getRootPath() + "/signin";
+	                return $q.reject(response);
+	            }
+	            return $q.reject(response);
+	        }
+	    }
+	    return httpInterceptor;
+	}]);
 	app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
 		$urlRouterProvider.otherwise('/index');
 		$stateProvider.state('index', {