Mercurial > lada > lada-server
changeset 720:5815920ccabc
Removed the OpenId authentorization files and dependencies.
author | Raimund Renkert <raimund.renkert@intevation.de> |
---|---|
date | Fri, 14 Aug 2015 09:43:29 +0200 (2015-08-14) |
parents | a4932159a469 |
children | 6eed8b5decb1 |
files | pom.xml src/main/java/de/intevation/lada/util/auth/OpenIDFilter.java src/main/java/de/intevation/lada/util/auth/OpenIdAuthorization.java src/main/java/de/intevation/lada/util/auth/TestAuthorization.java |
diffstat | 4 files changed, 55 insertions(+), 1028 deletions(-) [+] |
line wrap: on
line diff
--- a/pom.xml Thu Aug 06 09:59:22 2015 +0200 +++ b/pom.xml Fri Aug 14 09:43:29 2015 +0200 @@ -6,7 +6,7 @@ <name>Lada Server</name> <groupId>de.intevation</groupId> - <artifactId>lada-server</artifactId> + <artifactId>lada-server-dev</artifactId> <packaging>war</packaging> <parent> <groupId>org.jboss</groupId> @@ -69,6 +69,11 @@ <artifactId>jackson-annotations</artifactId> <version>2.5.1</version> </dependency> + <dependency> + <groupId>org.opensaml</groupId> + <artifactId>opensaml</artifactId> + <version>2.6.4</version> + </dependency> <!-- Hibernate --> <dependency> @@ -159,100 +164,39 @@ </configuration> </plugin> <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.1</version> - <executions> - <execution> - <id>default-testCompile</id> - <phase>test-compile</phase> - <goals> - <goal>testCompile</goal> - </goals> - <configuration> - <excludes> - <exclude>**/auth/TestAuthorization.java</exclude> - </excludes> - </configuration> - </execution> - <execution> - <id>default-compile</id> - <phase>compile</phase> - <goals> - <goal>compile</goal> - </goals> - <configuration> - <excludes> - <exclude>**/auth/TestAuthorization.java</exclude> - </excludes> - </configuration> - </execution> - </executions> - <configuration> - <showDeprecation>true</showDeprecation> - <showWarnings>true</showWarnings> - <compilerArguments> - <source>1.7</source> - <target>1.7</target> - </compilerArguments> - </configuration> - </plugin> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <showDeprecation>true</showDeprecation> + <showWarnings>true</showWarnings> + <compilerArguments> + <source>1.7</source> + <target>1.7</target> + </compilerArguments> + </configuration> + </plugin> </plugins> </build> - <dependencies> - <dependency> - <groupId>org.openid4java</groupId> - <artifactId>openid4java</artifactId> - <version>1.0.0</version> - </dependency> - </dependencies> </profile> <profile> <id>remote-test</id> <build> - <plugins> - <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.1</version> - <executions> - <execution> - <id>default-testCompile</id> - <phase>test-compile</phase> - <goals> - <goal>testCompile</goal> - </goals> - <configuration> - <excludes> - <exclude>**/auth/OpenIdAuthorization.java</exclude> - <exclude>**/auth/OpenIDFilter.java</exclude> - </excludes> - </configuration> - </execution> - <execution> - <id>default-compile</id> - <phase>compile</phase> - <goals> - <goal>compile</goal> - </goals> - <configuration> - <excludes> - <exclude>**/auth/OpenIdAuthorization.java</exclude> - <exclude>**/auth/OpenIDFilter.java</exclude> - </excludes> - </configuration> - </execution> - </executions> - <configuration> - <showDeprecation>true</showDeprecation> - <showWarnings>true</showWarnings> - <compilerArguments> - <source>1.7</source> - <target>1.7</target> - </compilerArguments> - </configuration> - </plugin> - </plugins> - </build> + <plugins> + <plugin> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <showDeprecation>true</showDeprecation> + <showWarnings>true</showWarnings> + <compilerArguments> + <source>1.7</source> + <target>1.7</target> + </compilerArguments> + </configuration> + </plugin> + </plugins> + </build> <dependencies> <dependency> <groupId>org.wildfly</groupId> @@ -280,15 +224,33 @@ <build> <plugins> <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <skip>true</skip> + </configuration> + </plugin> + <plugin> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.1</version> + <configuration> + <showDeprecation>true</showDeprecation> + <showWarnings>true</showWarnings> + <compilerArguments> + <source>1.7</source> + <target>1.7</target> + </compilerArguments> + </configuration> + </plugin> + <plugin> <groupId>org.wildfly.plugins</groupId> <artifactId>wildfly-maven-plugin</artifactId> <configuration> - <hostname>eulimene</hostname> - <port>9990</port> + <hostname>localhost</hostname> + <port>19990</port> <username>admin</username> <password>secret</password> </configuration> - <executions> + <!-- <executions> <execution> <id>deploy-jar</id> <phase>install</phase> @@ -296,17 +258,10 @@ <goal>deploy</goal> </goals> </execution> - </executions> + </executions>--> </plugin> </plugins> </build> - <dependencies> - <dependency> - <groupId>org.openid4java</groupId> - <artifactId>openid4java</artifactId> - <version>1.0.0</version> - </dependency> - </dependencies> </profile> </profiles>
--- a/src/main/java/de/intevation/lada/util/auth/OpenIDFilter.java Thu Aug 06 09:59:22 2015 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,377 +0,0 @@ -/* Copyright (C) 2015 by Bundesamt fuer Strahlenschutz - * Software engineering by Intevation GmbH - * - * This file is Free Software under the GNU GPL (v>=3) - * and comes with ABSOLUTELY NO WARRANTY! Check out - * the documentation coming with IMIS-Labordaten-Application for details. - */ - -package de.intevation.lada.util.auth; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URLDecoder; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; -import org.openid4java.association.AssociationException; -import org.openid4java.association.AssociationSessionType; -import org.openid4java.consumer.AbstractNonceVerifier; -import org.openid4java.consumer.ConsumerException; -import org.openid4java.consumer.ConsumerManager; -import org.openid4java.consumer.InMemoryConsumerAssociationStore; -import org.openid4java.consumer.VerificationResult; -import org.openid4java.discovery.DiscoveryException; -import org.openid4java.discovery.DiscoveryInformation; -import org.openid4java.discovery.Identifier; -import org.openid4java.message.AuthRequest; -import org.openid4java.message.AuthSuccess; -import org.openid4java.message.MessageException; -import org.openid4java.message.ParameterList; -import org.openid4java.message.ax.AxMessage; -import org.openid4java.message.ax.FetchRequest; -import org.openid4java.message.ax.FetchResponse; - -/** ServletFilter used for OpenID authentification. */ -@WebFilter("/*") -public class OpenIDFilter implements Filter { - - private static final String CONFIG_FILE = "/openid.properties"; - - /** The name of the header field used to transport OpenID parameters.*/ - private static final String OID_HEADER_DEFAULT = "X-OPENID-PARAMS"; - private String oidHeader; - - /** The identity provider we accept here. */ - private static final String IDENTITY_PROVIDER_DEFAULT = - "https://localhost/openid/"; - private String providerUrl; - - private static final int SESSION_TIMEOUT_DEFAULT_MINUTES = 60; - private int sessionTimeout; - - private boolean enabled; - - private static Logger logger = Logger.getLogger(OpenIDFilter.class); - - /** Nonce verifier to allow a session based on openid information. - * - * Usually one would create a session for the user but this would not - * be an advantage here as we want to transport the session in a header - * anyway. - * - * A nonce will be valid as long as as the maxAge is not reached. - * This is implemented by the basis verifier. - * We only implement seed no mark that we accept nonce's multiple - * times. - */ - private class SessionNonceVerifier extends AbstractNonceVerifier { - public SessionNonceVerifier(int maxAge) { - super(maxAge); - } - - @Override - protected int seen(Date now, String opUrl, String nonce) { - return OK; - } - }; - - private ConsumerManager manager; - - /* This should be moved into a map <server->discovered> - * as we currently only supporting one server this is static. */ - boolean discoveryDone = false; - private DiscoveryInformation discovered; - - private boolean discoverServer() { - /* Perform discovery on the configured providerUrl */ - List<?> discoveries = null; - try { - discoveries = manager.discover(providerUrl); - } catch (DiscoveryException e) { - logger.debug("Discovery failed: " + e.getMessage()); - return false; - } - - if (discoveries == null || discoveries.isEmpty()) { - logger.error( - "Failed discovery step. OpenID provider unavailable?"); - return false; - } - - /* Add association for the discovered information */ - discovered = manager.associate(discoveries); - - return true; - } - - /** Split up the OpenID response query provided in the header. - * - * @param responseQuery The query provided in the header field. - * @return The query as ParameterList or null on error. - */ - private ParameterList splitParams(String responseQuery) { - if (responseQuery == null) { - return null; - } - Map<String, String> queryMap = - new LinkedHashMap<String, String>(); - final String[] pairs = responseQuery.split("&"); - for (String pair : pairs) { - final int idx = pair.indexOf("="); - if (idx <= 0) { - logger.debug("Invalid query."); - return null; - } - try { - final String key = URLDecoder.decode( - pair.substring(0, idx), "UTF-8"); - - if (queryMap.containsKey(key)) { - logger.debug("Duplicate key: " + key + " ignored."); - continue; - } - final String value = URLDecoder.decode( - pair.substring(idx + 1), "UTF-8"); - queryMap.put(key, value); - } catch (java.io.UnsupportedEncodingException e) { - logger.error("UTF-8 unkown?!"); - return null; - } - } - if (queryMap.isEmpty()) { - logger.debug("Empty query."); - return null; - } - return new ParameterList(queryMap); - } - - private boolean checkOpenIDQuery(ServletRequest req) { - HttpServletRequest hReq = (HttpServletRequest) req; - - String oidParamString = hReq.getQueryString(); - - if (oidParamString == null) { - logger.debug("No query string."); - } - return checkOpenIDString(hReq, oidParamString); - } - - private boolean checkOpenIDHeader(ServletRequest req) { - - HttpServletRequest hReq = (HttpServletRequest) req; - /* Debug code to dump headers - Enumeration<String> headerNames = hReq.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - logger.debug("Header: " + headerName); - Enumeration<String> headers = hReq.getHeaders(headerName); - while (headers.hasMoreElements()) { - String headerValue = headers.nextElement(); - logger.debug("Value: " + headerValue); - } - } - */ - /* First check if the header is provided at all */ - String oidParamString = hReq.getHeader(oidHeader); - - if (oidParamString == null) { - logger.debug("Header " + oidHeader + " not provided."); - } - return checkOpenIDString(hReq, oidParamString); - } - - private boolean checkOpenIDString(HttpServletRequest hReq, - String oidParamString) { - - /* Parse the parameters to a map for openid4j */ - ParameterList oidParams = splitParams(oidParamString); - if (oidParams == null) { - return false; - } - - /* Verify against the discovered server. */ - VerificationResult verification = null; - String receivingURL = oidParams.getParameterValue("openid.return_to"); - - try { - verification = manager.verify(receivingURL, oidParams, - discovered); - } catch (MessageException e) { - logger.debug("Verification failed: " + e.getMessage()); - return false; - } catch (DiscoveryException e) { - logger.debug("Verification discovery exception: " + e.getMessage()); - return false; - } catch (AssociationException e) { - logger.debug("Verification assoc exception: " + e.getMessage()); - return false; - } - - /* See what could be verified */ - Identifier verified = verification.getVerifiedId(); - if (verified == null) { - logger.debug("Failed to verify Identity information: " + - verification.getStatusMsg()); - return false; - } - - AuthSuccess authSuccess = - (AuthSuccess) verification.getAuthResponse(); - String rolesValue = ""; - if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { - FetchResponse fetchResp = null; - try { - fetchResp = (FetchResponse) authSuccess.getExtension( - AxMessage.OPENID_NS_AX); - } catch (MessageException e) { - logger.debug("Failed to fetch extended result: " + - e.getMessage()); - return false; - } - rolesValue = fetchResp.getAttributeValue("attr1"); - } else { - logger.debug("No such extension."); - } - - String[] identifier = verified.getIdentifier().split("/"); - String userName = identifier[identifier.length -1]; - hReq.setAttribute("lada.user.roles", rolesValue); - hReq.setAttribute("lada.user.name", userName); - return true; - } - - @Override - public void init(FilterConfig config) - throws ServletException - { - /* Read config and initialize configuration variables */ - Properties properties = new Properties(); - InputStream stream = null; - try { - stream = getClass().getResourceAsStream(CONFIG_FILE); - properties.load(stream); - stream.close(); - } catch (java.io.FileNotFoundException e) { - logger.error ("Failed to find config file: " + CONFIG_FILE); - } catch (java.io.IOException e) { - logger.error ("Failed to read config file: " + CONFIG_FILE); - } - try { - sessionTimeout = Integer.parseInt( - properties.getProperty("session_timeout_minutes")); - } catch (NumberFormatException e) { - sessionTimeout = SESSION_TIMEOUT_DEFAULT_MINUTES; - } - oidHeader = properties.getProperty("oidHeader", OID_HEADER_DEFAULT); - providerUrl = properties.getProperty("identity_provider", - IDENTITY_PROVIDER_DEFAULT); - enabled = !properties.getProperty("enabled", - "true").toLowerCase().equals("false"); - - manager = new ConsumerManager(); - /* We probably want to implement our own association store to keep - * associations persistent. */ - manager.setAssociations(new InMemoryConsumerAssociationStore()); - manager.setNonceVerifier(new SessionNonceVerifier(sessionTimeout * 60)); - manager.setMinAssocSessEnc(AssociationSessionType.DH_SHA256); - discoveryDone = discoverServer(); - } - - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) - throws IOException, ServletException - { - if (!enabled) { - /* If we are not enabled we pass everything through */ - logger.debug("OpenID filter disabled. Passing through."); - chain.doFilter(req, resp); - return; - } - - HttpServletRequest hReq = (HttpServletRequest) req; - HttpServletResponse hResp = (HttpServletResponse) resp; - if (!discoveryDone) { - discoveryDone = discoverServer(); - } - if (discoveryDone) { - if (checkOpenIDHeader(req)) - { - /* Successfully authenticated. Through Header */ - chain.doFilter(req, resp); - return; - } else if (checkOpenIDQuery(req)) { - /* Successfully authenticated. Through Query parameters.*/ - hResp.addHeader(oidHeader, hReq.getQueryString().replace( - "is_return=true","")); - chain.doFilter(req, resp); - return; - } - } - /* Authentication failure */ - String authRequestURL = "Error communicating with openid server"; - int errorCode = 698; - if (discoveryDone) { - /* Parse the parameters to a map for openid4j */ - ParameterList params = splitParams(hReq.getQueryString()); - String returnToUrl; - if (params == null) { - logger.debug("Failed to get any parameters from url."); - hResp.reset(); - hResp.setStatus(401); - hResp.getOutputStream().print("{\"success\":false,\"message\":\"" + errorCode + "\",\"data\":" + - "\"No return url provided!\",\"errors\":{},\"warnings\":{}," + - "\"readonly\":false,\"totalCount\":0}"); - hResp.getOutputStream().flush(); - return; - } else { - returnToUrl = params.getParameterValue("return_to"); - } - try { - AuthRequest authReq = manager.authenticate(discovered, - returnToUrl); - // Fetch the role attribute - FetchRequest fetch = FetchRequest.createFetchRequest(); - - fetch.addAttribute("attr1", - "http://axschema.org/person/role", - true, 0); - // attach the extension to the authentication request - authReq.addExtension(fetch); - - authRequestURL = authReq.getDestinationUrl(true); - errorCode = 699; - } catch (MessageException e) { - logger.debug("Failed to create the Authentication request: " + - e.getMessage()); - } catch (ConsumerException e) { - logger.debug("Error in consumer manager: " + - e.getMessage()); - } - } - hResp.reset(); - hResp.setStatus(401); - hResp.getOutputStream().print("{\"success\":false,\"message\":\"" + errorCode + "\",\"data\":" + - "\"" + authRequestURL + "\",\"errors\":{},\"warnings\":{}," + - "\"readonly\":false,\"totalCount\":0}"); - hResp.getOutputStream().flush(); - } - @Override - public void destroy() - { - } -};
--- a/src/main/java/de/intevation/lada/util/auth/OpenIdAuthorization.java Thu Aug 06 09:59:22 2015 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,551 +0,0 @@ -/* Copyright (C) 2013 by Bundesamt fuer Strahlenschutz - * Software engineering by Intevation GmbH - * - * This file is Free Software under the GNU GPL (v>=3) - * and comes with ABSOLUTELY NO WARRANTY! Check out - * the documentation coming with IMIS-Labordaten-Application for details. - */ -package de.intevation.lada.util.auth; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.inject.Inject; -import javax.persistence.EntityManager; -import javax.servlet.http.HttpServletRequest; - -import org.apache.log4j.Logger; - -import de.intevation.lada.model.land.LMessung; -import de.intevation.lada.model.land.LProbe; -import de.intevation.lada.model.stamm.Auth; -import de.intevation.lada.util.annotation.AuthorizationConfig; -import de.intevation.lada.util.annotation.RepositoryConfig; -import de.intevation.lada.util.data.QueryBuilder; -import de.intevation.lada.util.data.Repository; -import de.intevation.lada.util.data.RepositoryType; -import de.intevation.lada.util.rest.RequestMethod; -import de.intevation.lada.util.rest.Response; - -/** - * Authorize a user via HttpServletRequest attributes added by OpenIdFilter. - * - * @author <a href="mailto:rrenkert@intevation.de">Raimund Renkert</a> - */ -@AuthorizationConfig(type=AuthorizationType.OPEN_ID) -public class OpenIdAuthorization implements Authorization { - - /** - * The logger used in this class. - */ - @Inject - private Logger logger; - - /** - * The Repository used to read from Database. - */ - @Inject - @RepositoryConfig(type=RepositoryType.RO) - private Repository repository; - - /** - * Request user informations using the HttpServletRequest. - * - * @param source The HttpServletRequest - * @return The UserInfo object containing username and groups. - */ - @Override - public UserInfo getInfo(Object source) { - if (source instanceof HttpServletRequest) { - HttpServletRequest request = (HttpServletRequest)source; - String roleString = - request.getAttribute("lada.user.roles").toString(); - String[] roles = roleString.split(","); - UserInfo info = getGroupsFromDB(roleString); - info.setRoles(new ArrayList<String>(Arrays.asList(roles))); - info.setName(request.getAttribute("lada.user.name").toString()); - return info; - } - return null; - } - - /** - * Filter a list of data objects using the user informations contained in - * the HttpServletRequest. - * - * @param source The HttpServletRequest - * @param data The Response object containing the data. - * @param clazz The data object class. - * @return The Response object containing the filtered data. - */ - @Override - public <T> Response filter(Object source, Response data, Class<T> clazz) { - UserInfo userInfo = this.getInfo(source); - if (userInfo == null) { - return data; - } - if (clazz == LProbe.class) { - return this.authorizeProbe(userInfo, data); - } - if (clazz == LMessung.class) { - return this.authorizeMessung(userInfo, data); - } - Method[] methods = clazz.getMethods(); - for (Method method: methods) { - if (method.getName().equals("getProbeId")) { - return this.authorizeWithProbeId(userInfo, data, clazz); - } - if (method.getName().equals("getMessungsId")) { - return this.authorizeWithMessungsId(userInfo, data, clazz); - } - } - return data; - } - - /** - * Check whether a user is authorized to operate on the given data. - * - * @param source The HttpServletRequest containing user information. - * @param data The data to test. - * @param method The Http request type. - * @param clazz The data object class. - * @return True if the user is authorized else returns false. - */ - @Override - public <T> boolean isAuthorized( - Object source, - Object data, - RequestMethod method, - Class<T> clazz - ) { - UserInfo userInfo = this.getInfo(source); - if (userInfo == null) { - return false; - } - if (clazz == LProbe.class) { - LProbe probe = (LProbe)data; - if (method == RequestMethod.POST) { - return getAuthorization(userInfo, probe); - } - else if (method == RequestMethod.PUT || - method == RequestMethod.DELETE) { - return !isReadOnly(probe.getId()); - } - else { - return false; - } - } - else if (clazz == LMessung.class) { - LMessung messung = (LMessung)data; - Response response = - repository.getById(LProbe.class, messung.getProbeId(), "land"); - LProbe probe = (LProbe)response.getData(); - if (method == RequestMethod.POST) { - return getAuthorization(userInfo, probe); - } - else if (method == RequestMethod.PUT || - method == RequestMethod.DELETE) { - Response messResponse = - repository.getById(LMessung.class, messung.getId(), "land"); - LMessung messungDb = (LMessung)messResponse.getData(); - boolean fertigChanged = - !messung.getFertig().equals(messungDb.getFertig()); - logger.warn("changed " + fertigChanged); - return (!messung.getFertig() || fertigChanged) && - getAuthorization(userInfo, probe); - } - } - else { - Method[] methods = clazz.getMethods(); - for (Method m: methods) { - if (m.getName().equals("getProbeId")) { - Integer id; - try { - id = (Integer) m.invoke(data); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - logger.warn(e.getCause() + ": " + e.getMessage()); - return false; - } - Response response = - repository.getById(LProbe.class, id, "land"); - LProbe probe = (LProbe)response.getData(); - return !isReadOnly(id) && getAuthorization(userInfo, probe); - - } - if (m.getName().equals("getMessungsId")) { - Integer id; - try { - id = (Integer) m.invoke(data); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - logger.warn(e.getCause() + ": " + e.getMessage()); - return false; - } - Response mResponse = - repository.getById(LMessung.class, id, "land"); - LMessung messung = (LMessung)mResponse.getData(); - Response pResponse = - repository.getById( - LProbe.class, - messung.getProbeId(), - "land"); - LProbe probe = (LProbe)pResponse.getData(); - return !messung.getFertig() && - getAuthorization(userInfo, probe); - } - } - } - return true; - } - - /** - * Get the authorization of a single probe. - * - * @param userInfo The user information. - * @param probe The probe to authorize. - */ - private boolean getAuthorization(UserInfo userInfo, LProbe probe) { - if (userInfo.getMessstellen().contains(probe.getMstId())) { - return true; - } - else { - return false; - } - } - - /** - * Request the lada specific groups. - * - * @param roles The roles defined in the OpenId server. - * @return The UserInfo contianing roles and user name. - */ - private UserInfo getGroupsFromDB(String roles) { - QueryBuilder<Auth> builder = new QueryBuilder<Auth>( - repository.entityManager("stamm"), - Auth.class); - builder.andIn("ldapGroup", Arrays.asList(roles.split(","))); - Response response = repository.filter(builder.getQuery(), "stamm"); - @SuppressWarnings("unchecked") - List<Auth> auth = (List<Auth>)response.getData(); - List<String> netzbetreiber = new ArrayList<String>(); - List<String> messstellen = new ArrayList<String>(); - for (Auth a : auth) { - if (a.getNetzBetreiber() != null) { - netzbetreiber.add(a.getNetzBetreiber()); - } - if (a.getMessStelle() != null) { - messstellen.add(a.getMessStelle()); - } - } - UserInfo userInfo = new UserInfo(); - userInfo.setNetzbetreiber(netzbetreiber); - userInfo.setMessstellen(messstellen); - return userInfo; - } - - /** - * Authorize data that has a messungsId Attribute. - * - * @param userInfo The user information. - * @param data The Response object containing the data. - * @param clazz The data object class. - * @return A Response object containing the data. - */ - @SuppressWarnings("unchecked") - private <T> Response authorizeWithMessungsId( - UserInfo userInfo, - Response data, - Class<T> clazz - ) { - if (data.getData() instanceof List<?>) { - List<Object> objects = new ArrayList<Object>(); - for (Object object :(List<Object>)data.getData()) { - objects.add(authorizeSingleWithMessungsId(userInfo, object, clazz)); - } - data.setData(objects); - } - else { - Object object = data.getData(); - data.setData(authorizeSingleWithMessungsId(userInfo, object, clazz)); - } - return data; - } - - /** - * Authorize data that has a probeId Attribute. - * - * @param userInfo The user information. - * @param data The Response object containing the data. - * @param clazz The data object class. - * @return A Response object containing the data. - */ - @SuppressWarnings("unchecked") - private <T> Response authorizeWithProbeId( - UserInfo userInfo, - Response data, - Class<T> clazz - ) { - if (data.getData() instanceof List<?>) { - List<Object> objects = new ArrayList<Object>(); - for (Object object :(List<Object>)data.getData()) { - objects.add(authorizeSingleWithProbeId( - userInfo, - object, - clazz)); - } - data.setData(objects); - } - else { - Object object = data.getData(); - data.setData(authorizeSingleWithProbeId(userInfo, object, clazz)); - } - return data; - } - - /** - * Authorize a single data object that has a messungsId Attribute. - * - * @param userInfo The user information. - * @param data The Response object containing the data. - * @param clazz The data object class. - * @return A Response object containing the data. - */ - private <T> Object authorizeSingleWithMessungsId( - UserInfo userInfo, - Object data, - Class<T> clazz - ) { - try { - Method getMessungsId = clazz.getMethod("getMessungsId"); - Integer id = (Integer)getMessungsId.invoke(data); - LMessung messung = - (LMessung)repository.getById( - LMessung.class, id, "land").getData(); - LProbe probe = - (LProbe)repository.getById( - LProbe.class, messung.getProbeId(), "land").getData(); - - boolean readOnly = true; - boolean owner = false; - if (!userInfo.getNetzbetreiber().contains( - probe.getNetzbetreiberId())) { - owner = false; - readOnly = true; - } - else { - if (userInfo.getMessstellen().contains(probe.getMstId())) { - owner = true; - } - else { - owner = false; - } - readOnly = messung.getFertig(); - } - - Method setOwner = clazz.getMethod("setOwner", boolean.class); - Method setReadonly = clazz.getMethod("setReadonly", boolean.class); - setOwner.invoke(data, owner); - setReadonly.invoke(data, readOnly); - } catch (NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - return null; - } - return data; - } - - /** - * Authorize a single data object that has a probeId Attribute. - * - * @param userInfo The user information. - * @param data The Response object containing the data. - * @param clazz The data object class. - * @return A Response object containing the data. - */ - private <T> Object authorizeSingleWithProbeId( - UserInfo userInfo, - Object data, - Class<T> clazz - ) { - try { - Method getProbeId = clazz.getMethod("getProbeId"); - Integer id = null; - if (getProbeId != null) { - id = (Integer) getProbeId.invoke(data); - } - else { - return null; - } - LProbe probe = - (LProbe)repository.getById(LProbe.class, id, "land").getData(); - - boolean readOnly = true; - boolean owner = false; - if (!userInfo.getNetzbetreiber().contains( - probe.getNetzbetreiberId())) { - owner = false; - readOnly = true; - } - else { - if (userInfo.getMessstellen().contains(probe.getMstId())) { - owner = true; - } - else { - owner = false; - } - readOnly = this.isReadOnly(id); - } - - Method setOwner = clazz.getMethod("setOwner", boolean.class); - Method setReadonly = clazz.getMethod("setReadonly", boolean.class); - setOwner.invoke(data, owner); - setReadonly.invoke(data, readOnly); - } catch (NoSuchMethodException | SecurityException - | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - return null; - } - return data; - } - - /** - * Authorize probe objects. - * - * @param userInfo The user information. - * @param data The Response object containing the probe objects. - * @return A Response object containing the data. - */ - @SuppressWarnings("unchecked") - private Response authorizeProbe(UserInfo userInfo, Response data) { - if (data.getData() instanceof List<?>) { - List<LProbe> proben = new ArrayList<LProbe>(); - for (LProbe probe :(List<LProbe>)data.getData()) { - proben.add(authorizeSingleProbe(userInfo, probe)); - } - data.setData(proben); - } - else if (data.getData() instanceof LProbe) { - LProbe probe = (LProbe)data.getData(); - data.setData(authorizeSingleProbe(userInfo, probe)); - } - return data; - } - - /** - * Authorize a sinle probe object. - * - * @param userInfo The user information. - * @param probe The probe object. - * @return The probe. - */ - private LProbe authorizeSingleProbe(UserInfo userInfo, LProbe probe) { - if (!userInfo.getNetzbetreiber().contains(probe.getNetzbetreiberId())) { - probe.setOwner(false); - probe.setReadonly(true); - return probe; - } - if (userInfo.getMessstellen().contains(probe.getMstId())) { - probe.setOwner(true); - } - else { - probe.setOwner(false); - } - probe.setReadonly(this.isReadOnly(probe.getId())); - return probe; - } - - /** - * Authorize messung objects. - * - * @param userInfo The user information. - * @param data The Response object containing the messung objects. - * @return A Response object containing the data. - */ - @SuppressWarnings("unchecked") - private Response authorizeMessung(UserInfo userInfo, Response data) { - if (data.getData() instanceof List<?>) { - List<LMessung> messungen = new ArrayList<LMessung>(); - for (LMessung messung :(List<LMessung>)data.getData()) { - messungen.add(authorizeSingleMessung(userInfo, messung)); - } - data.setData(messungen); - } - else if (data.getData() instanceof LMessung) { - LMessung messung = (LMessung)data.getData(); - data.setData(authorizeSingleMessung(userInfo, messung)); - } - return data; - } - - /** - * Authorize a sinle messung object. - * - * @param userInfo The user information. - * @param messung The messung object. - * @return The messung. - */ - private LMessung authorizeSingleMessung( - UserInfo userInfo, - LMessung messung - ) { - LProbe probe = - (LProbe)repository.getById( - LProbe.class, messung.getProbeId(), "land").getData(); - if (!userInfo.getNetzbetreiber().contains(probe.getNetzbetreiberId())) { - messung.setOwner(false); - messung.setReadonly(true); - return messung; - } - if (userInfo.getMessstellen().contains(probe.getMstId())) { - messung.setOwner(true); - } - else { - messung.setOwner(false); - } - messung.setReadonly(messung.getFertig()); - return messung; - } - - /** - * Test whether a probe is readonly. - * - * @param probeId The probe Id. - * @return True if the probe is readonly. - */ - @Override - public boolean isReadOnly(Integer probeId) { - EntityManager manager = repository.entityManager("land"); - QueryBuilder<LMessung> builder = - new QueryBuilder<LMessung>( - manager, - LMessung.class); - builder.and("probeId", probeId); - builder.and("fertig", true); - Response response = repository.filter(builder.getQuery(), "land"); - @SuppressWarnings("unchecked") - List<LMessung> messungen = (List<LMessung>) response.getData(); - if (messungen.isEmpty()) { - return false; - } - return true; - } - - /** - * Check whether a user is authorized to operate on the given probe. - * - * @param userInfo The user information. - * @param data The probe data to test. - * @return True if the user is authorized else returns false. - */ - @Override - public boolean isAuthorized(UserInfo userInfo, Object data) { - if (data instanceof LProbe) { - return getAuthorization(userInfo, (LProbe)data); - } - return false; - } -}
--- a/src/main/java/de/intevation/lada/util/auth/TestAuthorization.java Thu Aug 06 09:59:22 2015 +0200 +++ b/src/main/java/de/intevation/lada/util/auth/TestAuthorization.java Fri Aug 14 09:43:29 2015 +0200 @@ -14,7 +14,7 @@ import de.intevation.lada.util.rest.RequestMethod; import de.intevation.lada.util.rest.Response; -@AuthorizationConfig(type=AuthorizationType.OPEN_ID) +@AuthorizationConfig(type=AuthorizationType.NONE) public class TestAuthorization implements Authorization { @Override