diff --git a/android/feign/pom.xml b/android/feign/pom.xml new file mode 100644 index 0000000..9a69ca3 --- /dev/null +++ b/android/feign/pom.xml @@ -0,0 +1,146 @@ + + + + android + com.maptology + 0.0.1-SNAPSHOT + + 4.0.0 + com.maptology.android + feign + Maptology Android Feign + Source code of the generated client. + jar + + 1.5.15 + 9.4.0 + 2.1.0 + 2.8.9 + 1.0.1 + + + + + maven-dependency-plugin + + + + copy + + generate-sources + + + + com.maptology + api + ${project.version} + swagger + maptology.json + ${project.build.directory}/swagger/ + + + + + + + + + io.swagger + swagger-codegen-maven-plugin + 2.2.3 + + + + generate + + process-sources + + ${project.build.directory}/swagger/maptology.json + java + ${project.build.directory}/generated-sources/maptology/ + feign + false + false + false + false + false + com.maptology.android.feign + com.maptology.android.feign.api + com.maptology.android.feign.model + + + + + + + + + + com.maptology + api + ${project.version} + swagger + provided + + + + + io.swagger + swagger-annotations + ${version.swagger} + + + + + io.github.openfeign + feign-core + ${version.feign} + + + io.github.openfeign + feign-jackson + ${version.feign} + + + io.github.openfeign + feign-slf4j + ${version.feign} + + + io.github.openfeign.form + feign-form + ${version.feign-form} + + + + + com.fasterxml.jackson.core + jackson-core + ${version.jackson} + + + com.fasterxml.jackson.core + jackson-annotations + ${version.jackson} + + + com.fasterxml.jackson.core + jackson-databind + ${version.jackson} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${version.jackson} + + + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${version.oltu} + + + + diff --git a/android/feign/src/main/java/com/maptology/android/feign/ApiClient.java b/android/feign/src/main/java/com/maptology/android/feign/ApiClient.java new file mode 100644 index 0000000..d101578 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/ApiClient.java @@ -0,0 +1,319 @@ +package com.maptology.android.feign; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; + +import feign.Feign; +import feign.RequestInterceptor; +import feign.form.FormEncoder; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.slf4j.Slf4jLogger; +import com.maptology.android.feign.auth.*; +import com.maptology.android.feign.auth.OAuth.AccessTokenListener; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-20T17:10:12.901+02:00") +public class ApiClient { + public interface Api {} + + protected ObjectMapper objectMapper; + private String basePath = "https://maptology/api"; + private Map apiAuthorizations; + private Feign.Builder feignBuilder; + + public ApiClient() { + objectMapper = createObjectMapper(); + apiAuthorizations = new LinkedHashMap(); + feignBuilder = Feign.builder() + .encoder(new FormEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) + .logger(new Slf4jLogger()); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Feign.Builder getFeignBuilder() { + return feignBuilder; + } + + public ApiClient setFeignBuilder(Feign.Builder feignBuilder) { + this.feignBuilder = feignBuilder; + return this; + } + + private ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.setDateFormat(new RFC3339DateFormat()); + objectMapper.registerModule(new JodaModule()); + return objectMapper; + } + + public ObjectMapper getObjectMapper(){ + return objectMapper; + } + + /** + * Creates a feign client for given API interface. + * + * Usage: + * ApiClient apiClient = new ApiClient(); + * apiClient.setBasePath("http://localhost:8080"); + * XYZApi api = apiClient.buildClient(XYZApi.class); + * XYZResponse response = api.someMethod(...); + * @param Type + * @param clientClass Client class + * @return The Client + */ + public T buildClient(Class clientClass) { + return feignBuilder.target(clientClass, basePath); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Helper method to configure the first api key found + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return ; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure the username/password for basic auth or password OAuth + * @param username Username + * @param password Password + */ + public void setCredentials(String username, String password) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + throw new RuntimeException("No Basic authentication or OAuth configured!"); + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Authentication request builder + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken Access Token + * @param expiresIn Validity period in seconds + */ + public void setAccessToken(String accessToken, Long expiresIn) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken, expiresIn); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener Acesss token listener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Gets request interceptor based on authentication name + * @param authName Authentiation name + * @return Request Interceptor + */ + public RequestInterceptor getAuthorization(String authName) { + return apiAuthorizations.get(authName); + } + + /** + * Adds an authorization to be used by the client + * @param authName Authentication name + * @param authorization Request interceptor + */ + public void addAuthorization(String authName, RequestInterceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + feignBuilder.requestInterceptor(authorization); + } + +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/EncodingUtils.java b/android/feign/src/main/java/com/maptology/android/feign/EncodingUtils.java new file mode 100644 index 0000000..66d5eb4 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/EncodingUtils.java @@ -0,0 +1,86 @@ +package com.maptology.android.feign; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** +* Utilities to support Swagger encoding formats in Feign. +*/ +public final class EncodingUtils { + + /** + * Private constructor. Do not construct this class. + */ + private EncodingUtils() {} + + /** + *

Encodes a collection of query parameters according to the Swagger + * collection format.

+ * + *

Of the various collection formats defined by Swagger ("csv", "tsv", + * etc), Feign only natively supports "multi". This utility generates the + * other format types so it will be properly processed by Feign.

+ * + *

Note, as part of reformatting, it URL encodes the parameters as + * well.

+ * @param parameters The collection object to be formatted. This object will + * not be changed. + * @param collectionFormat The Swagger collection format (eg, "csv", "tsv", + * "pipes"). See the + * + * Swagger Spec for more details. + * @return An object that will be correctly formatted by Feign. + */ + public static Object encodeCollection(Collection parameters, + String collectionFormat) { + if (parameters == null) { + return parameters; + } + List stringValues = new ArrayList<>(parameters.size()); + for (Object parameter : parameters) { + // ignore null values (same behavior as Feign) + if (parameter != null) { + stringValues.add(encode(parameter)); + } + } + // Feign natively handles single-element lists and the "multi" format. + if (stringValues.size() < 2 || "multi".equals(collectionFormat)) { + return stringValues; + } + // Otherwise return a formatted String + String[] stringArray = stringValues.toArray(new String[0]); + switch (collectionFormat) { + case "csv": + default: + return StringUtil.join(stringArray, ","); + case "ssv": + return StringUtil.join(stringArray, " "); + case "tsv": + return StringUtil.join(stringArray, "\t"); + case "pipes": + return StringUtil.join(stringArray, "|"); + } + } + + /** + * URL encode a single query parameter. + * @param parameter The query parameter to encode. This object will not be + * changed. + * @return The URL encoded string representation of the parameter. If the + * parameter is null, returns null. + */ + public static String encode(Object parameter) { + if (parameter == null) { + return null; + } + try { + return URLEncoder.encode(parameter.toString(), "UTF-8"); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/ParamExpander.java b/android/feign/src/main/java/com/maptology/android/feign/ParamExpander.java new file mode 100644 index 0000000..7f65a97 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/ParamExpander.java @@ -0,0 +1,22 @@ +package com.maptology.android.feign; + +import feign.Param; + +import java.text.DateFormat; +import java.util.Date; + +/** + * Param Expander to convert {@link Date} to RFC3339 + */ +public class ParamExpander implements Param.Expander { + + private static final DateFormat dateformat = new RFC3339DateFormat(); + + @Override + public String expand(Object value) { + if (value instanceof Date) { + return dateformat.format(value); + } + return value.toString(); + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/RFC3339DateFormat.java b/android/feign/src/main/java/com/maptology/android/feign/RFC3339DateFormat.java new file mode 100644 index 0000000..c02003b --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Maptology Service + * Maptology Service + * + * OpenAPI spec version: 0.0.1-SNAPSHOT + * Contact: nes-admin@uni-due.de + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +package com.maptology.android.feign; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/android/feign/src/main/java/com/maptology/android/feign/StringUtil.java b/android/feign/src/main/java/com/maptology/android/feign/StringUtil.java new file mode 100644 index 0000000..3041178 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/StringUtil.java @@ -0,0 +1,55 @@ +/* + * Maptology Service + * Maptology Service + * + * OpenAPI spec version: 0.0.1-SNAPSHOT + * Contact: nes-admin@uni-due.de + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.maptology.android.feign; + +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-10-20T17:10:12.901+02:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/auth/ApiKeyAuth.java b/android/feign/src/main/java/com/maptology/android/feign/auth/ApiKeyAuth.java new file mode 100644 index 0000000..dad7a02 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/auth/ApiKeyAuth.java @@ -0,0 +1,41 @@ +package com.maptology.android.feign.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class ApiKeyAuth implements RequestInterceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public void apply(RequestTemplate template) { + if ("query".equals(location)) { + template.query(paramName, apiKey); + } else if ("header".equals(location)) { + template.header(paramName, apiKey); + } + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/auth/HttpBasicAuth.java b/android/feign/src/main/java/com/maptology/android/feign/auth/HttpBasicAuth.java new file mode 100644 index 0000000..855f2d0 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package com.maptology.android.feign.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.auth.BasicAuthRequestInterceptor; + +/** + * An interceptor that adds the request header needed to use HTTP basic authentication. + */ +public class HttpBasicAuth implements RequestInterceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public void apply(RequestTemplate template) { + RequestInterceptor requestInterceptor = new BasicAuthRequestInterceptor(username, password); + requestInterceptor.apply(template); + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/auth/OAuth.java b/android/feign/src/main/java/com/maptology/android/feign/auth/OAuth.java new file mode 100644 index 0000000..8eff7a4 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/auth/OAuth.java @@ -0,0 +1,197 @@ +package com.maptology.android.feign.auth; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import feign.Client; +import feign.Request.Options; +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.Response; +import feign.RetryableException; +import feign.Util; +import com.maptology.android.feign.StringUtil; + + +public class OAuth implements RequestInterceptor { + + static final int MILLIS_PER_SECOND = 1000; + + public interface AccessTokenListener { + void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private Long expirationTimeMillis; + private OAuthClient oauthClient; + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + + public OAuth(Client client, TokenRequestBuilder requestBuilder) { + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); + } + + @Override + public void apply(RequestTemplate template) { + // If the request already have an authorization (eg. Basic auth), do nothing + if (template.headers().containsKey("Authorization")) { + return; + } + // If first time, get the token + if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { + updateAccessToken(); + } + if (getAccessToken() != null) { + template.header("Authorization", "Bearer " + getAccessToken()); + } + } + + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } + } + + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken, Long expiresIn) { + this.accessToken = accessToken; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + + public OAuthClient getOauthClient() { + return oauthClient; + } + + public void setOauthClient(OAuthClient oauthClient) { + this.oauthClient = oauthClient; + } + + public void setOauthClient(Client client) { + this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); + } + + public static class OAuthFeignClient implements HttpClient { + + private Client client; + + public OAuthFeignClient() { + this.client = new Client.Default(null, null); + } + + public OAuthFeignClient(Client client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + RequestTemplate req = new RequestTemplate() + .append(request.getLocationUri()) + .method(requestMethod) + .body(request.getBody()); + + for (Entry entry : headers.entrySet()) { + req.header(entry.getKey(), entry.getValue()); + } + Response feignResponse; + String body = ""; + try { + feignResponse = client.execute(req.request(), new Options()); + body = Util.toString(feignResponse.body().asReader()); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + + String contentType = null; + Collection contentTypeHeader = feignResponse.headers().get("Content-Type"); + if(contentTypeHeader != null) { + contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";"); + } + + return OAuthClientResponseFactory.createCustomResponse( + body, + contentType, + feignResponse.status(), + responseClass + ); + } + + public void shutdown() { + // Nothing to do here + } + } +} diff --git a/android/feign/src/main/java/com/maptology/android/feign/auth/OAuthFlow.java b/android/feign/src/main/java/com/maptology/android/feign/auth/OAuthFlow.java new file mode 100644 index 0000000..d3c8124 --- /dev/null +++ b/android/feign/src/main/java/com/maptology/android/feign/auth/OAuthFlow.java @@ -0,0 +1,18 @@ +/* + * Maptology Service + * Maptology Service + * + * OpenAPI spec version: 0.0.1-SNAPSHOT + * Contact: nes-admin@uni-due.de + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package com.maptology.android.feign.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} diff --git a/android/pom.xml b/android/pom.xml index 8a9866e..d5877c4 100644 --- a/android/pom.xml +++ b/android/pom.xml @@ -7,11 +7,9 @@ all 0.0.1-SNAPSHOT - com.maptology android Maptology Android Android code for maptology. - 0.0.1-SNAPSHOT pom 7.0_r2 @@ -19,6 +17,7 @@ app + feign leafless diff --git a/api/pom.xml b/api/pom.xml new file mode 100644 index 0000000..5a8b994 --- /dev/null +++ b/api/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + com.maptology + all + 0.0.1-SNAPSHOT + + api + Maptology Api + Api of the maptology service. + + + + + com.github.kongchen + swagger-maven-plugin + + + process-classes + + generate + + + + + + + false + + com.maptology.api.user.IUserService + + https + maptology + /api + + Maptology Service + ${project.version} + + Maptology Service + + https://maptology.com/terms-of-service + + NES Universität Duisburg-Essen + nes-admin@uni-due.de + https://www.nes.uni-due.de + + + https://maptology.com/license + Proprietary + + + maptology + ${basedir}/target/swagger/ + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + package + + attach-artifact + + + + + ${basedir}/target/swagger/maptology.json + swagger + + + + + + + + + + + + javax + javaee-api + 7.0 + provided + + + io.swagger + swagger-annotations + 1.5.16 + provided + + + com.fasterxml.jackson.core + jackson-annotations + 2.6.3 + provided + + + diff --git a/api/src/main/java/com/maptology/api/Entity.java b/api/src/main/java/com/maptology/api/Entity.java new file mode 100644 index 0000000..6b4a162 --- /dev/null +++ b/api/src/main/java/com/maptology/api/Entity.java @@ -0,0 +1,129 @@ +package com.maptology.api; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +import io.swagger.annotations.ApiModelProperty; + + +/** + * An abstract base class for data that has a unique identifier, + * a creation data, a modification date and a flag to indicate + * whether it has been deleted or not. + * + * @author Marcus + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +public abstract class Entity { + + /** + * The unique identifier of the data. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The unique identifier of the data.", readOnly=true, required=true) + private long id; + + /** + * The time stamp when the data was created. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The time stamp when the data was created.", readOnly=true, required=true) + private long creationTime; + + /** + * The time stamp when the data was last modified. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The time stamp when the data was created.", readOnly=true, required=true) + private long modificationTime; + + /** + * A flag to indicate wether the data was deleted. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A flag to indicate whether the data was deleted.", readOnly=true, required=true) + private boolean deleted; + + /** + * Returns the id. + * + * @return The id. + */ + public long getId() { + return id; + } + + /** + * Sets the id. + * + * @param id The id to set. + */ + public void setId(long id) { + this.id = id; + } + + /** + * Returns the creation time. + * + * @return The creation time. + */ + public long getCreationTime() { + return creationTime; + } + + /** + * Sets the creation time in Epoch milliseconds. + * + * @param creationTime The creation time to set. + */ + public void setCreationTime(long creationTime) { + this.creationTime = creationTime; + } + + /** + * Returns the modification time in Epoch milliseconds. + * + * @return The modification time. + */ + public long getModificationTime() { + return modificationTime; + } + + /** + * Sets the modificationTime. + * + * @param modificationTime The modificationTime to set. + */ + public void setModificationTime(long modificationTime) { + this.modificationTime = modificationTime; + } + + /** + * Returns the deleted flag. + * + * @return The deleted flag. + */ + public boolean isDeleted() { + return deleted; + } + + /** + * Sets the deleted flag that marks an entity as deleted. + * + * @param deleted The deleted to set. + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + +} diff --git a/api/src/main/java/com/maptology/api/Page.java b/api/src/main/java/com/maptology/api/Page.java new file mode 100644 index 0000000..0b3656e --- /dev/null +++ b/api/src/main/java/com/maptology/api/Page.java @@ -0,0 +1,131 @@ +package com.maptology.api; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +/** + * An abstract base class for pages. + * + * @author Marcus + * + * @param The type of the element on the page. + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +public abstract class Page { + + /** + * The size of the page, i.e. the maximum number of elements. + */ + @XmlAttribute(required=true) + private int size; + + /** + * The offset of the elements (0-based). + */ + @XmlAttribute(required=true) + private int offset; + + /** + * The total number of elements available. + */ + @XmlAttribute(required=true) + private int total; + + /** + * The elements on the page (up to size). + */ + @XmlElementWrapper + @XmlElement(name="element") + private List elements = new ArrayList<>(); + + /** + * Returns the size. + * + * @return The size. + */ + public int getSize() { + return size; + } + + /** + * Sets the size. + * + * @param size The size to set. + */ + public void setSize(int size) { + this.size = size; + } + + /** + * Returns the offset. + * + * @return The offset. + */ + public int getOffset() { + return offset; + } + + /** + * Sets the offset. + * + * @param offset The offset to set. + */ + public void setOffset(int offset) { + this.offset = offset; + } + + /** + * Returns the total. + * + * @return The total. + */ + public int getTotal() { + return total; + } + + /** + * Sets the total. + * + * @param total The total to set. + */ + public void setTotal(int total) { + this.total = total; + } + + /** + * Returns the elements. + * + * @return The elements. + */ + public List getElements() { + return elements; + } + + /** + * Sets the elements. + * + * @param elements The elements to set. + */ + public void setElements(List elements) { + this.elements = elements; + } + + + + +} diff --git a/api/src/main/java/com/maptology/api/PageConfig.java b/api/src/main/java/com/maptology/api/PageConfig.java new file mode 100644 index 0000000..9cc6af5 --- /dev/null +++ b/api/src/main/java/com/maptology/api/PageConfig.java @@ -0,0 +1,66 @@ +package com.maptology.api; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.QueryParam; + +/** + * A bean parameter to configure a page. + * + * @author Marcus + * + */ +public class PageConfig { + + /** + * The page offset in terms of elements. + */ + @QueryParam("pageOffset") + @DefaultValue("0") + private int offset; + + /** + * The maximum number of elements on the page. + */ + @QueryParam("pageSize") + @DefaultValue("20") + private int size; + + /** + * Returns the offset. + * + * @return The offset. + */ + public int getOffset() { + return offset; + } + + /** + * Sets the offset. + * + * @param offset The offset to set. + */ + public void setOffset(int offset) { + this.offset = offset; + } + + /** + * Returns the size. + * + * @return The size. + */ + public int getSize() { + return size; + } + + /** + * Sets the size. + * + * @param size The size to set. + */ + public void setSize(int size) { + this.size = size; + } + + + +} diff --git a/api/src/main/java/com/maptology/api/access/PrincipalRequired.java b/api/src/main/java/com/maptology/api/access/PrincipalRequired.java new file mode 100644 index 0000000..34a9d35 --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/PrincipalRequired.java @@ -0,0 +1,33 @@ +package com.maptology.api.access; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.ws.rs.NameBinding; + +/** + * An annotation to limit access to a method to a particular + * user or group of user. Note that this can also be used + * to require that any user is logged in. + * + * @author Marcus + */ +@Documented +@Inherited +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface PrincipalRequired { + + /** + * A regular expression that will be matched against + * principal names of a caller. + * + * @return The regular expression. + */ + String value() default ".*"; +} diff --git a/api/src/main/java/com/maptology/api/access/RoleRequired.java b/api/src/main/java/com/maptology/api/access/RoleRequired.java new file mode 100644 index 0000000..b8ad012 --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/RoleRequired.java @@ -0,0 +1,37 @@ +package com.maptology.api.access; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.ws.rs.NameBinding; + +/** + * An annotation to demand that the caller principal has + * a set of roles. Note that a user must have all roles + * defined in the annotation value. To define optional + * sets, use the RolesRequired annotation to define + * multiple sets. + * + * @author Marcus + */ +@Documented +@Inherited +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface RoleRequired { + + /** + * The set of roles that a principal must exhibit. + * Note that the principal must exhibit all roles + * simultaneously. + * + * @return The roles required. + */ + Roles[] value(); + +} diff --git a/api/src/main/java/com/maptology/api/access/Roles.java b/api/src/main/java/com/maptology/api/access/Roles.java new file mode 100644 index 0000000..b31754f --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/Roles.java @@ -0,0 +1,21 @@ +package com.maptology.api.access; + +/** + * The user roles used by the application. + * + * @author Marcus + */ +public enum Roles { + /** + * The role that grants system administration privileges. + */ + ADMIN, + /** + * The role that grants user login privileges. + */ + USER, + /** + * The role that grants data submission privileges. + */ + APP +} diff --git a/api/src/main/java/com/maptology/api/access/RolesRequired.java b/api/src/main/java/com/maptology/api/access/RolesRequired.java new file mode 100644 index 0000000..5dd2f56 --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/RolesRequired.java @@ -0,0 +1,32 @@ +package com.maptology.api.access; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.ws.rs.NameBinding; + +/** + * An annotation to allow the definition of optional groups of roles required by + * the caller prinicpal. + * + * @author Marcus + */ +@Documented +@Inherited +@NameBinding +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD}) +public @interface RolesRequired { + + /** + * A set of alternative role sets that is allowed to access a method. + * + * @return The alternative roles required by the user. + */ + RoleRequired[] value(); + +} diff --git a/api/src/main/java/com/maptology/api/access/package-info.java b/api/src/main/java/com/maptology/api/access/package-info.java new file mode 100644 index 0000000..fb57a88 --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/package-info.java @@ -0,0 +1,9 @@ +/** + * This package defines the basic roles for role-based + * access control. In addition, it defines annotations + * that can be used to define access restrictions on + * resource methods. + * + * @author Marcus + */ +package com.maptology.api.access; \ No newline at end of file diff --git a/api/src/main/java/com/maptology/api/user/Email.java b/api/src/main/java/com/maptology/api/user/Email.java new file mode 100644 index 0000000..c447547 --- /dev/null +++ b/api/src/main/java/com/maptology/api/user/Email.java @@ -0,0 +1,95 @@ +package com.maptology.api.user; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import com.maptology.api.Entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * An email address of a particular user. + * + * @author Marcus + */ +@XmlRootElement +@ApiModel(description="Represents a user.", parent=Entity.class) +public class Email extends Entity { + + /** + * The email address. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The email address.", required=true) + private String address; + + /** + * A flag to mark the email address as primary email. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A flag to mark the email address as primary email.", required=true) + private boolean correspondence; + + /** + * A flag to mark the email address as verified. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A flag to mark the email address as verified.", required=true) + private boolean verified; + + /** + * Returns the address. + * + * @return The address. + */ + public String getAddress() { + return address; + } + + /** + * Sets the address. + * + * @param address The address to set. + */ + public void setAddress(String address) { + this.address = address; + } + + /** + * Returns the correspondence. + * + * @return The correspondence. + */ + public boolean isCorrespondence() { + return correspondence; + } + + /** + * Sets the correspondence. + * + * @param correspondence The correspondence to set. + */ + public void setCorrespondence(boolean correspondence) { + this.correspondence = correspondence; + } + + /** + * Returns the verified. + * + * @return The verified. + */ + public boolean isVerified() { + return verified; + } + + /** + * Sets the verified. + * + * @param verified The verified to set. + */ + public void setVerified(boolean verified) { + this.verified = verified; + } + +} diff --git a/api/src/main/java/com/maptology/api/user/IUserService.java b/api/src/main/java/com/maptology/api/user/IUserService.java new file mode 100644 index 0000000..1bfbc3c --- /dev/null +++ b/api/src/main/java/com/maptology/api/user/IUserService.java @@ -0,0 +1,45 @@ +package com.maptology.api.user; + +import javax.ws.rs.BeanParam; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import com.maptology.api.PageConfig; +import com.maptology.api.access.PrincipalRequired; +import com.maptology.api.access.RoleRequired; +import com.maptology.api.access.Roles; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +/** + * A service to retrieve users. + * + * @author Marcus + */ +@Api +@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@Path("/") +public interface IUserService { + + /** + * Returns a list of users as a page. + * + * @return The list of users as page. + */ + @GET + @Path("users") + @ApiOperation(value = "Returns a list of users.", response = UserPage.class) + @RoleRequired({ Roles.ADMIN }) + Response getUsers(@BeanParam PageConfig pageConfig); + + @GET + @Path("users/current") + @ApiOperation(value = "Returns the current (logged-in) user.", response = User.class) + @PrincipalRequired + Response getCurrentUser(); + +} diff --git a/api/src/main/java/com/maptology/api/user/User.java b/api/src/main/java/com/maptology/api/user/User.java new file mode 100644 index 0000000..34ffd3b --- /dev/null +++ b/api/src/main/java/com/maptology/api/user/User.java @@ -0,0 +1,152 @@ +package com.maptology.api.user; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +import com.maptology.api.Entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A data transfer object for a user with associated swagger and + * jaxb annotations that supports xml and json serialization. + * + * @author Marcus + */ +@XmlRootElement +@ApiModel(description="Represents a user.", parent=Entity.class) +public class User extends Entity { + + /** + * The (globally unique) login of the user. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The (globally unique) login of the user.", required=true) + private String login; + + /** + * The human name of the user. + */ + @XmlAttribute(required=false) + @ApiModelProperty(value="The human name of the user.", required=false) + private String name; + + /** + * A flag to indicate that user account is suspended. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A flag to indicate that user account is suspended.", required=true) + private boolean suspended; + + /** + * The list of roles of the user. + */ + @XmlElementWrapper + @XmlElement(name="role") + private List roles = new ArrayList<>(); + + /** + * The email accounts of the user. + */ + @XmlElementWrapper + @XmlElement(name="email") + private List emails = new ArrayList<>(); + + /** + * Returns the login. + * + * @return The login. + */ + public String getLogin() { + return login; + } + + /** + * Sets the login. + * + * @param login The login to set. + */ + public void setLogin(String login) { + this.login = login; + } + + /** + * Returns the name. + * + * @return The name. + */ + public String getName() { + return name; + } + + /** + * Returns the suspended. + * + * @return The suspended. + */ + public boolean isSuspended() { + return suspended; + } + + /** + * Sets the suspended. + * + * @param suspended The suspended to set. + */ + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } + + /** + * Sets the name. + * + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the roles. + * + * @return The roles. + */ + public List getRoles() { + return roles; + } + + /** + * Sets the roles. + * + * @param roles The roles to set. + */ + public void setRoles(List roles) { + this.roles = roles; + } + + /** + * Returns the emails. + * + * @return The emails. + */ + public List getEmails() { + return emails; + } + + /** + * Sets the emails. + * + * @param emails The emails to set. + */ + public void setEmails(List emails) { + this.emails = emails; + } + + +} diff --git a/api/src/main/java/com/maptology/api/user/UserPage.java b/api/src/main/java/com/maptology/api/user/UserPage.java new file mode 100644 index 0000000..0861c3f --- /dev/null +++ b/api/src/main/java/com/maptology/api/user/UserPage.java @@ -0,0 +1,19 @@ +package com.maptology.api.user; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSeeAlso; + +import com.maptology.api.Page; + +/** + * A page containing users. This class simply + * materializes the page for users so that + * clients can infer the type. + * + * @author Marcus + */ +@XmlRootElement +@XmlSeeAlso(User.class) +public class UserPage extends Page { + +} diff --git a/pom.xml b/pom.xml index cf059ef..7618992 100644 --- a/pom.xml +++ b/pom.xml @@ -12,6 +12,7 @@ UTF-8 + api android service web @@ -19,9 +20,10 @@ + org.apache.maven.plugins maven-source-plugin - 2.4 + 3.0.1 attach-sources @@ -37,26 +39,102 @@ + + + maven-surefire-plugin + 2.20.1 + + + maven-dependency-plugin + 3.0.2 + + + maven-ear-plugin + 2.10.1 + + + maven-ejb-plugin + 3.0.0 + + + maven-war-plugin + 3.2.0 + maven-compiler-plugin - 2.5.1 + 3.7.0 + 1.7 1.7 + + com.github.kongchen + swagger-maven-plugin + 3.1.5 + + + io.swagger + swagger-codegen-maven-plugin + 2.2.3 + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + com.github.kongchen + swagger-maven-plugin + [1.0.0,) + + generate + + + + + + + + + io.swagger + sswagger-codegen-maven-plugin + [1.0.0,) + + generate + + + + + + + + + + - - - junit - junit - jar - 4.12 - test - - + + + + junit + junit + jar + 4.12 + test + + diff --git a/service/ear/pom.xml b/service/ear/pom.xml new file mode 100644 index 0000000..ab35590 --- /dev/null +++ b/service/ear/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + com.maptology + service + 0.0.1-SNAPSHOT + + com.maptology.service + ear + Maptology Service Ear + Ear with the maptology service. + 0.0.1-SNAPSHOT + ear + + + + maven-ear-plugin + + maptology + + + com.maptology.service + ejb + + + com.maptology.service + war + api + + + 7 + lib + + + true + + + ${jenkins.build.number} + + + false + full + + + + + + + com.maptology.service + ejb + ${project.version} + ejb + + + com.maptology.service + war + war + ${project.version} + + + diff --git a/service/ejb/pom.xml b/service/ejb/pom.xml new file mode 100644 index 0000000..669529a --- /dev/null +++ b/service/ejb/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.maptology + service + 0.0.1-SNAPSHOT + + com.maptology.service + ejb + Maptology Service Ejb + Ejbs for the maptology service. + ejb + + + + maven-ejb-plugin + + + + true + + + ${jenkins.build.number} + + + + + + + + + com.maptology + api + ${project.version} + + + javax + javaee-api + 7.0 + provided + + + diff --git a/service/ejb/src/main/java/com/maptology/service/crypto/SecureHash.java b/service/ejb/src/main/java/com/maptology/service/crypto/SecureHash.java new file mode 100644 index 0000000..a57131c --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/crypto/SecureHash.java @@ -0,0 +1,187 @@ +package com.maptology.service.crypto; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Arrays; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +/** + * Implements secure password hashing using a memory hard key derivation + * function (PBKDF2). The java crypto code is taken from + * this article and the values for constants is based on + * this + * article. + * + * @author Marcus + * + */ +public class SecureHash { + + /** + * The default size of the salt in bytes (recommended minimum 8). + */ + public static int SALT_SIZE = 16; + + /** + * The size of the hash in bytes (recommended 64 -> 512 bits). + */ + public static int HASH_SIZE = 64; + + /** + * The default number of iterations to use (recommended >10000). + */ + public static int HASH_ITERATIONS = 12000; + + /** + * The salt used to compute the hash. + */ + private byte[] salt; + + /** + * The number of iterations. + */ + private int iterations; + + /** + * The hash. + */ + private byte[] hash; + + /** + * Creates a secure hash from a password using a newly generated salt and + * the default number of iterations. This method is intended to generate + * the hash, salt and iterations for a newly set password. + * + * @param password The password. + * @throws SecureHashException Thrown if the hash cannot be computed due to + * an unavailable algorithm. + */ + public SecureHash(String password) { + this.iterations = HASH_ITERATIONS; + this.salt = createSalt(SALT_SIZE); + this.hash = createHash(iterations, salt, password.toCharArray()); + } + + /** + * Creates a secure hash from a given number of iterations, a salt and + * a hash value. + * + * @param iterations The iterations. + * @param salt The salt. + * @param hash The hash value. + */ + public SecureHash(int iterations, byte[] salt, byte[] hash) { + this.iterations = iterations; + this.salt = salt; + this.hash = hash; + } + + /** + * Returns the hash value. + * + * @return The hash value. + */ + public byte[] getHash() { + return hash; + } + + /** + * Returns the number of iterations. + * + * @return The number of iterations. + */ + public int getIterations() { + return iterations; + } + + /** + * Returns the salt. + * + * @return The salt. + */ + public byte[] getSalt() { + return salt; + } + + /** + * Verifies the password against the hash. + * + * @param password The password to verify. + * @return True if the hashed password equals the secure hash. + * @throws SecureHashException Thrown if the hash cannot be computed due to + * an unavailable algorithm. + */ + public boolean verify(String password) { + byte[] h = createHash(iterations, salt, password.toCharArray()); + return Arrays.equals(h, hash); + } + + + @Override + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != getClass()) + return false; + SecureHash h = (SecureHash) obj; + return h.iterations == iterations && Arrays.equals(h.salt, salt) && Arrays.equals(h.hash, hash); + } + + @Override + public int hashCode() { + int code = iterations; + code = 37 * code + Arrays.hashCode(salt); + code = 37 * code + Arrays.hashCode(hash); + return code; + + } + + /** + * Creates a salt of the specified length. + * + * @param length The length in bytes. + * @return The salt. + * @throws SecureHashException Thrown if the salt cannot be computed due to + * an unavailable algorithm. + */ + private static byte[] createSalt(int length) { + try { + SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); + byte[] salt = new byte[length]; + sr.nextBytes(salt); + return salt; + } catch (Exception e) { + throw new SecureHashException("Failed to create salt.", e); + } + } + + /** + * Creates a hash that is computed using PBDKF2 under a salt, with a number + * of iterations. + * + * @param iterations The iterations. + * @param salt The salt. + * @param password The password. + * @return The sequence of bytes constituting the hash. + * @throws SecureHashException Thrown if the hash cannot be computed due to + * an unavailable algorithm. + */ + private static byte[] createHash(int iterations, byte[] salt, char[] password) { + try { + PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, HASH_SIZE * 8); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + return skf.generateSecret(spec).getEncoded(); + } catch (Exception e) { + throw new SecureHashException("Failed to create hash.", e); + } + } + + @Override + public String toString() { + BigInteger s = new BigInteger(salt); + BigInteger h = new BigInteger(hash); + return iterations + ":" + s.toString(16) + ":" + h.toString(16); + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/crypto/SecureHashException.java b/service/ejb/src/main/java/com/maptology/service/crypto/SecureHashException.java new file mode 100644 index 0000000..e432685 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/crypto/SecureHashException.java @@ -0,0 +1,25 @@ +package com.maptology.service.crypto; + +/** + * An exception thrown if a crypto algorithm is not available. + * + * @author Marcus + */ +public class SecureHashException extends RuntimeException { + + /** + * The serialization version. + */ + private static final long serialVersionUID = 2437081630235766887L; + + /** + * Creates a new exception with the message and cause. + * + * @param message The message. + * @param cause The root cause. + */ + public SecureHashException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java new file mode 100644 index 0000000..8895a2e --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java @@ -0,0 +1,130 @@ +package com.maptology.service.entity; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.SequenceGenerator; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +@SequenceGenerator(name = "uid_generator", sequenceName = "UID_GENERATOR", initialValue=1, allocationSize=1) +@SuppressWarnings("serial") +public abstract class AbstractEntity implements Serializable { + + /** + * The unique id generator that we use for all entities stored in + * the database. Since we are using a long as an identifier, there + * is no need to have separate generators. Also note that the + * generator is 1-based and not 0-based which allows us to use + * 0 to determine whether an entity is new or has been stored already. + */ + @Id + @GeneratedValue(strategy = GenerationType.AUTO, generator = "uid_generator") + private long id; + + /** + * The initial creation time stamp in Epoch milliseconds. + */ + private long creationTime; + + /** + * The last modification time stamp in Epoch milliseconds. + */ + private long modificationTime; + + /** + * A flag to indicate whether the entity has been deleted. Instead + * of deleting stuff from the database, we rather mark it as deleted. + * This allows us to restore accidentally deleted entities. + */ + private boolean deleted; + + /** + * Automatically sets the creation date. + */ + @PrePersist + protected void onCreate() { + creationTime = System.currentTimeMillis(); + modificationTime = System.currentTimeMillis(); + } + + /** + * Automatically updates the modification date. + */ + @PreUpdate + protected void onUpdate() { + modificationTime = Math.max(System.currentTimeMillis(), modificationTime + 1); + } + + /** + * Enables manually changing the object, even if there is nothing to change. + */ + public void touch() { + modificationTime = Math.max(System.currentTimeMillis(), modificationTime + 1); + } + + /** + * Returns the id of the entity. + * + * @return The id of the entity. + */ + public long getId() { + return id; + } + + /** + * Determines whether the id of the entity is the + * new id, meaning that the entity has not been + * persisted. + * + * @return True if the id is the new id. + */ + public boolean isNew() { + return id <= 0; + } + + /** + * Returns the creation time in Epoch milliseconds. + * + * @return The creation time in Epoch milliseconds. + */ + public long getCreationTime() { + return creationTime; + } + + /** + * Returns the modification time in Epoch milliseconds. + * + * @return The modification time in Epoch milliseconds. + */ + public long getModificationTime() { + return modificationTime; + } + + /** + * Marks the entity as deleted or restores a deleted + * entity. + * + * @param deleted True to delete, false to restore. + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + /** + * Determines whether the entity is deleted. + * + * @return True if deleted. + */ + public boolean isDeleted() { + return deleted; + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/CodeEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/user/CodeEntity.java new file mode 100644 index 0000000..82dca7e --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/CodeEntity.java @@ -0,0 +1,18 @@ +package com.maptology.service.entity.user; + +import com.maptology.service.entity.AbstractEntity; + +/** + * The entity that represents codes sent out to the user. + * + * @author Marcus + */ +public class CodeEntity extends AbstractEntity { + + /** + * Serialization version. + */ + private static final long serialVersionUID = 2477619107225809934L; + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/Codes.java b/service/ejb/src/main/java/com/maptology/service/entity/user/Codes.java new file mode 100644 index 0000000..758732f --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/Codes.java @@ -0,0 +1,20 @@ +package com.maptology.service.entity.user; + +/** + * Constants used to differentiate generated codes + * sent out to the user. + * + * @author Marcus + */ +public enum Codes { + + /** + * The code to verify email addresses. + */ + VERIFY, + /** + * The code type to reset passwords. + */ + RESET; + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/EmailEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/user/EmailEntity.java new file mode 100644 index 0000000..d80f7ec --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/EmailEntity.java @@ -0,0 +1,123 @@ +package com.maptology.service.entity.user; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +import com.maptology.service.entity.AbstractEntity; + +/** + * An entity to manage email addresses of users. + * + * @author Marcus + */ +@Entity +@Table(name="email", uniqueConstraints=@UniqueConstraint(columnNames= {"user_id", "address"})) +public class EmailEntity extends AbstractEntity { + + /** + * The serialization version. + */ + private static final long serialVersionUID = -377353791989186093L; + + /** + * The user that has this email address. + */ + @NotNull + @ManyToOne + private UserEntity user; + + /** + * The actual email address. + */ + @NotNull + @Pattern(regexp=".+@.+\\..+", message="Invalid email address format.") + private String address; + + /** + * A flag to determine whether this email is verified. + */ + private boolean verified; + + /** + * A flag to determine whether this email is the primary email. + */ + private boolean correspondence; + + /** + * Returns the user. + * + * @return The user. + */ + public UserEntity getUser() { + return user; + } + + /** + * Sets the user. + * + * @param user The user to set. + */ + public void setUser(UserEntity user) { + this.user = user; + } + + /** + * Returns the address. + * + * @return The address. + */ + public String getAddress() { + return address; + } + + /** + * Sets the address. + * + * @param address The address to set. + */ + public void setAddress(String address) { + this.address = address; + } + + /** + * Returns the verified. + * + * @return The verified. + */ + public boolean isVerified() { + return verified; + } + + /** + * Sets the verified. + * + * @param verified The verified to set. + */ + public void setVerified(boolean verified) { + this.verified = verified; + } + + /** + * Returns the correspondence flag. + * + * @return The correspondence flag. + */ + public boolean isCorrespondence() { + return correspondence; + } + + /** + * Sets the correspondence flag. + * + * @param correspondence The correspondence to set. + */ + public void setCorrespondence(boolean correspondence) { + this.correspondence = correspondence; + } + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/RoleEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/user/RoleEntity.java new file mode 100644 index 0000000..73c2e78 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/RoleEntity.java @@ -0,0 +1,97 @@ +package com.maptology.service.entity.user; + +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ManyToMany; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import javax.validation.constraints.NotNull; + +import com.maptology.service.entity.AbstractEntity; + +/** + * An entity to define user roles. + * + * @author Marcus + */ +@Entity +@Table(name="role", uniqueConstraints=@UniqueConstraint(columnNames="name")) +@NamedQueries({ + @NamedQuery(name="findRoleByName", query="select r from RoleEntity r where r.name=:name"), + @NamedQuery(name="findRoles", query="select r from RoleEntity r") +}) +public class RoleEntity extends AbstractEntity { + + /** + * The serialization id. + */ + private static final long serialVersionUID = 7657274432924335496L; + + /** + * The name of the role. + */ + @NotNull + private String name; + + /** + * A human readable description of the role. + */ + @NotNull + private String description; + + /** + * The users that have this role. + */ + @ManyToMany(fetch=FetchType.LAZY, mappedBy="roles") + private Set users; + + /** + * Returns the name. + * + * @return The name. + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the description. + * + * @return The description. + */ + public String getDescription() { + return description; + } + + /** + * Sets the description. + * + * @param description The description to set. + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the users. + * + * @return The users. + */ + public Set getUsers() { + return users; + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java new file mode 100644 index 0000000..15fcde5 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java @@ -0,0 +1,237 @@ +package com.maptology.service.entity.user; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +import com.maptology.service.entity.AbstractEntity; + +/** + * The entity to store users. + * + * @author Marcus + */ +@Entity +@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "login")) +@NamedQueries({ + @NamedQuery(name="findUsers", query="select u from UserEntity u"), + @NamedQuery(name="findUserByLogin", query="select u from UserEntity u where u.login=:login") +}) +public class UserEntity extends AbstractEntity { + + /** + * The serialization id. + */ + private static final long serialVersionUID = -5741461462663188231L; + + /** + * The (human) name of the user. + */ + @NotNull + @Pattern(regexp = "(\\p{L}| ){0,64}", message = "Invalid name format (only letters and space, maximum 64 characters).") + @Column(length=64) + private String name; + + /** + * The (unique) login of the user. + */ + @Pattern(regexp = "(\\p{L}|[0-9]){5,32}", message = "Invalid login format (only letters an numbers, minimum 5 and maximum 32 characters).") + @Column(length=32) + private String login; + + /** + * The roles of the user. This is the owning relationship, so changes to user + * roles must be made on this set. + */ + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) + private Set roles; + + /** + * The email addresses of the user. This is not the owning relationship, so + * email address should be changed by setting the user on the email instead. + */ + @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") + private Set emails; + + /** + * The iterations of the password hash. + */ + private int iterations; + + /** + * The password hash. + */ + @NotNull + private byte[] hash; + + /** + * The password salt. + */ + @NotNull + private byte[] salt; + + /** + * A flag that indicates that the account is deactivated. + */ + private boolean suspended; + + /** + * Returns the name. + * + * @return The name. + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the login. + * + * @return The login. + */ + public String getLogin() { + return login; + } + + /** + * Sets the login. + * + * @param login The login to set. + */ + public void setLogin(String login) { + this.login = login; + } + + /** + * Returns the roles. + * + * @return The roles. + */ + public Set getRoles() { + return roles; + } + + /** + * Sets the roles. + * + * @param roles The roles to set. + */ + public void setRoles(Set roles) { + this.roles = roles; + } + + /** + * Returns the emails. + * + * @return The emails. + */ + public Set getEmails() { + return emails; + } + + /** + * Sets the emails. + * + * @param emails The emails to set. + */ + public void setEmails(Set emails) { + this.emails = emails; + } + + /** + * Returns the iterations. + * + * @return The iterations. + */ + public int getIterations() { + return iterations; + } + + /** + * Sets the iterations. + * + * @param iterations The iterations to set. + */ + public void setIterations(int iterations) { + this.iterations = iterations; + } + + /** + * Returns the hash. + * + * @return The hash. + */ + public byte[] getHash() { + return hash; + } + + /** + * Sets the hash. + * + * @param hash The hash to set. + */ + public void setHash(byte[] hash) { + this.hash = hash; + } + + /** + * Returns the salt. + * + * @return The salt. + */ + public byte[] getSalt() { + return salt; + } + + /** + * Sets the salt. + * + * @param salt The salt to set. + */ + public void setSalt(byte[] salt) { + this.salt = salt; + } + + /** + * Returns the suspended. + * + * @return The suspended. + */ + public boolean isSuspended() { + return suspended; + } + + /** + * Sets the suspended. + * + * @param suspended The suspended to set. + */ + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } + + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/injection/Datasources.java b/service/ejb/src/main/java/com/maptology/service/injection/Datasources.java new file mode 100644 index 0000000..aeed2b5 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/injection/Datasources.java @@ -0,0 +1,36 @@ +package com.maptology.service.injection; + +import javax.enterprise.inject.Produces; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceProperty; + +/** + * The producers for data sources. + * + * @author Marcus + * + */ +public class Datasources { + + /** + * The name of the datastore. + */ + public static final String MAPTOLOGY_DATASTORE = "maptology-datastore"; + + /** + * Defines the entity manager for the default database. This + * definition sets some standard properties. More properties + * are defined in the persistence xml, but they differ depending + * on the execution environment (i.e. production or test). + */ + @Produces + @PersistenceContext( + unitName=MAPTOLOGY_DATASTORE, + properties= { + @PersistenceProperty(name="hibernate.connection.useUnicode", value="true"), + @PersistenceProperty(name="hibernate.connection.characterEncoding", value="UTF-8"), + }) + private EntityManager defaultEntityManager; + +} \ No newline at end of file diff --git a/service/ejb/src/main/java/com/maptology/service/injection/Loggers.java b/service/ejb/src/main/java/com/maptology/service/injection/Loggers.java new file mode 100644 index 0000000..bd5f33c --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/injection/Loggers.java @@ -0,0 +1,25 @@ +package com.maptology.service.injection; + +import java.util.logging.Logger; + +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; + +/** + * The producers for loggers. + * + * @author Marcus + */ +public class Loggers { + + /** + * Defines the default logger. + * + * @param injectionPoint The injection point. + * @return The logger for the injection point. + */ + @Produces + public Logger getDefaultLogger(InjectionPoint injectionPoint) { + return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); + } +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/AbstractSession.java b/service/ejb/src/main/java/com/maptology/service/session/AbstractSession.java new file mode 100644 index 0000000..4192f4a --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/AbstractSession.java @@ -0,0 +1,23 @@ +package com.maptology.service.session; + +import java.util.logging.Logger; + +import javax.inject.Inject; +import javax.persistence.EntityManager; + +/** + * An abstract base class for session beans. The base class + * provides access to the default logger and the default + * entity manager. + * + * @author Marcus + */ +public abstract class AbstractSession { + + @Inject + protected Logger log; + + @Inject + protected EntityManager em; + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/DataInitializer.java b/service/ejb/src/main/java/com/maptology/service/session/DataInitializer.java new file mode 100644 index 0000000..cee19d1 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/DataInitializer.java @@ -0,0 +1,161 @@ +package com.maptology.service.session; + +import java.util.HashSet; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.annotation.PostConstruct; +import javax.ejb.Singleton; +import javax.ejb.Startup; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.TypedQuery; + +import com.maptology.api.access.Roles; +import com.maptology.service.crypto.SecureHash; +import com.maptology.service.entity.user.EmailEntity; +import com.maptology.service.entity.user.RoleEntity; +import com.maptology.service.entity.user.UserEntity; + +/** + * A bean that is executed at startup to initialize the + * database with the default roles and users. + * + * @author Marcus + */ +@Startup +@Singleton +public class DataInitializer { + + + @Inject + protected Logger log; + + @Inject + protected EntityManager em; + + + @PostConstruct + public void init() { + initRoles(); + initUsers(); + } + + /** + * Initializes the database with the default roles. + */ + public void initRoles() { + log.log(Level.INFO, "Initializing roles."); + addRole(Roles.ADMIN.name(), "Grants admin privileges."); + addRole(Roles.USER.name(), "Grants user privileges."); + addRole(Roles.APP.name(), "Grants app privileges."); + } + + /** + * Adds a role, if it is not present already, and returns it. + * + * @param name The name of the role. + * @param description The description of the role. + * @return The role that was present or has been added. + */ + public RoleEntity addRole(String name, String description) { + log.log(Level.INFO, "Creating role " + name + "."); + RoleEntity r = findRole(name); + if (r != null) { + log.log(Level.INFO, "Role " + name + " exists."); + return r; + } else { + r = new RoleEntity(); + r.setName(name); + r.setDescription(description); + log.log(Level.INFO, "Role " + name + " created."); + em.persist(r); + return r; + } + } + + /** + * Finds a role with a given name. + * + * @param name The name. + * @return The role or null, if it does not exist. + */ + public RoleEntity findRole(String name) { + TypedQuery q = em.createNamedQuery("findRoleByName", RoleEntity.class); + q.setParameter("name", name); + try { + return q.getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + /** + * Initializes a default set of users. + */ + public void initUsers() { + log.log(Level.INFO, "Initializing users."); + initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new Roles[] { Roles.ADMIN, Roles.USER}); + initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new Roles[] { Roles.USER }); + } + + /** + * Adds a user, if it does not exist already, and returns it. + * + * @param login The login. + * @param name The name. + * @param password The password. + * @param email The email address. + * @param roles The roles. + * @return The created or existing user. + */ + public UserEntity initUser(String login, String name, String password, String email, Roles[] roles) { + log.log(Level.INFO, "Creating user " + login + "."); + UserEntity u = findUser(login); + if (u != null) { + log.log(Level.INFO, "User " + login + " exists."); + return u; + } else { + u = new UserEntity(); + u.setLogin(login); + u.setName(name); + SecureHash s = new SecureHash(password); + u.setHash(s.getHash()); + u.setSalt(s.getSalt()); + u.setIterations(s.getIterations()); + u.setRoles(new HashSet()); + for (Roles r: roles) { + u.getRoles().add(findRole(r.name())); + } + u.setEmails(new HashSet()); + em.persist(u); + EmailEntity e = new EmailEntity(); + e.setUser(u); + e.setAddress(email); + e.setVerified(true); + e.setCorrespondence(true); + u.getEmails().add(e); + em.persist(e); + log.log(Level.INFO, "User " + login + " created."); + return u; + } + } + + /** + * Finds a user with a given login. + * + * @param login The login. + * @return The user. + */ + public UserEntity findUser(String login) { + TypedQuery q = em.createNamedQuery("findUserByLogin", UserEntity.class); + q.setParameter("login", login); + try { + return q.getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/UserSession.java b/service/ejb/src/main/java/com/maptology/service/session/UserSession.java new file mode 100644 index 0000000..79f5c4e --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/UserSession.java @@ -0,0 +1,22 @@ +package com.maptology.service.session; + +import javax.annotation.Resource; +import javax.ejb.SessionContext; +import javax.ejb.Stateless; +import javax.enterprise.context.RequestScoped; +import javax.inject.Named; + +@Named +@Stateless +@RequestScoped +public class UserSession extends AbstractSession { + + @Resource + private SessionContext context; + + public String getCurrentUser() { + + return context.getCallerPrincipal().getName(); + } + +} diff --git a/service/ejb/src/main/resources/META-INF/beans.xml b/service/ejb/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000..ec3d0f3 --- /dev/null +++ b/service/ejb/src/main/resources/META-INF/beans.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/service/ejb/src/main/resources/META-INF/persistence.xml b/service/ejb/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..d9875d8 --- /dev/null +++ b/service/ejb/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + java:jboss/datasources/ExampleDS + + + + + + + + \ No newline at end of file diff --git a/service/ejb/src/test/resources/META-INF/persistence.xml b/service/ejb/src/test/resources/META-INF/persistence.xml new file mode 100644 index 0000000..0eb7927 --- /dev/null +++ b/service/ejb/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + + java:jboss/datasources/ExampleDS + + + + + + \ No newline at end of file diff --git a/service/pom.xml b/service/pom.xml index ad96d88..e33949c 100644 --- a/service/pom.xml +++ b/service/pom.xml @@ -7,10 +7,13 @@ all 0.0.1-SNAPSHOT - com.maptology service Maptology Service - Backend services for maptology. - 0.0.1-SNAPSHOT + Backend service for maptology. pom + + ejb + war + ear + diff --git a/service/war/pom.xml b/service/war/pom.xml new file mode 100644 index 0000000..1bb3bd5 --- /dev/null +++ b/service/war/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.maptology + service + 0.0.1-SNAPSHOT + + com.maptology.service + war + Maptology Service War + War of the maptology service. + war + + 3.0.19.Final + + + + + maven-war-plugin + + src/main/webapp/WEB-INF/web.xml + + + true + + + ${jenkins.build.number} + + + + + + + + + com.maptology + api + ${project.version} + + + com.maptology.service + ejb + ${project.version} + provided + + + javax + javaee-api + 7.0 + provided + + + org.jboss.resteasy + resteasy-jaxrs + ${version.resteasy} + provided + + + junit + junit + + + diff --git a/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java b/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java new file mode 100644 index 0000000..3851522 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java @@ -0,0 +1,153 @@ +package com.maptology.service.access; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.security.Principal; +import java.util.Arrays; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.Provider; + +import com.maptology.api.access.PrincipalRequired; +import com.maptology.api.access.RoleRequired; +import com.maptology.api.access.Roles; +import com.maptology.api.access.RolesRequired; + +/** + * A container request filter that performs access control. + * + * @author Marcus + */ +@Provider +public class AccessControlFilter implements ContainerRequestFilter { + + @Context + ResourceInfo resource; + + @Context + HttpServletRequest request; + + @Context + HttpServletResponse response; + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + Method m = resource.getResourceMethod(); + RolesRequired roles = findAnnotation(m, RolesRequired.class); + RoleRequired role = findAnnotation(m, RoleRequired.class); + PrincipalRequired principal = findAnnotation(m, PrincipalRequired.class); + if (roles == null && role == null && principal == null) return; + boolean success = true; + try { + if (request.getUserPrincipal() != null || request.authenticate(response)) { + if (roles != null && !isFulfilled(roles)) { + success = false; + } else if (role != null && !isFulfilled(role)) { + success = false; + } else if (principal != null && !isFulfilled(principal)) { + success = false; + } + } else { + success = false; + } + } catch (Exception e) { + success = false; + } + if (! success) { + requestContext.abortWith(Response.status(Status.FORBIDDEN).build()); + } + } + + /** + * Determines whether the principal matches. + * + * @param principal The principal requirement. + * @return True if the requirement matches. + */ + public boolean isFulfilled(PrincipalRequired principal) { + Principal user = request.getUserPrincipal(); + if (user == null) return false; + // this is conceptually not needed, but since this + // will be a common case, let's avoid compiling the pattern + if (principal.value().equals(".*")) return true; + else { + try { + return Pattern.compile(principal.value()).matcher(user.getName()).matches(); + } catch (PatternSyntaxException e) { + e.printStackTrace(); + return false; + } + } + + } + + /** + * Determines whether an alternative roles requirement + * is fulfilled. + * + * @param roles The roles to check. + * @return True if the role requirement is empty or if + * one of the specified requirements matches. + */ + public boolean isFulfilled(RolesRequired roles) { + if (roles.value().length == 0) return true; + for (RoleRequired r: roles.value()) { + if (isFulfilled(r)) { + return true; + } + } + return false; + } + + /** + * Determines whether a role requirement is fulfilled. + * + * @param role The role requirement. + * @return True if fulfilled. + */ + public boolean isFulfilled(RoleRequired role) { + for (Roles r: role.value()) { + if (! request.isUserInRole(r.name())) { + return false; + } + } + return true; + } + + /** + * Tries to find an annotation on a resource method. If no annotation can be found, + * the search continues on all interfaces implemented by the class. This is somewhat + * hacky since the order is not really fixed. + * + * @param m The method to start searching from. + * @param annotation The annotation to find. + * @return The annnotation or null, if there is none. + */ + public T findAnnotation(Method m, Class annotation) { + T result = m.getAnnotation(annotation); + if (result != null) return result; + Class c = m.getDeclaringClass(); + i: for (Class i: c.getInterfaces()) { + for (Method method: i.getMethods()) { + if (method.getName().equals(m.getName()) && Arrays.equals(method.getParameterTypes(), m.getParameterTypes())) { + result = method.getAnnotation(annotation); + if (result != null) return result; + continue i; + } + } + } + return null; + } + + +} diff --git a/service/war/src/main/java/com/maptology/service/access/package-info.java b/service/war/src/main/java/com/maptology/service/access/package-info.java new file mode 100644 index 0000000..f47e1a8 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/access/package-info.java @@ -0,0 +1,7 @@ +/** + * This package contains tools to implement + * the access control. + * + * @author Marcus + */ +package com.maptology.service.access; \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/app/MaptologyApplication.java b/service/war/src/main/java/com/maptology/service/app/MaptologyApplication.java new file mode 100644 index 0000000..5da4ac1 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/app/MaptologyApplication.java @@ -0,0 +1,29 @@ +package com.maptology.service.app; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +import com.maptology.service.access.AccessControlFilter; +import com.maptology.service.rest.UserResource; + +/** + * The application is the main entry point of JAX-RS. + * + * @author Marcus + * + */ +@ApplicationPath("/") +public class MaptologyApplication extends Application { + + @Override + public Set> getClasses() { + Set> classes = new HashSet<>(); + classes.add(AccessControlFilter.class); + classes.add(UserResource.class); + return classes; + } + +} diff --git a/service/war/src/main/java/com/maptology/service/app/MaptologyContextListener.java b/service/war/src/main/java/com/maptology/service/app/MaptologyContextListener.java new file mode 100644 index 0000000..a8b4f9f --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/app/MaptologyContextListener.java @@ -0,0 +1,42 @@ +package com.maptology.service.app; + +import javax.security.auth.message.config.AuthConfigFactory; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; + +import com.maptology.service.auth.MaptologyAuthProvider; + +/** + * A context listener for the maptology project that registers the + * authentication module upon startup. + * + * @author Marcus + */ +@WebListener +public class MaptologyContextListener implements ServletContextListener { + + /** + * The logger. + */ + private Logger log = Logger.getLogger(getClass().getName()); + + @Override + public void contextInitialized(ServletContextEvent sce) { + String server = sce.getServletContext().getVirtualServerName(); + String context = sce.getServletContext().getContextPath(); + String appContext = server + " " + context; + log.log(Level.INFO, "Registering AuthConfigFactory for " + appContext + "."); + MaptologyAuthProvider.setContext(appContext); + MaptologyAuthProvider.registerProvider(AuthConfigFactory.getFactory()); + + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + // nothing to be done + } +} \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthConfig.java b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthConfig.java new file mode 100644 index 0000000..71bacf2 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthConfig.java @@ -0,0 +1,79 @@ +package com.maptology.service.auth; + +import java.util.Map; + +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.message.AuthException; +import javax.security.auth.message.MessageInfo; +import javax.security.auth.message.MessagePolicy; +import javax.security.auth.message.MessagePolicy.TargetPolicy; +import javax.security.auth.message.config.ServerAuthConfig; +import javax.security.auth.message.config.ServerAuthContext; + +/** + * A server auth config module that creates a single module context. + */ +public class MaptologyAuthConfig implements ServerAuthConfig { + + /** + * The layer. + */ + private String layer; + /** + * The app context. + */ + private String appContext; + /** + * The handler. + */ + private CallbackHandler handler; + + /** + * Creates a new auth ocnfig using the layer, context and handler. + * + * @param layer The layer. + * @param appContext The app context. + * @param handler The handler. + */ + public MaptologyAuthConfig(String layer, String appContext, CallbackHandler handler) { + this.layer = layer; + this.appContext = appContext; + this.handler = handler; + } + + @Override + public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, + @SuppressWarnings("rawtypes") Map properties) throws AuthException { + MessagePolicy policy = new MessagePolicy(new TargetPolicy[0], false); + MaptologyAuthModule module = new MaptologyAuthModule(); + module.initialize(policy, policy, handler, properties); + return new MaptologyAuthContext(module); + } + + @Override + public String getMessageLayer() { + return layer; + } + + @Override + public String getAuthContextID(MessageInfo messageInfo) { + return appContext; + } + + @Override + public String getAppContext() { + return appContext; + } + + @Override + public void refresh() { + // nothing to be done + } + + @Override + public boolean isProtected() { + return false; + } + +} \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthContext.java b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthContext.java new file mode 100644 index 0000000..45770ce --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthContext.java @@ -0,0 +1,48 @@ +package com.maptology.service.auth; + +import javax.security.auth.Subject; +import javax.security.auth.message.AuthException; +import javax.security.auth.message.AuthStatus; +import javax.security.auth.message.MessageInfo; +import javax.security.auth.message.config.ServerAuthContext; +import javax.security.auth.message.module.ServerAuthModule; + +/** + * Implements an server auth context that forwards request to + * a single module. + * + * @author Marcus + */ +public class MaptologyAuthContext implements ServerAuthContext { + + /** + * The server auth module that performs the work. + */ + private ServerAuthModule module; + + /** + * Creates a new context using the module.. + * + * @param module The module. + */ + public MaptologyAuthContext(ServerAuthModule module) { + this.module = module; + } + + @Override + public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) + throws AuthException { + return module.validateRequest(messageInfo, clientSubject, serviceSubject); + } + + @Override + public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { + return module.secureResponse(messageInfo, serviceSubject); + } + + @Override + public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { + module.cleanSubject(messageInfo, subject); + } + +} \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java new file mode 100644 index 0000000..435cb55 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java @@ -0,0 +1,215 @@ +package com.maptology.service.auth; + +import java.io.IOException; +import java.security.Principal; +import java.util.Iterator; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.TypedQuery; +import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.message.AuthException; +import javax.security.auth.message.AuthStatus; +import javax.security.auth.message.callback.CallerPrincipalCallback; +import javax.security.auth.message.callback.GroupPrincipalCallback; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; +import javax.ws.rs.core.HttpHeaders; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; + +import com.maptology.service.auth.basic.BasicAuthCredential; +import com.maptology.service.auth.http.AbstractHttpServletAuthModule; +import com.maptology.service.auth.http.HttpServletMessageInfo; +import com.maptology.service.crypto.SecureHash; +import com.maptology.service.entity.user.RoleEntity; +import com.maptology.service.entity.user.UserEntity; + +/** + * The server authentication module that + * + */ +public class MaptologyAuthModule extends AbstractHttpServletAuthModule { + + public static final String REALM = "Basic realm=\"maptology-api\""; + + /** + * The logger to write debug data to the console. + */ + private Logger log = Logger.getLogger(getClass().getName()); + + @Override + protected AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { + HttpServletRequest request = messageInfo.getRequest(); + BasicAuthCredential credential = BasicAuthCredential.valueOf(request.getHeader(HttpHeaders.AUTHORIZATION)); + log.log(Level.INFO, "Validating request for '" + (credential==null?"":credential.getUsername()) + "'."); + Principal principal = request.getUserPrincipal(); + // first we try to resume a session + if (principal != null && (credential == null || principal.getName().equals(credential.getUsername()))) { + log.log(Level.INFO, "Resuming previous session for " + principal.getName() + "."); + try { + messageInfo.setRegisterSession(true); + callbackHandler.handle(new Callback[] { new CallerPrincipalCallback(clientSubject, principal) } ); + return AuthStatus.SUCCESS; + } catch (Exception ex) { + log.log(Level.WARN, "Failed to resume sssion for " + principal.getName() + ".", ex); + return sendServerError(messageInfo, "Failed to resume session."); + } + } + // then we handle requests without credentials + if (credential == null) { + if (!messageInfo.isAuthMandatory()) { + // no auth needed, so this is ok + return AuthStatus.SUCCESS; + } else { + return sendForbidden(messageInfo, "Access not allowed."); + } + + } + // now we try to login with credentials + EntityManager em = getEntityManager(); + UserTransaction ta = getUserTransaction(); + if (em == null || ta == null) { + return sendServerError(messageInfo, "User database not available."); + } + boolean success = false; + UserEntity user = getUser(em, ta, credential.getUsername()); + if (user != null && !user.isDeleted() && !user.isSuspended()) { + SecureHash hash = new SecureHash(user.getIterations(), user.getSalt(), user.getHash()); + if (hash.verify(credential.getPassword())) { + try { + String[] roles = new String[user.getRoles().size()]; + Iterator it = user.getRoles().iterator(); + for (int i = 0; i < roles.length; i++) { + roles[i] = it.next().getName(); + } + callbackHandler.handle(new Callback[] { + new CallerPrincipalCallback(clientSubject, user.getLogin()), + new GroupPrincipalCallback(clientSubject, roles) + }); + messageInfo.setRegisterSession(true); + success = true; + log.log(Level.INFO, "User login for " + credential.getUsername() + "."); + } catch (Exception e) { + log.log(Level.ERROR, "Fatal processing error.", e); + return sendServerError(messageInfo, "User login failed."); + } + } + } + if (success || !messageInfo.isAuthMandatory()) { + return AuthStatus.SUCCESS; + } else { + return sendForbidden(messageInfo, "Access not allowed."); + } + } + + /** + * Loads the user and its roles in a single transaction. + * + * @param em The entity manager. + * @param t The transaction. + * @param login The login. + * @return The user entity or null, if the user does not exist. + */ + private UserEntity getUser(EntityManager em, UserTransaction t, String login) { + try { + t.begin(); + try { + TypedQuery q = em.createNamedQuery("findUserByLogin", UserEntity.class); + q.setParameter("login", login); + UserEntity user = q.getSingleResult(); + // ensure that roles are loaded + user.getRoles().size(); + return user; + } catch (NoResultException e) { + log.log(Level.INFO, "User " + login + " not found."); + } finally { + t.commit(); + } + } catch (Exception e) { + log.log(Level.WARN, "User query failed.", e); + } + return null; + } + + + + /** + * Returns the entity manager for the maptology datastore. + * + * @return The entity manager or null, if the entity manager cannot be found. + */ + private EntityManager getEntityManager() { + try { + Context context = new InitialContext(); + return (EntityManager)context.lookup("java:app/maptology/datastore"); + } catch (NamingException e) { + log.log(Level.ERROR, "Failed to resolve entity manager.", e); + return null; + } + } + + /** + * Returns a user transaction for the maptology datastore. + * + * @return The user transaction or null, if the transaction cannot be found. + */ + private UserTransaction getUserTransaction() { + try { + Context context = new InitialContext(); + return (UserTransaction)context.lookup("java:comp/UserTransaction"); + } catch (NamingException e) { + log.log(Level.ERROR, "Failed to resolve user transaction.", e); + return null; + } + } + + /** + * Sends a forbidden message and returns failed. + * + * @param messageInfo The message info. + * @param message The error message. + * @return AuthStatus.FAILED + */ + private AuthStatus sendForbidden(HttpServletMessageInfo messageInfo, String message) { + HttpServletResponse response = messageInfo.getResponse(); + response.addHeader(HttpHeaders.WWW_AUTHENTICATE, REALM); + return sendError(response, HttpServletResponse.SC_UNAUTHORIZED, message); + } + + /** + * Sends a server error and returns a auth status failure. + * + * @param messageInfo The message info. + * @param message The error message. + * @return AuthStatus.FAILED + */ + private AuthStatus sendServerError(HttpServletMessageInfo messageInfo, String message) { + return sendError(messageInfo.getResponse(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + } + + + /** + * Sends an http error with the specified code and message and returns failure. + * + * @param response The servlet response. + * @param code The message code. + * @param message The error message. + * @return AuthStatus.FAILURE. + */ + private AuthStatus sendError(HttpServletResponse response, int code, String message) { + try { + response.sendError(code, message); + } catch (IOException e) { + log.log(Level.WARN, "Failed to send error " + code + " " + message + ".", e); + } + return AuthStatus.FAILURE; + } + +} \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthProvider.java b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthProvider.java new file mode 100644 index 0000000..077ef23 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthProvider.java @@ -0,0 +1,106 @@ +package com.maptology.service.auth; + +import java.util.HashMap; +import java.util.Map; + +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.message.AuthException; +import javax.security.auth.message.config.AuthConfigFactory; +import javax.security.auth.message.config.AuthConfigProvider; +import javax.security.auth.message.config.ClientAuthConfig; +import javax.security.auth.message.config.ServerAuthConfig; + +/** + * Implements an auth config provider that uses basic auth to authenticate requests. + * + * @author Marcus + */ +public class MaptologyAuthProvider implements AuthConfigProvider { + + /** + * The layer for the Servlet Container Profile. See page 27 of the JASPIC specification + * JSR-197. + */ + public static final String SERVLET_LAYER = "HttpServlet"; + + /** + * The description of the provider. + */ + private static final String DESCRIPTION = "Basic Auth Config Provider"; + + /** + * The application context to register for. + */ + private static String context; + + /** + * Sets th application context. + * + * @param context The context. + */ + public static void setContext(String context) { + MaptologyAuthProvider.context = context; + } + + /** + * Registers the provider at the factory. + * + * @param factory The factory. + */ + public static void registerProvider(AuthConfigFactory factory) { + registerProvider(factory, new MaptologyAuthProvider()); + } + + /** + * Registers the specified provider at the factory. + * + * @param factory The factory. + * @param provider The provider. + */ + private static void registerProvider(AuthConfigFactory factory, MaptologyAuthProvider provider) { + factory.registerConfigProvider(provider, SERVLET_LAYER, context, DESCRIPTION); + } + + /** + * The configuration properties. + */ + private Map properties = new HashMap<>(); + + /** + * Creates a new provider without properties. + */ + protected MaptologyAuthProvider() { + super(); + } + + /** + * Constructor with signature and implementation that's required by the api. + * + * @param properties The properties. + * @param factory The factory. + */ + public MaptologyAuthProvider(Map properties, AuthConfigFactory factory) { + this.properties.putAll(properties); + if (factory != null) registerProvider(factory, this); + } + + @Override + public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) + throws AuthException, SecurityException { + if (handler == null) throw new AuthException("No authentication callback provided."); + return new MaptologyAuthConfig(layer, appContext, handler); + } + + @Override + public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) + throws AuthException, SecurityException { + // should not be called for servlet container profile + return null; + } + + @Override + public void refresh() { + // nothing to be done + } + +} \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/auth/basic/BasicAuthCredential.java b/service/war/src/main/java/com/maptology/service/auth/basic/BasicAuthCredential.java new file mode 100644 index 0000000..5cc8912 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/basic/BasicAuthCredential.java @@ -0,0 +1,112 @@ +package com.maptology.service.auth.basic; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +/** + * Utility to extract and generate basic auth credentials. + * + * @author Marcus + */ +public class BasicAuthCredential { + + /** + * The basic prefix. + */ + private static final String PREFIX_BASIC = "Basic"; + + /** + * The username. + */ + private String username; + + /** + * The password. + */ + private String password; + + /** + * Creates a new basic auth from a username and password. + * + * @param username + * The username. + * @param password + * The password. + * @throws NullPointerException + * Thrown if the username or password is null. + */ + public BasicAuthCredential(String username, String password) { + if (username == null) + throw new NullPointerException("Username must not be null."); + if (password == null) + throw new NullPointerException("Passowrd must not be null."); + this.username = username; + this.password = password; + } + + /** + * Returns the user name. + * + * @return The user name. + */ + public String getUsername() { + return username; + } + + /** + * Returns the password. + * + * @return The password. + */ + public String getPassword() { + return password; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != getClass()) + return false; + BasicAuthCredential b = (BasicAuthCredential) obj; + return b.getUsername().equals(username) && b.getPassword().equals(password); + } + + @Override + public int hashCode() { + return username.hashCode() ^ password.hashCode(); + } + + /** + * Returns the string representation. + * + * @return The string representation. + */ + public String toString() { + byte[] bytes = Base64.getEncoder().encode((username + ':' + password).getBytes(StandardCharsets.ISO_8859_1)); + return PREFIX_BASIC + ' ' + new String(bytes, StandardCharsets.ISO_8859_1); + } + + /** + * Tries to parse the basic auth credentials from the value. + * + * @param value + * The value. + * @return The basic auth credential or null, if it is not possible to parse + * them. + */ + public static BasicAuthCredential valueOf(String value) { + if (value == null || !value.startsWith(PREFIX_BASIC)) + return null; + value = value.substring(PREFIX_BASIC.length()).trim(); + try { + String s = new String(Base64.getDecoder().decode(value), StandardCharsets.ISO_8859_1); + int index = s.indexOf(':'); + if (index == -1) + return null; + else + return new BasicAuthCredential(s.substring(0, index), s.substring(index + 1)); + } catch (IllegalArgumentException e) { + return null; + } + } + +} diff --git a/service/war/src/main/java/com/maptology/service/auth/http/AbstractHttpServletAuthModule.java b/service/war/src/main/java/com/maptology/service/auth/http/AbstractHttpServletAuthModule.java new file mode 100644 index 0000000..67fe29a --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/http/AbstractHttpServletAuthModule.java @@ -0,0 +1,112 @@ +package com.maptology.service.auth.http; + +import java.util.Map; + +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.message.AuthException; +import javax.security.auth.message.AuthStatus; +import javax.security.auth.message.MessageInfo; +import javax.security.auth.message.MessagePolicy; +import javax.security.auth.message.module.ServerAuthModule; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Base class to simplfy the implementation of server auth modules. + * + * @author Marcus + */ +public abstract class AbstractHttpServletAuthModule implements ServerAuthModule { + + /** + * The supported message types. + */ + private static final Class[] MESSAGE_TYPES = new Class[] { HttpServletRequest.class, HttpServletResponse.class }; + + /** + * The request policy. + */ + protected MessagePolicy requestPolicy; + + /** + * The response policy. + */ + protected MessagePolicy responsePolicy; + + /** + * The callback handler. + */ + protected CallbackHandler callbackHandler; + + /** + * The properties. + */ + protected Map properties; + + @Override + public void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler, + @SuppressWarnings("rawtypes") Map options) throws AuthException { + this.callbackHandler = handler; + this.requestPolicy = requestPolicy; + this.responsePolicy = responsePolicy; + this.properties = (Map) properties; + } + + @Override + public Class[] getSupportedMessageTypes() { + return MESSAGE_TYPES; + } + + @Override + public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) + throws AuthException { + return validateRequest(new HttpServletMessageInfo(messageInfo), clientSubject, serviceSubject); + } + + @Override + public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) throws AuthException { + return secureResponse(new HttpServletMessageInfo(messageInfo), serviceSubject); + } + + @Override + public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthException { + cleanSubject(new HttpServletMessageInfo(messageInfo), subject); + } + + /** + * Validates the request. + * + * @param messageInfo The message info. + * @param clientSubject The client subject. + * @param serviceSubject The service subject. + * @return The auth status. + * @throws AuthException Thrown if the auth fails. + */ + protected abstract AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, + Subject serviceSubject) throws AuthException; + + /** + * Secures the response. + * + * @param messageInfo The message info. + * @param serviceSubject The service subject. + * @return The auth status. + * @throws AuthException Thrown if the auth fails. + */ + protected AuthStatus secureResponse(HttpServletMessageInfo messageInfo, Subject serviceSubject) throws AuthException { + return AuthStatus.SEND_CONTINUE; + } + + /** + * Cleans the subject. + * + * @param messageInfo The message info. + * @param subject The subject. + * @throws AuthException Thrown if the auth fails. + */ + protected void cleanSubject(HttpServletMessageInfo messageInfo, Subject subject) throws AuthException { + subject.getPrincipals().clear(); + } + +} diff --git a/service/war/src/main/java/com/maptology/service/auth/http/HttpServletMessageInfo.java b/service/war/src/main/java/com/maptology/service/auth/http/HttpServletMessageInfo.java new file mode 100644 index 0000000..acd0e54 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/http/HttpServletMessageInfo.java @@ -0,0 +1,143 @@ +package com.maptology.service.auth.http; + +import java.util.Map; + +import javax.security.auth.message.MessageInfo; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * A wrapper for message info objects that can be + * used to avoid type-casts of response and request + * objects. + * + * @author Marcus + */ +public class HttpServletMessageInfo implements MessageInfo { + + /** + * The auth type mechanism. + */ + public static final String AUTH_TYPE = "javax.servlet.http.authType"; + + /** + * The session registration mechanism. + */ + public static final String REGISTER_SESSION = "javax.servlet.http.registerSession"; + + /** + * A flag whether the authentication is mandatory. + */ + public static final String AUTH_MANDATORY = "javax.security.auth.message.MessagePolicy.isMandatory"; + + /** + * The message info. + */ + private MessageInfo messageInfo; + + /** + * Creates a http servlet message info from an + * underlying info. Note that the info must return + * http servlet requests and responses as its + * request and response objects. + * + * @param messageInfo The underlying info. + */ + public HttpServletMessageInfo(MessageInfo messageInfo) { + this.messageInfo = messageInfo; + } + + @Override + public Object getRequestMessage() { + return messageInfo.getRequestMessage(); + } + + @Override + @SuppressWarnings("rawtypes") + public Map getMap() { + return messageInfo.getMap(); + } + + @Override + public Object getResponseMessage() { + return messageInfo.getResponseMessage(); + } + + @Override + public void setRequestMessage(Object request) { + messageInfo.setRequestMessage(request); + } + + @Override + public void setResponseMessage(Object response) { + messageInfo.setResponseMessage(response); + } + + /** + * Returns the http servlet request. + * + * @return The http servlet request. + */ + public HttpServletRequest getRequest() { + return (HttpServletRequest) getRequestMessage(); + } + + /** + * Returns the http servlet response. + * + * @return The http servlet response. + */ + public HttpServletResponse getResponse() { + return (HttpServletResponse) getResponseMessage(); + } + + /** + * Sets the flag that tells the container to manage the + * principal and roles using the http session. + * + * @param value True to manage the session. + */ + @SuppressWarnings("unchecked") + public void setRegisterSession(boolean value) { + getMap().put(REGISTER_SESSION, value); + } + + /** + * Returns the state of the register session flag. + * + * @return True if the container shall manage the + * principal in the http session. False otherwise. + */ + public boolean isRegisterSession() { + return Boolean.valueOf((String) getMap().get(REGISTER_SESSION)); + } + + /** + * Sets the auth type. + * + * @param authType The auth type to set. + */ + @SuppressWarnings("unchecked") + public void setAuthType(String authType) { + getMap().put(AUTH_TYPE, authType); + } + + /** + * Returns the auth type. + * + * @return The auth type. + */ + public String getAuthType() { + return (String)getMap().get(AUTH_TYPE); + } + + /** + * Determines whether authentication is mandatory. + * + * @return True if auth is mandatory. + */ + public boolean isAuthMandatory() { + return Boolean.valueOf((String) getMap().get(AUTH_MANDATORY)); + } + +} diff --git a/service/war/src/main/java/com/maptology/service/auth/package-info.java b/service/war/src/main/java/com/maptology/service/auth/package-info.java new file mode 100644 index 0000000..1aa9600 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/auth/package-info.java @@ -0,0 +1,11 @@ +/** + * This package contains a server auth module with the associated plumbing. More + * information is available in JSR-196, here and here. + * + * @author Marcus + */ +package com.maptology.service.auth; \ No newline at end of file diff --git a/service/war/src/main/java/com/maptology/service/rest/UserResource.java b/service/war/src/main/java/com/maptology/service/rest/UserResource.java new file mode 100644 index 0000000..569bc9e --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/rest/UserResource.java @@ -0,0 +1,39 @@ +package com.maptology.service.rest; + +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.ws.rs.core.Response; + +import com.maptology.api.PageConfig; +import com.maptology.api.user.IUserService; +import com.maptology.api.user.User; +import com.maptology.api.user.UserPage; +import com.maptology.service.session.UserSession; + +/** + * The Jax-RS resource providing the user service. + * + * @author Marcus + */ +@Stateless +public class UserResource implements IUserService { + + @EJB + UserSession userSession; + + @Override + public Response getUsers(PageConfig pageConfig) { + UserPage p = new UserPage(); + p.setOffset(0); + p.setSize(pageConfig.getSize()); + p.setTotal(1); + p.getElements().add(new User()); + return Response.ok(p).build(); + } + + @Override + public Response getCurrentUser() { + return Response.ok(userSession.getCurrentUser()).build(); + } + +} diff --git a/service/war/src/main/java/com/maptology/service/servlet/TestServlet.java b/service/war/src/main/java/com/maptology/service/servlet/TestServlet.java new file mode 100644 index 0000000..16bc143 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/servlet/TestServlet.java @@ -0,0 +1,37 @@ +package com.maptology.service.servlet; + +import java.io.BufferedWriter; +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.maptology.api.access.Roles; + +@WebServlet(urlPatterns = "/servlet") +public class TestServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getUserPrincipal() != null || request.authenticate(response)) { + response.setContentType("text/plain"); + BufferedWriter w = new BufferedWriter(response.getWriter()); + w.write("User: '"); + w.write(request.getUserPrincipal()==null?"":request.getUserPrincipal().getName()); + w.write("'"); + w.newLine(); + for (Roles r: Roles.values()) { + w.write("Role '" + r.name() + "': "); + w.write(Boolean.toString(request.isUserInRole(r.name()))); + w.newLine(); + } + w.close(); + } + } + +} diff --git a/service/war/src/main/webapp/WEB-INF/jboss-web.xml b/service/war/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000..bd827a1 --- /dev/null +++ b/service/war/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,9 @@ + + + + jaspitest + \ No newline at end of file diff --git a/service/war/src/main/webapp/WEB-INF/web.xml b/service/war/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..4368c45 --- /dev/null +++ b/service/war/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + + resteasy.media.type.mappings + html : text/html, json : application/json, xml : application/xml + + + + + index.html + + diff --git a/service/war/src/main/webapp/index.html b/service/war/src/main/webapp/index.html new file mode 100644 index 0000000..7cbce72 --- /dev/null +++ b/service/war/src/main/webapp/index.html @@ -0,0 +1,10 @@ + + + + + Maptology + + +

Welcome to Maptology.

+ + diff --git a/service/war/src/test/java/com/maptology/service/auth/BasicAuthCredentialTest.java b/service/war/src/test/java/com/maptology/service/auth/BasicAuthCredentialTest.java new file mode 100644 index 0000000..026f4bd --- /dev/null +++ b/service/war/src/test/java/com/maptology/service/auth/BasicAuthCredentialTest.java @@ -0,0 +1,78 @@ +package com.maptology.service.auth; + +import org.junit.Test; + +import com.maptology.service.auth.basic.BasicAuthCredential; + +import org.junit.Assert; + +/** + * Tests the encoding and decoding of basic auth credentials, + * The test headers have been generated with an online tool + * from this page. + * + * @author Marcus + */ +public class BasicAuthCredentialTest { + + /** + * Username: Foo, Password: Bar + */ + public static final String FOO_BAR = "Basic Rm9vOkJhcg=="; + + /** + * Username: ÄÖÜäöu, Password: 1234$$%% + */ + public static final String AOU_123 = "Basic xNbc5PZ1OjEyMzQkJCUl"; + + @Test + public void testDecode() { + testDecode(FOO_BAR, "Foo", "Bar"); + testDecode(AOU_123, "ÄÖÜäöu", "1234$$%%"); + } + + /** + * Tests the decoding of the header against the username and password. + * + * @param header The header. + * @param username The username. + * @param password The password. + */ + private void testDecode(String header, String username, String password) { + BasicAuthCredential x = BasicAuthCredential.valueOf(header); + Assert.assertNotNull("Decoding should work.", x); + Assert.assertEquals("Username should match.", username, x.getUsername()); + Assert.assertEquals("Password should match.", password, x.getPassword()); + } + + @Test + public void testEncode() { + testEncode(FOO_BAR, "Foo", "Bar"); + testEncode(AOU_123, "ÄÖÜäöu", "1234$$%%"); + } + + /** + * Tests the encoding of the username and password against the header. + * + * @param header The header. + * @param username The username. + * @param password The password. + */ + private void testEncode(String header, String username, String password) { + BasicAuthCredential x = new BasicAuthCredential(username, password); + Assert.assertEquals("Header should match.", header, x.toString()); + } + + @Test + public void testRoundtrip() { + BasicAuthCredential x = new BasicAuthCredential("Marcus", "Handte"); + String s = x.toString(); + BasicAuthCredential y = BasicAuthCredential.valueOf(s); + Assert.assertNotNull("Decoding must work.", y); + Assert.assertEquals("Decoded should be encoded.", x, y); + Assert.assertEquals("Username should match.", x.getUsername(), y.getUsername()); + Assert.assertEquals("Password should match.", x.getPassword(), y.getPassword()); + } + +} diff --git a/web/pom.xml b/web/pom.xml index e656181..aab9acf 100644 --- a/web/pom.xml +++ b/web/pom.xml @@ -7,10 +7,8 @@ all 0.0.1-SNAPSHOT - com.maptology web Maptology Web Webapp frontend for maptology. - 0.0.1-SNAPSHOT pom