http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java b/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java deleted file mode 100644 index 1e9ffb0..0000000 --- a/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.standalone; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collection; - -import com.xasecure.biz.SessionMgr; -import com.xasecure.common.XAConstants; -import com.xasecure.entity.XXAuthSession; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.security.access.ConfigAttribute; -import org.springframework.security.access.SecurityConfig; -import org.springframework.security.access.vote.AffirmativeBased; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; - -@Component -public class StandaloneSecurityHandler { - public static final String AUTH_MANAGER_BEAN_NAME = "authenticationManager"; - public static final String ACCESS_DECISION_MANAGER_BEAN_NAME = "customAccessDecisionManager"; - - @Autowired - SessionMgr sessionMgr; - - public void login(String userName, String password, - ApplicationContext context) throws Exception { - // [1] Create AUTH Token - Authentication token = new UsernamePasswordAuthenticationToken( - userName, password); - - // [2] Authenticate User - AuthenticationManager am = (AuthenticationManager) context - .getBean(AUTH_MANAGER_BEAN_NAME); - token = am.authenticate(token); - - // [3] Check User Access - AffirmativeBased accessDecisionManager = (AffirmativeBased) context - .getBean(ACCESS_DECISION_MANAGER_BEAN_NAME); - Collection<ConfigAttribute> list = new ArrayList<ConfigAttribute>(); - SecurityConfig config = new SecurityConfig(XAConstants.ROLE_SYS_ADMIN); - list.add(config); - accessDecisionManager.decide(token, null, list); - - // [4] set token in spring context - SecurityContextHolder.getContext().setAuthentication(token); - - // [5] Process Success login - InetAddress thisIp = InetAddress.getLocalHost(); - sessionMgr.processStandaloneSuccessLogin( - XXAuthSession.AUTH_TYPE_PASSWORD, thisIp.getHostAddress()); - } -}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java deleted file mode 100644 index e3af85d..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.xasecure.security.web.authentication; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; -import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; - -import com.xasecure.common.JSONUtil; -import com.xasecure.view.VXResponse; - -public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler - implements LogoutSuccessHandler { - - @Autowired - JSONUtil jsonUtil; - - @Override - public void onLogoutSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws IOException, ServletException { - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - String jsonStr = ""; - try { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_OK); - vXResponse.setMsgDesc("Logout Successful"); - jsonStr = jsonUtil.writeObjectAsString(vXResponse); - - response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().write(jsonStr); - - if (logger.isDebugEnabled()) { - logger.debug("Log-out Successfully done. Returning Json : " +jsonStr); - } - - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java deleted file mode 100644 index 70b3df4..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.authentication; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.xasecure.common.JSONUtil; -import com.xasecure.common.PropertiesUtil; -import com.xasecure.view.VXResponse; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler; - -/** - * - * - */ -public class XAAuthFailureHandler extends -ExceptionMappingAuthenticationFailureHandler { - static Logger logger = Logger.getLogger(XAAuthFailureHandler.class); - - String ajaxLoginfailurePage = null; - - @Autowired - JSONUtil jsonUtil; - - public XAAuthFailureHandler() { - super(); - if (ajaxLoginfailurePage == null) { - ajaxLoginfailurePage = PropertiesUtil.getProperty( - "xa.ajax.auth.failure.page", "/ajax_failure.jsp"); - } - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication. - * ExceptionMappingAuthenticationFailureHandler - * #onAuthenticationFailure(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, - * org.springframework.security.core.AuthenticationException) - */ - @Override - public void onAuthenticationFailure(HttpServletRequest request, - HttpServletResponse response, AuthenticationException exception) - throws IOException, ServletException { - String ajaxRequestHeader = request.getHeader("X-Requested-With"); - if (logger.isDebugEnabled()) { - logger.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - String jsonResp = ""; - try { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("Bad Credentials"); - - jsonResp = jsonUtil.writeObjectAsString(vXResponse); - response.getWriter().write(jsonResp); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - - if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) { -// if (logger.isDebugEnabled()) { -// logger.debug("Forwarding AJAX login request failure to " -// + ajaxLoginfailurePage); -// } -// request.getRequestDispatcher(ajaxLoginfailurePage).forward(request, -// response); - if (logger.isDebugEnabled()) { - logger.debug("Sending login failed response : " + jsonResp); - } - } else { -// super.onAuthenticationFailure(request, response, exception); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java deleted file mode 100644 index 426683d..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.authentication; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.xasecure.biz.SessionMgr; -import com.xasecure.common.JSONUtil; -import com.xasecure.common.PropertiesUtil; -import com.xasecure.entity.XXAuthSession; -import com.xasecure.view.VXResponse; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -import org.springframework.security.web.authentication.WebAuthenticationDetails; - -/** - * - * - */ -public class XAAuthSuccessHandler extends -SavedRequestAwareAuthenticationSuccessHandler { - static Logger logger = Logger.getLogger(XAAuthSuccessHandler.class); - - String ajaxLoginSuccessPage = null; - - @Autowired - SessionMgr sessionMgr; - - @Autowired - JSONUtil jsonUtil; - - public XAAuthSuccessHandler() { - super(); - if (ajaxLoginSuccessPage == null) { - ajaxLoginSuccessPage = PropertiesUtil.getProperty( - "xa.ajax.auth.success.page", "/ajax_success.html"); - } - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication. - * SavedRequestAwareAuthenticationSuccessHandler - * #onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, - * org.springframework.security.core.Authentication) - */ - @Override - public void onAuthenticationSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws ServletException, IOException { - - WebAuthenticationDetails details = (WebAuthenticationDetails) authentication - .getDetails(); - String remoteAddress = details != null ? details.getRemoteAddress() - : ""; - String sessionId = details != null ? details.getSessionId() : ""; - - boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName()); - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - - VXResponse vXResponse = new VXResponse(); - - if(!isValidUser) { - sessionMgr.processFailureLogin( - XXAuthSession.AUTH_STATUS_USER_NOT_FOUND, - XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(), - remoteAddress, sessionId); - authentication.setAuthenticated(false); - - vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED); - vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet for " + authentication.getName()); - - response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); - response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse)); - - // response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); - logger.info("Auth Succeeded but user is not synced yet for " - + authentication.getName()); - - } else { - - String ajaxRequestHeader = request.getHeader("X-Requested-With"); - if (logger.isDebugEnabled()) { - logger.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) { - // if (logger.isDebugEnabled()) { - // logger.debug("Forwarding AJAX login request success to " - // + ajaxLoginSuccessPage + " for user " - // + authentication.getName()); - // } - // request.getRequestDispatcher(ajaxLoginSuccessPage).forward(request, - // response); - - String jsonResp = ""; - try { - vXResponse.setStatusCode(HttpServletResponse.SC_OK); - vXResponse.setMsgDesc("Login Successful"); - - response.setStatus(HttpServletResponse.SC_OK); - jsonResp = jsonUtil.writeObjectAsString(vXResponse); - response.getWriter().write(jsonResp); - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - if (logger.isDebugEnabled()) { - logger.debug("Sending login success response : " + jsonResp); - } - clearAuthenticationAttributes(request); - } else { - String jsonResp = ""; - try { - vXResponse.setStatusCode(HttpServletResponse.SC_OK); - vXResponse.setMsgDesc("Login Successful"); - - response.setStatus(HttpServletResponse.SC_OK); - jsonResp = jsonUtil.writeObjectAsString(vXResponse); - response.getWriter().write(jsonResp); - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - if (logger.isDebugEnabled()) { - logger.debug("Sending login success response : " + jsonResp); - } - // super.onAuthenticationSuccess(request, response, - // authentication); - } - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java deleted file mode 100644 index 4c59519..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.authentication; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.xasecure.common.JSONUtil; -import com.xasecure.common.PropertiesUtil; -import com.xasecure.common.XAConfigUtil; -import com.xasecure.view.VXResponse; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; - - -/** - * - * - */ -public class XAAuthenticationEntryPoint extends -LoginUrlAuthenticationEntryPoint { - static Logger logger = Logger.getLogger(XAAuthenticationEntryPoint.class); - static int ajaxReturnCode = -1; - - @Autowired - XAConfigUtil configUtil; - - @Autowired - JSONUtil jsonUtil; - - public XAAuthenticationEntryPoint() { - super(); - if (logger.isDebugEnabled()) { - logger.debug("AjaxAwareAuthenticationEntryPoint(): constructor"); - } - - if (ajaxReturnCode < 0) { - ajaxReturnCode = PropertiesUtil.getIntProperty( - "xa.ajax.auth.required.code", 401); - } - } - - @Override - public void commence(HttpServletRequest request, - HttpServletResponse response, AuthenticationException authException) - throws IOException, ServletException { - String ajaxRequestHeader = request.getHeader("X-Requested-With"); - if (logger.isDebugEnabled()) { - logger.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - - String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : ""; - String servletPath = PropertiesUtil.getProperty("xa.servlet.mapping.url.pattern", "service"); - String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath; - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - try { - - VXResponse vXResponse = new VXResponse(); - - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("Authentication Failed"); - - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse)); - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - - if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) { - if (logger.isDebugEnabled()) { - logger.debug("commence() AJAX request. Authentication required. Returning " - + ajaxReturnCode + ". URL=" + request.getRequestURI()); - } - response.sendError(ajaxReturnCode, ""); - } else if(!(requestURL.startsWith(reqServletPath))) { - super.commence(request, response, authException); - } - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java deleted file mode 100644 index ca2b36b..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.filter; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import org.springframework.security.web.authentication.RememberMeServices; -import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter; - -/** - * - * - */ -@SuppressWarnings("deprecation") -public class MyRememberMeFilter extends RememberMeAuthenticationFilter { - - static Logger logger = Logger.getLogger(MyRememberMeFilter.class); - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter#afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() { - // TODO Auto-generated method stub - super.afterPropertiesSet(); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter#doFilter(javax.servlet.ServletRequest, - * javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, - FilterChain arg2) throws IOException, ServletException { - // TODO Auto-generated method stub - super.doFilter(arg0, arg1, arg2); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter#getRememberMeServices() - */ - @Override - public RememberMeServices getRememberMeServices() { - // TODO Auto-generated method stub - return super.getRememberMeServices(); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #onSuccessfulAuthentication(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, - * org.springframework.security.core.Authentication) - */ - @Override - protected void onSuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, Authentication authResult) { - super.onSuccessfulAuthentication(request, response, authResult); - // if (logger.isDebugEnabled()) { - logger.info("onSuccessfulAuthentication() authResult=" + authResult); - // } - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #onUnsuccessfulAuthentication(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, - * org.springframework.security.core.AuthenticationException) - */ - @Override - protected void onUnsuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, AuthenticationException failed) { - logger.error("Authentication failure. failed=" + failed, - new Throwable()); - super.onUnsuccessfulAuthentication(request, response, failed); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #setApplicationEventPublisher(org.springframework - * .context.ApplicationEventPublisher) - */ - @Override - public void setApplicationEventPublisher( - ApplicationEventPublisher eventPublisher) { - // TODO Auto-generated method stub - super.setApplicationEventPublisher(eventPublisher); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #setAuthenticationManager(org.springframework - * .security.authentication.AuthenticationManager) - */ - @Override - public void setAuthenticationManager( - AuthenticationManager authenticationManager) { - // TODO Auto-generated method stub - super.setAuthenticationManager(authenticationManager); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #setAuthenticationSuccessHandler(org.springframework - * .security.web.authentication.AuthenticationSuccessHandler) - */ - @Override - public void setAuthenticationSuccessHandler( - AuthenticationSuccessHandler successHandler) { - // TODO Auto-generated method stub - super.setAuthenticationSuccessHandler(successHandler); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.rememberme. - * RememberMeAuthenticationFilter - * #setRememberMeServices(org.springframework.security - * .web.authentication.RememberMeServices) - */ - @Override - public void setRememberMeServices(RememberMeServices rememberMeServices) { - // TODO Auto-generated method stub - super.setRememberMeServices(rememberMeServices); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java deleted file mode 100644 index ea3fd7c..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.filter; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import com.xasecure.biz.SessionMgr; -import com.xasecure.common.GUIDUtil; -import com.xasecure.common.HTTPUtil; -import com.xasecure.common.PropertiesUtil; -import com.xasecure.common.RequestContext; -import com.xasecure.common.UserSessionBase; -import com.xasecure.entity.XXAuthSession; -import com.xasecure.util.RestUtil; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.AnonymousAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.filter.GenericFilterBean; - -import com.xasecure.security.context.XAContextHolder; -import com.xasecure.security.context.XASecurityContext; - -public class XASecurityContextFormationFilter extends GenericFilterBean { - - static Logger logger = Logger - .getLogger(XASecurityContextFormationFilter.class); - - public static final String AKA_SC_SESSION_KEY = "AKA_SECURITY_CONTEXT"; - public static final String USER_AGENT = "User-Agent"; - - @Autowired - SessionMgr sessionMgr; - - @Autowired - HTTPUtil httpUtil; - - String testIP = null; - - public XASecurityContextFormationFilter() { - testIP = PropertiesUtil.getProperty("xa.env.ip"); - } - - /* - * (non-Javadoc) - * - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, - * javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - - try { - Authentication auth = SecurityContextHolder.getContext() - .getAuthentication(); - - if (auth instanceof AnonymousAuthenticationToken) { - // ignore - } else { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpSession httpSession = httpRequest.getSession(false); - - // [1]get the context from session - XASecurityContext context = (XASecurityContext) httpSession.getAttribute(AKA_SC_SESSION_KEY); - int clientTimeOffset = 0; - if (context == null) { - context = new XASecurityContext(); - httpSession.setAttribute(AKA_SC_SESSION_KEY, context); - } - String userAgent = httpRequest.getHeader(USER_AGENT); - if(httpRequest!=null){ - clientTimeOffset=RestUtil.getTimeOffset(httpRequest); - - } - // Get the request specific info - RequestContext requestContext = new RequestContext(); - String reqIP = testIP; - if (testIP == null) { - reqIP = httpRequest.getRemoteAddr(); - } - requestContext.setIpAddress(reqIP); - requestContext.setUserAgent(userAgent); - requestContext.setDeviceType(httpUtil - .getDeviceType(httpRequest)); - requestContext.setServerRequestId(GUIDUtil.genGUI()); - requestContext.setRequestURL(httpRequest.getRequestURI()); - - requestContext.setClientTimeOffsetInMinute(clientTimeOffset); - context.setRequestContext(requestContext); - - XAContextHolder.setSecurityContext(context); - - UserSessionBase userSession = sessionMgr.processSuccessLogin( - XXAuthSession.AUTH_TYPE_PASSWORD, userAgent); - - if(userSession!=null && userSession.getClientTimeOffsetInMinute()==0){ - userSession.setClientTimeOffsetInMinute(clientTimeOffset); - } - - context.setUserSession(userSession); - } - chain.doFilter(request, response); - - } finally { - // [4]remove context from thread-local - XAContextHolder.resetSecurityContext(); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java deleted file mode 100644 index 4d67a33..0000000 --- a/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - /** - * - */ -package com.xasecure.security.web.filter; - -import org.apache.log4j.Logger; -import org.springframework.security.web.authentication.RememberMeServices; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -public class XAUsernamePasswordAuthenticationFilter extends - UsernamePasswordAuthenticationFilter { - - static Logger logger = Logger - .getLogger(XAUsernamePasswordAuthenticationFilter.class); - - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication. - * AbstractAuthenticationProcessingFilter - * #setRememberMeServices(org.springframework - * .security.web.authentication.RememberMeServices) - */ - @Override - public void setRememberMeServices(RememberMeServices rememberMeServices) { - if (logger.isDebugEnabled()) { - logger.debug("setRememberMeServices() enter: rememberMeServices=" - + rememberMeServices.toString()); - } - super.setRememberMeServices(rememberMeServices); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java b/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java deleted file mode 100644 index e5ccaac..0000000 --- a/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java +++ /dev/null @@ -1,872 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.xasecure.service; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.TypeVariable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.xasecure.biz.XABizUtil; -import com.xasecure.common.ContextUtil; -import com.xasecure.common.DateUtil; -import com.xasecure.common.SortField.SORT_ORDER; -import com.xasecure.common.UserSessionBase; -import com.xasecure.common.XAConfigUtil; -import com.xasecure.common.MessageEnums; -import com.xasecure.common.RESTErrorUtil; -import com.xasecure.common.SearchCriteria; -import com.xasecure.common.SearchField; -import com.xasecure.common.SearchUtil; -import com.xasecure.common.SortField; -import com.xasecure.common.StringUtil; -import com.xasecure.common.db.BaseDao; -import com.xasecure.common.view.VList; -import com.xasecure.db.XADaoManager; -import com.xasecure.entity.XXAuthSession; -import com.xasecure.entity.XXDBBase; -import com.xasecure.entity.XXPortalUser; -import com.xasecure.view.VXDataObject; -import com.xasecure.view.VXLong; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import com.xasecure.security.handler.XADomainObjectSecurityHandler; -import com.xasecure.security.handler.Permission; - -public abstract class AbstractBaseResourceService<T extends XXDBBase, V extends VXDataObject> { - - public static final Logger logger = Logger - .getLogger(AbstractBaseResourceService.class); - - public static final int OPERATION_CREATE_CONTEXT = 1; - public static final int OPERATION_UPDATE_CONTEXT = 2; - - static HashMap<Integer, AbstractBaseResourceService<?, ?>> serviceList = new HashMap<Integer, AbstractBaseResourceService<?, ?>>(); - static List<AbstractBaseResourceService<?, ?>> preServiceList = new ArrayList<AbstractBaseResourceService<?, ?>>(); - protected Class<T> tEntityClass; - protected Class<V> tViewClass; - - protected String className; - protected String viewClassName; - protected String countQueryStr; - protected String queryStr; - protected final String distinctCountQueryStr; - protected final String distinctQueryStr; - - public List<SortField> sortFields = new ArrayList<SortField>(); - public List<SearchField> searchFields = new ArrayList<SearchField>(); - - @Autowired - XADaoManager daoManager; - - protected static final HashMap<Class<?>, String> tEntityValueMap = new HashMap<Class<?>, String>(); - static { - tEntityValueMap.put(XXAuthSession.class, "Auth Session"); - tEntityValueMap.put(XXDBBase.class, "Base"); - } - - BaseDao<T> entityDao; - - @Autowired - StringUtil stringUtil; - - @Autowired - protected XADaoManager daoMgr; - - @Autowired - protected SearchUtil searchUtil; - - @Autowired - protected RESTErrorUtil restErrorUtil; - - @Autowired - XADomainObjectSecurityHandler objectSecurityHandler; - - @Autowired - XABizUtil bizUtil; - - @Autowired - XAConfigUtil msConfigUtil; - - protected abstract void validateForCreate(V viewBaseBean); - - protected abstract void validateForUpdate(V viewBaseBean, T t); - - protected abstract T mapViewToEntityBean(V viewBean, T t, - int OPERATION_CONTEXT); - - protected abstract V mapEntityToViewBean(V viewBean, T t); - - public static void registerService( - AbstractBaseResourceService<?, ?> baseService) { - preServiceList.add(baseService); - } - - static public AbstractBaseResourceService<?, ?> getService(int classType) { - AbstractBaseResourceService<?, ?> service = serviceList.get(classType); - if (service == null) { - for (AbstractBaseResourceService<?, ?> myService : preServiceList) { - if (myService.getClassType() == classType) { - serviceList.put(myService.getClassType(), myService); - service = myService; - break; - } - } - } - - if (service == null) { - logger.error("Service not found for classType=" + classType, - new Throwable()); - } - return service; - } - - protected String getResourceName() { - - String resourceName = tEntityValueMap.get(tEntityClass); - if (resourceName == null || resourceName.isEmpty()) { - resourceName = "Object"; - } - return resourceName; - - // if (className.startsWith("M")) { - // return className.substring(1); - // } else if (className.startsWith("com.xasecure.entity.M")){ - // return className.substring(14); - // } - // return className; - } - - @SuppressWarnings("unchecked") - protected BaseDao<T> getDao() { - if (entityDao == null) { - entityDao = (BaseDao<T>) daoMgr.getDaoForClassName(tEntityClass - .getSimpleName()); - - } - return entityDao; - } - - protected T createEntityObject() { - try { - return tEntityClass.newInstance(); - } catch (Throwable e) { - logger.error("Error instantiating entity class. tEntityClass=" - + tEntityClass.toString(), e); - } - return null; - } - - protected V createViewObject() { - try { - return tViewClass.newInstance(); - } catch (Throwable e) { - logger.error("Error instantiating view class. tViewClass=" - + tViewClass.toString(), e); - } - return null; - } - - protected int getClassType() { - return bizUtil.getClassType(tEntityClass); - } - - protected int ownerRatingWeight; - - /** - * constructor - */ - @SuppressWarnings("unchecked") - public AbstractBaseResourceService() { - - Class klass = getClass(); - ParameterizedType genericSuperclass = (ParameterizedType) klass - .getGenericSuperclass(); - TypeVariable<Class<?>> var[] = klass.getTypeParameters(); - - if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { - tEntityClass = (Class<T>) genericSuperclass - .getActualTypeArguments()[0]; - tViewClass = (Class<V>) genericSuperclass.getActualTypeArguments()[1]; - } else if (var.length > 0) { - tEntityClass = (Class<T>) var[0].getBounds()[0]; - tViewClass = (Class<V>) var[1].getBounds()[0]; - } else { - logger.fatal("Cannot find class for template", new Throwable()); - } - if (tEntityClass != null) { - className = tEntityClass.getName(); - } - if (tViewClass != null) { - viewClassName = tViewClass.getName(); - } - - // Get total count of the rows which meet the search criteria - countQueryStr = "SELECT COUNT(obj) FROM " + tEntityClass.getName() - + " obj "; - queryStr = "SELECT obj FROM " + className + " obj "; - - distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM " - + tEntityClass.getName() + " obj "; - distinctQueryStr = "SELECT distinct obj FROM " + className + " obj "; - sortFields.add(new SortField("id", "obj.id",true,SORT_ORDER.ASC)); - registerService(this); - } - - // ---------------------------------------------------------------------------------- - // Create Operation - // ---------------------------------------------------------------------------------- - /** - * Create Entity object and populate it from view object. Used in create - * operation - */ - - protected void mapBaseAttributesToEntityBean(T resource, V viewBean) { - if (resource.getCreateTime() == null) { - resource.setCreateTime(DateUtil.getUTCDate()); - } - - resource.setUpdateTime(DateUtil.getUTCDate()); - - if (resource.getAddedByUserId() == null) { - resource.setAddedByUserId(ContextUtil.getCurrentUserId()); - } - - resource.setUpdatedByUserId(ContextUtil.getCurrentUserId()); - } - - protected T populateEntityBeanForCreate(T t, V viewBaseBean) { - mapBaseAttributesToEntityBean(t, viewBaseBean); - return mapViewToEntityBean(viewBaseBean, t, OPERATION_CREATE_CONTEXT); - } - - protected T preCreate(V viewBaseBean) { - validateGenericAttributes(viewBaseBean); - validateForCreate(viewBaseBean); - - T t = createEntityObject(); - t = populateEntityBeanForCreate(t, viewBaseBean); - return t; - } - - public V createResource(V viewBaseBean) { - T resource = preCreate(viewBaseBean); - - // object security - if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.CREATE)) { - throw restErrorUtil.create403RESTException(getResourceName() - + " access denied. classType=" + resource.getMyClassType() - + ", className=" + resource.getClass().getName() - + ", objectId=" + resource.getId()); - } - - bizUtil.updateCloneReferences(resource); - - resource = getDao().create(resource); - - V view = postCreate(resource); - return view; - } - - protected V postCreate(T resource) { - V view = populateViewBean(resource); - return view; - } - - // ---------------------------------------------------------------------------------- - // Read Operation - // ---------------------------------------------------------------------------------- - - protected T preRead(Long id) { - return null; - } - - public V readResource(Long id) { - // T resource = preRead(id); - - T resource = getDao().getById(id); - if (resource == null) { - // Returns code 400 with DATA_NOT_FOUND as the error message - throw restErrorUtil.createRESTException(getResourceName() - + " not found", MessageEnums.DATA_NOT_FOUND, id, null, - "preRead: " + id + " not found."); - } - - V viewBean = readResource(resource); - return viewBean; - } - - /** - * @param resource - * @return - */ - @SuppressWarnings("unchecked") - private V readResource(T resource) { - // object security - if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.READ)) { - - throw restErrorUtil.create403RESTException(getResourceName() - + " access denied. classType=" + resource.getMyClassType() - + ", className=" + resource.getClass().getName() - + ", objectId=" + resource.getId() + ", object=" - + resource.toString()); - } - - V viewBean = postRead(resource); - return viewBean; - } - - protected V postRead(T resource) { - V viewBean = populateViewBean(resource); - return viewBean; - } - - // ---------------------------------------------------------------------------------- - // Update Operation - // ---------------------------------------------------------------------------------- - - /** - * Populate Entity object from view object. Used in update operation - */ - protected T populateEntityBeanForUpdate(T t, V viewBaseBean) { - mapBaseAttributesToEntityBean(t, viewBaseBean); - return mapViewToEntityBean(viewBaseBean, t, OPERATION_UPDATE_CONTEXT); - } - - protected T preUpdate(V viewBaseBean) { - T resource = getDao().getById(viewBaseBean.getId()); - if (resource == null) { - // Returns code 400 with DATA_NOT_FOUND as the error message - throw restErrorUtil.createRESTException(getResourceName() - + " not found", MessageEnums.DATA_NOT_FOUND, - viewBaseBean.getId(), null, "preUpdate: id not found."); - } - validateForUpdate(viewBaseBean, resource); - - return populateEntityBeanForUpdate(resource, viewBaseBean); - } - - public V updateResource(V viewBaseBean) { - T resource = preUpdate(viewBaseBean); - - // object security - if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.UPDATE)) { - throw restErrorUtil.create403RESTException(getResourceName() - + " access denied. classType=" + resource.getMyClassType() - + ", className=" + resource.getClass().getName() - + ", objectId=" + resource.getId()); - } - - resource = getDao().update(resource); - V viewBean = postUpdate(resource); - return viewBean; - } - - protected V postUpdate(T resource) { - V view = populateViewBean(resource); - return view; - } - - // ---------------------------------------------------------------------------------- - // Delete Operation - // ---------------------------------------------------------------------------------- - protected T preDelete(Long id) { - T resource = getDao().getById(id); - if (resource == null) { - // Return without error - logger.info("Delete ignored for non-existent " + getResourceName() - + " id=" + id); - } - return resource; - } - - public boolean deleteResource(Long id) { - boolean result = false; - T resource = preDelete(id); - if (resource == null) { - throw restErrorUtil.createRESTException(getResourceName() - + " not found", MessageEnums.DATA_NOT_FOUND, id, null, - getResourceName() + ":" + id); - } - - // object security - if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.DELETE)) { - // throw 401 - logger.debug("OBJECT SECURITY"); - } - // Need to delete all dependent common objects like Notes and - // UserDataPref - bizUtil.deleteReferencedObjects(resource); - try { - result = getDao().remove(resource); - } catch (Exception e) { - logger.error("Error deleting " + getResourceName() + ". Id=" + id, - e); - - throw restErrorUtil.createRESTException(getResourceName() - + " can't be deleted", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id - + ", error=" + e.getMessage()); - } - - postDelete(resource); - - return result; - } - - protected void postDelete(T resource) { - - } - - // ---------------------------------------------------------------------------------- - // Validation - // ---------------------------------------------------------------------------------- - protected void validateGenericAttributes(V viewBaseBean) { - } - - // ---------------------------------------------------------------------------------- - // mapping view bean attributes - // ---------------------------------------------------------------------------------- - public V populateViewBean(T resource) { - V viewBean = createViewObject(); - populateViewBean(resource, viewBean); - mapEntityToViewBean(viewBean, resource); - return viewBean; - } - - protected V populateViewBean(T resource, V viewBean) { - mapBaseAttributesToViewBean(resource, viewBean); - // TODO:Current:Open: Need to set original and updated - // content - return viewBean; - } - - protected void mapBaseAttributesToViewBean(T resource, V viewBean) { - viewBean.setId(resource.getId()); - - // TBD: Need to review this change later - viewBean.setMObj(resource); - viewBean.setCreateDate(resource.getCreateTime()); - viewBean.setUpdateDate(resource.getUpdateTime()); - - Long ownerId = resource.getAddedByUserId(); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - - if (currentUserSession == null) { - return; - } - - if (ownerId != null) { - XXPortalUser tUser = daoManager.getXXPortalUser().getById( - resource.getAddedByUserId()); - if (tUser != null) { - if (tUser.getPublicScreenName() != null - && !tUser.getPublicScreenName().trim().isEmpty() - && !tUser.getPublicScreenName().trim() - .equalsIgnoreCase("null")) { - viewBean.setOwner(tUser.getPublicScreenName()); - } else { - if (tUser.getFirstName() != null - && !tUser.getFirstName().trim().isEmpty() - && !tUser.getFirstName().trim() - .equalsIgnoreCase("null")) { - if (tUser.getLastName() != null - && !tUser.getLastName().trim().isEmpty() - && !tUser.getLastName().trim() - .equalsIgnoreCase("null")) { - viewBean.setOwner(tUser.getFirstName() + " " - + tUser.getLastName()); - } else { - viewBean.setOwner(tUser.getFirstName()); - } - } else { - viewBean.setOwner(tUser.getLoginId()); - } - } - } - } - if (resource.getUpdatedByUserId() != null) { - XXPortalUser tUser = daoManager.getXXPortalUser().getById( - resource.getUpdatedByUserId()); - if (tUser != null) { - if (tUser.getPublicScreenName() != null - && !tUser.getPublicScreenName().trim().isEmpty() - && !tUser.getPublicScreenName().trim() - .equalsIgnoreCase("null")) { - viewBean.setUpdatedBy(tUser.getPublicScreenName()); - } else { - if (tUser.getFirstName() != null - && !tUser.getFirstName().trim().isEmpty() - && !tUser.getFirstName().trim() - .equalsIgnoreCase("null")) { - if (tUser.getLastName() != null - && !tUser.getLastName().trim().isEmpty() - && !tUser.getLastName().trim() - .equalsIgnoreCase("null")) { - viewBean.setUpdatedBy(tUser.getFirstName() + " " - + tUser.getLastName()); - } else { - viewBean.setUpdatedBy(tUser.getFirstName()); - } - } else { - viewBean.setUpdatedBy(tUser.getLoginId()); - } - } - } - } - - } - - // ---------------------------------------------------------------------------------- - // Search Operation - // ---------------------------------------------------------------------------------- - - protected Query createQuery(String searchString, String sortString, - SearchCriteria searchCriteria, List<SearchField> searchFieldList, - boolean isCountQuery) { -// EntityManager em = entityDao != null ? entityDao.getEntityManager() : daoManager.getEntityManager(); - EntityManager em = getDao().getEntityManager(); - - Query query = searchUtil.createSearchQuery(em, searchString, sortString, - searchCriteria, searchFieldList, getClassType(), false, - isCountQuery); - return query; - } - - protected long getCountForSearchQuery(SearchCriteria searchCriteria, - List<SearchField> searchFieldList) { - - String q = countQueryStr; - // Get total count of the rows which meet the search criteria - if (searchCriteria.isDistinct()) { - q = distinctCountQueryStr; - } - - // Get total count of the rows which meet the search criteria - Query query = createQuery(q, null, searchCriteria, searchFieldList, - true); - - // Make the database call to get the total count - Long count = getDao().executeCountQueryInSecurityContext(tEntityClass, - query); - if (count == null) { - // If no data that meets the criteria, return 0 - return 0; - } - return count.longValue(); - } - - public VXLong getSearchCount(SearchCriteria searchCriteria, - List<SearchField> searchFieldList) { - long count = getCountForSearchQuery(searchCriteria, searchFieldList); - - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } - - protected List<T> searchResources(SearchCriteria searchCriteria, - List<SearchField> searchFieldList, List<SortField> sortFieldList, - VList vList) { - - // Get total count of the rows which meet the search criteria - long count = -1; - if (searchCriteria.isGetCount()) { - count = getCountForSearchQuery(searchCriteria, searchFieldList); - if (count == 0) { - return Collections.emptyList(); - } - } - // construct the sort clause - String sortClause = searchUtil.constructSortClause(searchCriteria, - sortFieldList); - - String q = queryStr; - if (searchCriteria.isDistinct()) { - q = distinctQueryStr; - } - // construct the query object for retrieving the data - Query query = createQuery(q, sortClause, searchCriteria, - searchFieldList, false); - - List<T> resultList = getDao().executeQueryInSecurityContext( - tEntityClass, query); - - if (vList != null) { - // Set the meta values for the query result - vList.setPageSize(query.getMaxResults()); - vList.setSortBy(searchCriteria.getSortBy()); - vList.setSortType(searchCriteria.getSortType()); - vList.setStartIndex(query.getFirstResult()); - vList.setTotalCount(count); - vList.setResultSize(resultList.size()); - } - return resultList; - } - - // -------------Criteria Usage-------------------- - // ----------------------------------------------- - public VXLong getSearchCountUsingCriteria(SearchCriteria searchCriteria, - List<SearchField> searchFieldList) { - EntityManager em = getDao().getEntityManager(); - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class); - - Root<T> from = criteria.from(tEntityClass); - Expression<Long> countExpression = criteriaBuilder - .count(from.get("id")); - criteria.select(countExpression); - - Predicate resourceConditions = buildResourceSpecificConditions( - criteriaBuilder, from, searchCriteria); - Predicate userConditions = buildUserConditions( - searchCriteria.getParamList(), searchFieldList, - criteriaBuilder, from); - - if (resourceConditions != null) { - criteria.where(criteriaBuilder.and(resourceConditions, - userConditions)); - } else { - criteria.where(criteriaBuilder.and(userConditions)); - } - - TypedQuery<Long> countQuery = em.createQuery(criteria); - long count = getDao().executeCountQueryInSecurityContext(tEntityClass, - countQuery); - - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } - - protected List<T> searchResourcesUsingCriteria( - SearchCriteria searchCriteria, List<SearchField> searchFieldList, - List<SortField> sortFieldList, VList vList) { - // boolean filterEnabled = getDao().enableVisiblityFilters(tClass, - // true); - - EntityManager em = getDao().getEntityManager(); - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery(); - Root<T> from = criteria.from(tEntityClass); - - Predicate resourceConditions = buildResourceSpecificConditions( - criteriaBuilder, from, searchCriteria); - Predicate userConditions = buildUserConditions( - searchCriteria.getParamList(), searchFieldList, - criteriaBuilder, from); - - if (resourceConditions != null) { - criteria.where(criteriaBuilder.and(resourceConditions, - userConditions)); - } else { - criteria.where(criteriaBuilder.and(userConditions)); - } - - // Get total count of the rows which meet the search criteria - long count = -1; - if (searchCriteria.isGetCount()) { - - Expression<Long> countExpression = criteriaBuilder.count(from - .get("id")); - criteria.select(countExpression); - TypedQuery<Long> countQuery = em.createQuery(criteria); - count = getDao().executeCountQueryInSecurityContext(tEntityClass, - countQuery); - if (count == 0) { - return Collections.emptyList(); - } - } - - // construct the sort clause - setSortClause(searchCriteria, sortFieldList, criteriaBuilder, criteria, - from); - - criteria.select(from); - TypedQuery<T> typedQuery = em.createQuery(criteria); - searchUtil.updateQueryPageSize(typedQuery, searchCriteria); - - List<T> resultList = getDao().executeQueryInSecurityContext( - tEntityClass, typedQuery); - - if (vList != null) { - // Set the meta values for the query result - vList.setPageSize(typedQuery.getMaxResults()); - vList.setSortBy(searchCriteria.getSortBy()); - vList.setSortType(searchCriteria.getSortType()); - vList.setStartIndex(typedQuery.getFirstResult()); - vList.setTotalCount(count); - } - - // if (filterEnabled) { - // getDao().disableVisiblityFilters(tClass); - // } - - return resultList; - } - - protected Predicate buildUserConditions(Map<String, Object> paramList, - List<SearchField> searchFields, CriteriaBuilder cb, - Root<? extends XXDBBase> from) { - Predicate userConditions = cb.conjunction(); - - for (SearchField searchField : searchFields) { - if (paramList.containsKey(searchField.getClientFieldName())) { - Path<Object> tableField = null; - String fieldName = searchField.getFieldName(); - - // stuff to handle jpql syntax (e.g. obj.id, obj.city.city etc). - // There has to be better way of dealing with this. Will look - // again. - int dotIndex = fieldName.indexOf("."); - if (dotIndex != -1) { - fieldName = fieldName.substring(dotIndex + 1); - } - dotIndex = fieldName.indexOf("."); - if (dotIndex == -1) { - tableField = from.get(fieldName); - } else { - String joinTable = fieldName.substring(0, dotIndex); - fieldName = fieldName.substring(dotIndex + 1); - tableField = from.join(joinTable).get(fieldName); - } - - Object value = paramList.get(searchField.getClientFieldName()); - if (value == null) { - userConditions = cb.and(userConditions, - cb.isNull(tableField)); - continue; - } - - if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER - || searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) { - userConditions = cb.and(userConditions, - cb.equal(tableField, value)); - } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) { - String strFieldValue = (String) value; - Expression<String> tableFieldWithLowerExpr = cb - .lower(tableField.as(String.class)); - - if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) { - Expression<String> literal = cb.lower(cb - .literal(strFieldValue)); - userConditions = cb.and(userConditions, - cb.equal(tableFieldWithLowerExpr, literal)); - } else { - Expression<String> literal = cb.lower(cb.literal("%" - + strFieldValue + "%")); - userConditions = cb.and(userConditions, - cb.like(tableFieldWithLowerExpr, literal)); - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST) { - - @SuppressWarnings("unchecked") - Collection<Number> intValueList = (Collection<Number>) value; - if (intValueList.size() == 1) { - userConditions = cb.and(userConditions, - cb.equal(tableField, value)); - } else if (intValueList.size() > 1) { - userConditions = cb.and(userConditions, - tableField.in(intValueList)); - } - } - - } - - } // for - - return userConditions; - } - - protected Predicate buildResourceSpecificConditions( - CriteriaBuilder criteriaBuilder, Root<T> from, SearchCriteria sc) { - return null; - } - - public void setSortClause(SearchCriteria searchCriteria, - List<SortField> sortFields, CriteriaBuilder criteriaBuilder, - CriteriaQuery<? extends Object> criteria, Root<? extends XXDBBase> from) { - - String sortBy = searchCriteria.getSortBy(); - String sortByField = null; - - if (!stringUtil.isEmpty(sortBy)) { - sortBy = sortBy.trim(); - for (SortField sortField : sortFields) { - if (sortBy.equalsIgnoreCase(sortField.getParamName())) { - sortByField = sortField.getFieldName(); - // Override the sortBy using the normalized value - // searchCriteria.setSortBy(sortByField); - break; - } - } - } - - if (sortByField == null) { - for (SortField sortField : sortFields) { - if (sortField.isDefault()) { - sortByField = sortField.getFieldName(); - // Override the sortBy using the default value - searchCriteria.setSortBy(sortField.getParamName()); - searchCriteria.setSortType(sortField.getDefaultOrder() - .name()); - break; - } - } - } - - if (sortByField != null) { - int dotIndex = sortByField.indexOf("."); - if (dotIndex != -1) { - sortByField = sortByField.substring(dotIndex + 1); - } - - // Add sort type - String sortType = searchCriteria.getSortType(); - if (sortType != null && sortType.equalsIgnoreCase("desc")) { - criteria.orderBy(criteriaBuilder.desc(from.get(sortByField))); - } else { - criteria.orderBy(criteriaBuilder.asc(from.get(sortByField))); - } - - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java b/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java deleted file mode 100644 index 63ba034..0000000 --- a/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.xasecure.service; - -import java.util.ArrayList; -import java.util.List; - -import com.xasecure.common.XAConstants; -import com.xasecure.common.SearchCriteria; -import com.xasecure.common.SearchField; -import com.xasecure.common.SortField; -import com.xasecure.common.StringUtil; -import com.xasecure.common.db.BaseDao; -import com.xasecure.entity.XXAuthSession; -import com.xasecure.entity.XXPortalUser; -import com.xasecure.view.VXAuthSession; -import com.xasecure.view.VXAuthSessionList; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; - -@Service -@Scope("singleton") -public class AuthSessionService extends - AbstractBaseResourceService<XXAuthSession, VXAuthSession> { - @Autowired - StringUtil stringUtil; - - public static final String NAME = "AuthSession"; - - public static final List<SortField> AUTH_SESSION_SORT_FLDS = new ArrayList<SortField>(); - static { - AUTH_SESSION_SORT_FLDS.add(new SortField("id", "obj.id")); - AUTH_SESSION_SORT_FLDS.add(new SortField("authTime", "obj.authTime", - true, SortField.SORT_ORDER.DESC)); - } - - public static List<SearchField> AUTH_SESSION_SEARCH_FLDS = new ArrayList<SearchField>(); - static { - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("id", "obj.id")); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("loginId", - "obj.loginId", SearchField.SEARCH_TYPE.PARTIAL, - StringUtil.VALIDATION_LOGINID)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("userId", - "obj.userId")); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authStatus", - "obj.authStatus", "statusList", XXAuthSession.AuthStatus_MAX)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authType", - "obj.authType", "Authentication Type", - XXAuthSession.AuthType_MAX)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("deviceType", - "obj.deviceType", "Device Type", XAConstants.DeviceType_MAX)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP", - "obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL, - StringUtil.VALIDATION_IP_ADDRESS)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString( - "requestUserAgent", "obj.requestUserAgent", - SearchField.SEARCH_TYPE.PARTIAL, null)); - AUTH_SESSION_SEARCH_FLDS.add(new SearchField("firstName", - "obj.user.firstName", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL)); - AUTH_SESSION_SEARCH_FLDS.add(new SearchField("lastName", - "obj.user.lastName", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL)); - AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP", - "obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL, - StringUtil.VALIDATION_IP_ADDRESS)); - AUTH_SESSION_SEARCH_FLDS.add(new SearchField("startDate", "obj.createTime", - SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); - AUTH_SESSION_SEARCH_FLDS.add(new SearchField("endDate", "obj.createTime", - SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); - } - - @Override - protected String getResourceName() { - return NAME; - } - - @Override - protected int getClassType() { - return XAConstants.CLASS_TYPE_AUTH_SESS; - } - - /* - * (non-Javadoc) - */ - @Override - protected BaseDao<XXAuthSession> getDao() { - return daoMgr.getXXAuthSession(); - } - - /* - * (non-Javadoc) - */ - @Override - protected XXAuthSession createEntityObject() { - return new XXAuthSession(); - } - - /* - * (non-Javadoc) - */ - @Override - protected VXAuthSession createViewObject() { - return new VXAuthSession(); - } - - /* - * (non-Javadoc) - */ - @Override - protected void validateForCreate(VXAuthSession vXAuthSession) { - logger.error("This method is not required and shouldn't be called.", - new Throwable().fillInStackTrace()); - } - - /* - * (non-Javadoc) - */ - @Override - protected void validateForUpdate(VXAuthSession vXAuthSession, - XXAuthSession mObj) { - logger.error("This method is not required and shouldn't be called.", - new Throwable().fillInStackTrace()); - } - - /* - * (non-Javadoc) - */ - @Override - protected XXAuthSession mapViewToEntityBean(VXAuthSession vXAuthSession, - XXAuthSession t, int OPERATION_CONTEXT) { - logger.error("This method is not required and shouldn't be called.", - new Throwable().fillInStackTrace()); - return null; - } - - /* - * (non-Javadoc) - */ - @Override - protected VXAuthSession mapEntityToViewBean(VXAuthSession viewObj, - XXAuthSession resource) { - viewObj.setLoginId(resource.getLoginId()); - viewObj.setAuthTime(resource.getAuthTime()); - viewObj.setAuthStatus(resource.getAuthStatus()); - viewObj.setAuthType(resource.getAuthType()); - viewObj.setDeviceType(resource.getDeviceType()); - viewObj.setExtSessionId(resource.getExtSessionId()); - viewObj.setId(resource.getId()); - viewObj.setRequestIP(resource.getRequestIP()); - - viewObj.setRequestUserAgent(resource.getRequestUserAgent()); - - if (resource.getUserId() != null) { - XXPortalUser gjUser = daoMgr.getXXPortalUser().getById(resource.getUserId()); - viewObj.setEmailAddress(gjUser.getEmailAddress()); - viewObj.setFamilyScreenName(gjUser.getEmailAddress()); - viewObj.setFirstName(gjUser.getFirstName()); - viewObj.setLastName(gjUser.getLastName()); - viewObj.setLastName(gjUser.getLastName()); - viewObj.setPublicScreenName(gjUser.getPublicScreenName()); - viewObj.setUserId(resource.getUserId()); - } - - return viewObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXAuthSessionList search(SearchCriteria searchCriteria) { - VXAuthSessionList returnList = new VXAuthSessionList(); - List<VXAuthSession> viewList = new ArrayList<VXAuthSession>(); - - List<XXAuthSession> resultList = searchResources(searchCriteria, - AUTH_SESSION_SEARCH_FLDS, AUTH_SESSION_SORT_FLDS, returnList); - - // Iterate over the result list and create the return list - for (XXAuthSession gjObj : resultList) { - VXAuthSession viewObj = populateViewBean(gjObj); - viewList.add(viewObj); - } - - returnList.setVXAuthSessions(viewList); - return returnList; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java b/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java deleted file mode 100644 index 90917c3..0000000 --- a/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.xasecure.service; - -import com.xasecure.view.VXDataObject; - -public abstract class PublicAPIServiceBase<VXA extends VXDataObject, VX extends VXDataObject> { - - protected VX mapBaseAttributesToPublicObject(VXA vXAObj, VX vPublicObj) { - vPublicObj.setId(vXAObj.getId()); - vPublicObj.setCreateDate(vXAObj.getCreateDate()); - vPublicObj.setUpdateDate(vXAObj.getUpdateDate()); - vPublicObj.setOwner(vXAObj.getOwner()); - vPublicObj.setUpdatedBy(vXAObj.getUpdatedBy()); - return vPublicObj; - } - - protected VXA mapBaseAttributesToXAObject(VX vPublicObj, VXA vXAObj) { - vXAObj.setId(vPublicObj.getId()); - vXAObj.setCreateDate(vPublicObj.getCreateDate()); - vXAObj.setUpdateDate(vPublicObj.getUpdateDate()); - vXAObj.setOwner(vPublicObj.getOwner()); - vXAObj.setUpdatedBy(vPublicObj.getUpdatedBy()); - - return vXAObj; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/UserService.java ---------------------------------------------------------------------- diff --git a/security-admin/src/main/java/com/xasecure/service/UserService.java b/security-admin/src/main/java/com/xasecure/service/UserService.java deleted file mode 100644 index 462a68c..0000000 --- a/security-admin/src/main/java/com/xasecure/service/UserService.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - package com.xasecure.service; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import com.xasecure.common.XAConstants; -import com.xasecure.common.ContextUtil; -import com.xasecure.common.XAConfigUtil; -import com.xasecure.common.MessageEnums; -import com.xasecure.common.StringUtil; -import com.xasecure.common.UserSessionBase; -import com.xasecure.entity.XXPortalUser; -import com.xasecure.entity.XXPortalUserRole; -import com.xasecure.view.VXMessage; -import com.xasecure.view.VXResponse; -import com.xasecure.view.VXPortalUser; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; - -@Service -@Scope("singleton") -public class UserService extends UserServiceBase<XXPortalUser, VXPortalUser> { - static Logger logger = Logger.getLogger(UserService.class); - - public static final String NAME = "User"; - - @Autowired - XAConfigUtil configUtil; - - private static UserService instance = null; - - public UserService() { - super(); - instance = this; - } - - public static UserService getInstance() { - if (instance == null) { - logger.error("Instance is null", new Throwable()); - } - return instance; - } - - @Override - protected void validateForCreate(VXPortalUser userProfile) { - List<VXMessage> messageList = new ArrayList<VXMessage>(); - if (stringUtil.isEmpty(userProfile.getEmailAddress())) { - logger.info("Empty Email Address." + userProfile); - messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null, - "emailAddress")); - } - - if (stringUtil.isEmpty(userProfile.getFirstName())) { - logger.info("Empty firstName." + userProfile); - messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null, - "firstName")); - } - if (stringUtil.isEmpty(userProfile.getLastName())) { - logger.info("Empty lastName." + userProfile); - messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null, - "lastName")); - } - // firstName - if (!stringUtil.isValidName(userProfile.getFirstName())) { - logger.info("Invalid first name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "firstName")); - } - userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile - .getFirstName())); - - // lastName - if (!stringUtil.isValidName(userProfile.getLastName())) { - logger.info("Invalid last name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "lastName")); - } - userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile - .getLastName())); - - if (!stringUtil.validateEmail(userProfile.getEmailAddress())) { - logger.info("Invalid email address." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "emailAddress")); - - } - - // Normalize email. Make it lower case - userProfile.setEmailAddress(stringUtil.normalizeEmail(userProfile - .getEmailAddress())); - - // loginId - userProfile.setLoginId(userProfile.getEmailAddress()); - - // password - if (!stringUtil.validatePassword( - userProfile.getPassword(), - new String[] { userProfile.getFirstName(), - userProfile.getLastName() })) { - logger.info("Invalid password." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "password")); - } - - // firstName - if (!stringUtil.validateString(StringUtil.VALIDATION_NAME, - userProfile.getFirstName())) { - logger.info("Invalid first name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "firstName")); - } - - // lastName - if (!stringUtil.validateString(StringUtil.VALIDATION_NAME, - userProfile.getLastName())) { - logger.info("Invalid last name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "lastName")); - } - - // create the public screen name - userProfile.setPublicScreenName(userProfile.getFirstName() + " " - + userProfile.getLastName()); - - if (messageList.size() > 0) { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMsgDesc("Validation failure"); - gjResponse.setMessageList(messageList); - logger.info("Validation Error in createUser() userProfile=" - + userProfile + ", error=" + gjResponse); - throw restErrorUtil.createRESTException(gjResponse); - } - } - - @Override - protected void validateForUpdate(VXPortalUser userProfile, XXPortalUser xXPortalUser) { - List<VXMessage> messageList = new ArrayList<VXMessage>(); - - if (userProfile.getEmailAddress() != null - && !userProfile.getEmailAddress().equalsIgnoreCase( - xXPortalUser.getEmailAddress())) { - throw restErrorUtil.createRESTException("serverMsg.userEmail", - MessageEnums.DATA_NOT_UPDATABLE, null, "emailAddress", - userProfile.getEmailAddress()); - } - - // Login Id can't be changed - if (userProfile.getLoginId() != null - && !xXPortalUser.getLoginId().equalsIgnoreCase( - userProfile.getLoginId())) { - throw restErrorUtil.createRESTException("serverMsg.userUserName", - MessageEnums.DATA_NOT_UPDATABLE, null, "loginId", - userProfile.getLoginId()); - } - // } - - userProfile.setFirstName(restErrorUtil.validateStringForUpdate( - userProfile.getFirstName(), xXPortalUser.getFirstName(), - StringUtil.VALIDATION_NAME, "serverMsg.userFirstName", - MessageEnums.INVALID_INPUT_DATA, null, "firstName")); - - userProfile.setFirstName(restErrorUtil.validateStringForUpdate( - userProfile.getFirstName(), xXPortalUser.getFirstName(), - StringUtil.VALIDATION_NAME, "serverMsg.userFirstName", - MessageEnums.INVALID_INPUT_DATA, null, "firstName")); - - userProfile.setLastName(restErrorUtil.validateStringForUpdate( - userProfile.getLastName(), xXPortalUser.getLastName(), - StringUtil.VALIDATION_NAME, "serverMsg.userLastName", - MessageEnums.INVALID_INPUT_DATA, null, "lastName")); - - // firstName - if (!stringUtil.isValidName(userProfile.getFirstName())) { - logger.info("Invalid first name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "firstName")); - } - - // lastName - if (!stringUtil.isValidName(userProfile.getLastName())) { - logger.info("Invalid last name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "lastName")); - } - - userProfile.setNotes(restErrorUtil.validateStringForUpdate( - userProfile.getNotes(), xXPortalUser.getNotes(), - StringUtil.VALIDATION_NAME, "serverMsg.userNotes", - MessageEnums.INVALID_INPUT_DATA, null, "notes")); - - // validate status - restErrorUtil.validateMinMax(userProfile.getStatus(), 0, - XAConstants.ActivationStatus_MAX, "Invalid status", null, - "status"); - - // validate user roles - if (userProfile.getUserRoleList() != null) { - // First let's normalize it - splitUserRoleList(userProfile.getUserRoleList()); - for (String userRole : userProfile.getUserRoleList()) { - restErrorUtil.validateStringList(userRole, - configUtil.getRoles(), "serverMsg.userRole", null, - "userRoleList"); - } - - } - - // TODO: Need to see whether user can set user as internal - - if (messageList.size() > 0) { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMsgDesc("Validation failure"); - gjResponse.setMessageList(messageList); - logger.info("Validation Error in updateUser() userProfile=" - + userProfile + ", error=" + gjResponse); - throw restErrorUtil.createRESTException(gjResponse); - } - } - - void splitUserRoleList(Collection<String> collection) { - Collection<String> newCollection = new ArrayList<String>(); - for (String role : collection) { - String roles[] = role.split(","); - for (int i = 0; i < roles.length; i++) { - String str = roles[i]; - newCollection.add(str); - } - } - collection.clear(); - collection.addAll(newCollection); - } - - @Override - protected XXPortalUser mapViewToEntityBean(VXPortalUser userProfile, XXPortalUser mObj, - int OPERATION_CONTEXT) { - mObj.setEmailAddress(userProfile.getEmailAddress()); - mObj.setFirstName(userProfile.getFirstName()); - mObj.setLastName(userProfile.getLastName()); - mObj.setLoginId(userProfile.getLoginId()); - mObj.setPassword(userProfile.getPassword()); - mObj.setPublicScreenName(bizUtil.generatePublicName(userProfile, null)); - mObj.setUserSource(userProfile.getUserSource()); - return mObj; - - } - - @Override - protected VXPortalUser mapEntityToViewBean(VXPortalUser userProfile, - XXPortalUser user) { - userProfile.setId(user.getId()); - userProfile.setLoginId(user.getLoginId()); - userProfile.setFirstName(user.getFirstName()); - userProfile.setLastName(user.getLastName()); - userProfile.setPublicScreenName(user.getPublicScreenName()); - userProfile.setStatus(user.getStatus()); - userProfile.setUserRoleList(new ArrayList<String>()); - String emailAddress = user.getEmailAddress(); - if (emailAddress != null && stringUtil.validateEmail(emailAddress)) { - userProfile.setEmailAddress(user.getEmailAddress()); - } - - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - if (sess != null) { - userProfile.setUserSource(sess.getAuthProvider()); - } - - List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId( - user.getId()); - - for (XXPortalUserRole gjUserRole : gjUserRoleList) { - userProfile.getUserRoleList().add(gjUserRole.getUserRole()); - } - return userProfile; - } - - // TODO: Need to remove this ASAP - public void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) { - userProfile.setId(user.getId()); - userProfile.setLoginId(user.getLoginId()); - userProfile.setFirstName(user.getFirstName()); - userProfile.setLastName(user.getLastName()); - userProfile.setPublicScreenName(user.getPublicScreenName()); - userProfile.setStatus(user.getStatus()); - userProfile.setUserRoleList(new ArrayList<String>()); - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - - String emailAddress = user.getEmailAddress(); - if (emailAddress != null && stringUtil.validateEmail(emailAddress)) { - userProfile.setEmailAddress(user.getEmailAddress()); - } - - if (sess != null) { - userProfile.setUserSource(sess.getAuthProvider()); - } - - List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId( - user.getId()); - - for (XXPortalUserRole gjUserRole : gjUserRoleList) { - userProfile.getUserRoleList().add(gjUserRole.getUserRole()); - } - } - -}
