diff options
author | Thomas Lenz <thomas.lenz@egiz.gv.at> | 2019-12-04 19:43:32 +0100 |
---|---|---|
committer | Thomas Lenz <thomas.lenz@egiz.gv.at> | 2019-12-04 19:43:32 +0100 |
commit | 759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f (patch) | |
tree | 2132024fc058b1ef5338bf50df575a3244cc3f9f /eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller | |
parent | 4f15bdc45b08724d20c66c9fd74ea6a43a03c32f (diff) | |
download | EAAF-Components-759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f.tar.gz EAAF-Components-759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f.tar.bz2 EAAF-Components-759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f.zip |
common EGIZ code-style refactoring
Diffstat (limited to 'eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller')
7 files changed, 1136 insertions, 1084 deletions
diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java index 4505163d..7c42f506 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java @@ -1,43 +1,27 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.web.bind.annotation.ExceptionHandler; - import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IStatusMessenger; @@ -47,165 +31,215 @@ import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.utils.Random; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.web.bind.annotation.ExceptionHandler; /** + * Basic application controller that implements core error-handling. + * * @author tlenz * */ public abstract class AbstractController { - private static final Logger log = LoggerFactory.getLogger(AbstractController.class); - - @Autowired(required=true) protected IProtocolAuthenticationService protAuthService; - @Autowired(required=true) protected ApplicationContext applicationContext; - @Autowired(required=true) protected IConfigurationWithSP authConfig; - @Autowired(required=true) protected ITransactionStorage transactionStorage; - @Autowired(required=true) protected IStatusMessenger statusMessager; - - @Autowired protected IRevisionLogger revisionsLogger; - - @ExceptionHandler({EAAFException.class}) - public void EAAFExceptionHandler(final HttpServletRequest req, final HttpServletResponse resp, final Exception e) throws IOException { - try { - protAuthService.handleErrorNoRedirect(e, req, resp, true); - - } catch (final EAAFException e1) { - log.warn("Can NOT handle an 'EAAFException'. Forwarding to generic error ... ", e); - IOExceptionHandler(resp, e); - - } - - } - - @ExceptionHandler({Exception.class}) - public void GenericExceptionHandler(final HttpServletResponse resp, final Exception exception) throws IOException { - log.error("Internel Server Error." , exception); - resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + - "(Errorcode=9199" - +" | Description=" - + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(exception.getMessage())) - + ")"); - return; - - } - - @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(final HttpServletResponse resp, final Throwable exception) { - log.error("Internel Server Error." , exception); - resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - - } - - protected void handleError(final String errorMessage, final Throwable exceptionThrown, - final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) throws IOException, EAAFException { - - Throwable loggedException = null; - final Throwable extractedException = extractOriginalExceptionFromProcessException(exceptionThrown); - - //extract pendingRequestID and originalException if it was a TaskExecutionException - if (extractedException instanceof TaskExecutionException) { - //set original exception - loggedException = ((TaskExecutionException) extractedException).getOriginalException(); - - } else if (exceptionThrown instanceof PendingReqIdValidationException) { - log.trace("Find pendingRequestId validation exception. Looking for invalid pending-request ... "); - if (((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq() != null) - pendingReq = ((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq(); - - } - - //use TaskExecutionException directly, if no Original Exeception is included - if (loggedException == null) - loggedException = exceptionThrown; - - try { - //switch to protocol-finalize method to generate a protocol-specific error message - - //log error directly in debug mode - if (log.isDebugEnabled()) - log.warn(loggedException.getMessage(), loggedException); - - - //put exception into transaction store for redirect - final String key = Random.nextLongRandom(); - if (pendingReq != null) { - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR); - transactionStorage.put(key, - new ExceptionContainer(pendingReq, loggedException), -1); - - } else { - transactionStorage.put(key, - new ExceptionContainer(null, loggedException), -1); - - } - - //build up redirect URL - String redirectURL = null; - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/"+ProtocolFinalizationController.ENDPOINT_ERRORHANDLING - + "?" + EAAFConstants.PARAM_HTTP_ERROR_CODE + "=" + key; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - log.debug("REDIRECT TO: " + redirectURL); - - return; - - } catch (final Exception e) { - log.warn("Default error-handling FAILED. Exception can not be stored ....", e); - log.info("Switch to generic generic backup error-handling ... "); - protAuthService.handleErrorNoRedirect(loggedException, req, resp, true); - - } - - } - - - - - - /** - * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. - * - * @param exception - * @return Return the latest TaskExecutionExecption if exists, otherwise the latest ProcessExecutionException - */ - private Throwable extractOriginalExceptionFromProcessException(final Throwable exception) { - Throwable exholder = exception; - TaskExecutionException taskExc = null; - - while(exholder != null - && exholder instanceof ProcessExecutionException) { - final ProcessExecutionException procExc = (ProcessExecutionException) exholder; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - taskExc = (TaskExecutionException) procExc.getCause(); - exholder = taskExc.getOriginalException(); - - } else - break; - - } - - if (taskExc == null) - return exholder; - - else - return taskExc; - } - - - + private static final Logger log = LoggerFactory.getLogger(AbstractController.class); + + @Autowired(required = true) + protected IProtocolAuthenticationService protAuthService; + @Autowired(required = true) + protected ApplicationContext applicationContext; + @Autowired(required = true) + protected IConfigurationWithSP authConfig; + @Autowired(required = true) + protected ITransactionStorage transactionStorage; + @Autowired(required = true) + protected IStatusMessenger statusMessager; + + @Autowired + protected IRevisionLogger revisionsLogger; + + /** + * EAAF framework exception handler. + * + *<p> + *This handler start a protocol-specific error handling. + *</p> + * + * @param req http request + * @param resp http response + * @param e exception + * @throws IOException in case of an exception handling error + */ + @ExceptionHandler({EaafException.class}) + public void eaafExceptionHandler(final HttpServletRequest req, final HttpServletResponse resp, + final Exception e) throws IOException { + try { + protAuthService.handleErrorNoRedirect(e, req, resp, true); + + } catch (final EaafException e1) { + log.warn("Can NOT handle an 'EAAFException'. Forwarding to generic error ... ", e); + ioExceptionHandler(resp, e); + + } + + } + + /** + * Generic exception handler. + * + * <p> + * This handler wrote an internal server error into http response + * </p> + * + * @param resp http response + * @param exception exception + * @throws IOException In case of an internal error. + */ + @ExceptionHandler({Exception.class}) + public void genericExceptionHandler(final HttpServletResponse resp, final Exception exception) + throws IOException { + log.error("Internel Server Error.", exception); + resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + + "(Errorcode=9199" + " | Description=" + + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(exception.getMessage())) + + ")"); + return; + + } + + /** + * Generic exception handler. + * + * <p> + * This handler wrote an internal server error into http response + * </p> + * + * @param resp http response + * @param exception exception + */ + @ExceptionHandler({IOException.class}) + public void ioExceptionHandler(final HttpServletResponse resp, final Throwable exception) { + log.error("Internel Server Error.", exception); + resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + + } + + protected void handleError(final String errorMessage, final Throwable exceptionThrown, + final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) + throws IOException, EaafException { + + Throwable loggedException = null; + final Throwable extractedException = + extractOriginalExceptionFromProcessException(exceptionThrown); + + // extract pendingRequestID and originalException if it was a TaskExecutionException + if (extractedException instanceof TaskExecutionException) { + // set original exception + loggedException = ((TaskExecutionException) extractedException).getOriginalException(); + + } else if (exceptionThrown instanceof PendingReqIdValidationException) { + log.trace( + "Find pendingRequestId validation exception. Looking for invalid pending-request ... "); + if (((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq() != null) { + pendingReq = ((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq(); + } + + } + + // use TaskExecutionException directly, if no Original Exeception is included + if (loggedException == null) { + loggedException = exceptionThrown; + } + + try { + // switch to protocol-finalize method to generate a protocol-specific error message + + // log error directly in debug mode + if (log.isDebugEnabled()) { + log.warn(loggedException.getMessage(), loggedException); + } + + + // put exception into transaction store for redirect + final String key = Random.nextLongRandom(); + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR); + transactionStorage.put(key, new ExceptionContainer(pendingReq, loggedException), -1); + + } else { + transactionStorage.put(key, new ExceptionContainer(null, loggedException), -1); + + } + + // build up redirect URL + String redirectUrl = null; + redirectUrl = ServletUtils.getBaseUrl(req); + redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + + EAAFConstants.PARAM_HTTP_ERROR_CODE + "=" + key; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectUrl); + log.debug("REDIRECT TO: " + redirectUrl); + + return; + + } catch (final Exception e) { + log.warn("Default error-handling FAILED. Exception can not be stored ....", e); + log.info("Switch to generic generic backup error-handling ... "); + protAuthService.handleErrorNoRedirect(loggedException, req, resp, true); + + } + + } + + + + /** + * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. + * + * @param exception error + * @return Return the latest TaskExecutionExecption if exists, otherwise the latest + * ProcessExecutionException + */ + private Throwable extractOriginalExceptionFromProcessException(final Throwable exception) { + Throwable exholder = exception; + TaskExecutionException taskExc = null; + + while (exholder != null && exholder instanceof ProcessExecutionException) { + final ProcessExecutionException procExc = (ProcessExecutionException) exholder; + if (procExc.getCause() != null && procExc.getCause() instanceof TaskExecutionException) { + taskExc = (TaskExecutionException) procExc.getCause(); + exholder = taskExc.getOriginalException(); + + } else { + break; + } + + } + + if (taskExc == null) { + return exholder; + } else { + return taskExc; + } + } + + + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java index b87c9b78..9ff468d3 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java @@ -1,119 +1,113 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFIllegalStateException; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafIllegalStateException; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; /** * Servlet that resumes a suspended process (in case of asynchronous tasks). - * + * * @author tknall - * + * */ public abstract class AbstractProcessEngineSignalController extends AbstractController { - private static final Logger log = LoggerFactory.getLogger(AbstractProcessEngineSignalController.class); - - @Autowired(required=true) protected ProcessEngine processEngine; - @Autowired(required=true) protected IRequestStorage requestStorage; - - protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException, EAAFException { - String pendingRequestID = StringEscapeUtils.escapeHtml4(getPendingRequestId(req)); - IRequest pendingReq = null; - try { - if (pendingRequestID == null) { - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null); - - } - - pendingReq = requestStorage.getPendingRequest(pendingRequestID); - if (pendingReq == null) { - log.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure."); - throw new EAAFException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, new Object[]{pendingRequestID}); - - } - - //change pending-request ID - requestStorage.changePendingRequestID(pendingReq); - pendingRequestID = pendingReq.getPendingRequestId(); - - // process instance is mandatory - if (pendingReq.getProcessInstanceId() == null) { - throw new EAAFIllegalStateException(new Object[]{"MOA session does not provide process instance id."}); - - } - - // wake up next task - processEngine.signal(pendingReq); - - } catch (Exception ex) { - handleError(null, ex, req, resp, pendingReq); - - } finally { - //MOASessionDBUtils.closeSession(); - TransactionIDUtils.removeAllLoggingVariables(); - - } - - - } - - /** - * Retrieves the current pending-request id from the HttpServletRequest parameter - * - * <p/> - * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the - * respective pending-request id. - * - * @param request - * The unterlying HttpServletRequest. - * @return The current pending-request id. - */ - public String getPendingRequestId(HttpServletRequest request) { - return StringEscapeUtils.escapeHtml4(request.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); - - } + private static final Logger log = + LoggerFactory.getLogger(AbstractProcessEngineSignalController.class); + + @Autowired(required = true) + protected ProcessEngine processEngine; + @Autowired(required = true) + protected IRequestStorage requestStorage; + + protected void signalProcessManagement(final HttpServletRequest req, + final HttpServletResponse resp) throws IOException, EaafException { + final String pendingRequestID = StringEscapeUtils.escapeHtml4(getPendingRequestId(req)); + IRequest pendingReq = null; + try { + if (pendingRequestID == null) { + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null); + + } + + pendingReq = requestStorage.getPendingRequest(pendingRequestID); + if (pendingReq == null) { + log.info("No PendingRequest with Id: " + pendingRequestID + + " Maybe, a transaction timeout occure."); + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, + new Object[] {pendingRequestID}); + + } + + // change pending-request ID + requestStorage.changePendingRequestID(pendingReq); + + // process instance is mandatory + if (pendingReq.getProcessInstanceId() == null) { + throw new EaafIllegalStateException( + new Object[] {"MOA session does not provide process instance id."}); + + } + + // wake up next task + processEngine.signal(pendingReq); + + } catch (final Exception ex) { + handleError(null, ex, req, resp, pendingReq); + + } finally { + // MOASessionDBUtils.closeSession(); + TransactionIdUtils.removeAllLoggingVariables(); + + } + + + } + + /** + * Retrieves the current pending-request id from the HttpServletRequest parameter + * + * <p/> + * Note that this class/method can be overwritten by modules providing their own strategy of + * retrieving the respective pending-request id. + * + * @param request The unterlying HttpServletRequest. + * @return The current pending-request id. + */ + public String getPendingRequestId(final HttpServletRequest request) { + return StringEscapeUtils + .escapeHtml4(request.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index b830e240..7b350c3b 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -1,32 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.components.eventlog.api.EventConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,114 +37,121 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import at.gv.egiz.components.eventlog.api.EventConstants; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.IRequestStorage; -import at.gv.egiz.eaaf.core.api.IStatusMessenger; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; -import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - /** + * Protocol finialization end-point. + * * @author tlenz * */ @Controller public class ProtocolFinalizationController extends AbstractController { - private static final Logger log = LoggerFactory.getLogger(ProtocolFinalizationController.class); - public static final String ENDPOINT_FINALIZEPROTOCOL = "finalizeAuthProtocol"; - public static final String ENDPOINT_ERRORHANDLING = "errorHandling"; - - @Autowired(required=true) IRequestStorage requestStorage; - - @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET}) - public void errorHandling(HttpServletRequest req, HttpServletResponse resp) throws EAAFException, IOException { - //receive an authentication error - String errorid = StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_ERROR_CODE)); - if (errorid != null) { - IRequest pendingReq = null; - try { - //load stored exception from database - ExceptionContainer container = transactionStorage.get(errorid, ExceptionContainer.class); - if (container != null) { - //remove exception if it was found - transactionStorage.remove(errorid); - - Throwable throwable = container.getExceptionThrown(); - pendingReq = container.getPendingRequest(); - - if (pendingReq != null) { - //build protocol-specific error message if possible - protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); - - //remove active user-session - transactionStorage.remove(pendingReq.getPendingRequestId()); - - return; - - } else { - protAuthService.handleErrorNoRedirect(throwable, req, resp, true); - - } - } else { - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null), req, resp, false); - - } - - } catch (Throwable e) { - log.error(e.getMessage(), e); - protAuthService.handleErrorNoRedirect(e, req, resp, false); - - } finally { - //remove pending-request - if (pendingReq != null) { - requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - - } - - } else { - log.debug("Request contains NO ErrorId"); - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null), req, resp, false); - - } - - } - - - @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) - public void finalizeAuthProtocol(HttpServletRequest req, HttpServletResponse resp) throws EAAFException, IOException { - - //read pendingRequest from http request - Object idObject = StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); - IRequest pendingReq = null; - String pendingRequestID = null; - if (idObject != null && (idObject instanceof String)) { - pendingRequestID = (String) idObject; - pendingReq = requestStorage.getPendingRequest(pendingRequestID); - - } - - if (pendingReq == null) { - log.error("No PendingRequest with ID " + pendingRequestID + " found.!"); - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, - new Object[]{pendingRequestID, - }), req, resp, false); - - } else - protAuthService.finalizeAuthentication(req, resp, pendingReq); - - } - + private static final Logger log = LoggerFactory.getLogger(ProtocolFinalizationController.class); + public static final String ENDPOINT_FINALIZEPROTOCOL = "finalizeAuthProtocol"; + public static final String ENDPOINT_ERRORHANDLING = "errorHandling"; + + @Autowired(required = true) + IRequestStorage requestStorage; + + /** + * End-Point to handle errors. + * + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ + @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET}) + public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + // receive an authentication error + final String errorid = + StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_ERROR_CODE)); + if (errorid != null) { + IRequest pendingReq = null; + try { + // load stored exception from database + final ExceptionContainer container = + transactionStorage.get(errorid, ExceptionContainer.class); + if (container != null) { + // remove exception if it was found + transactionStorage.remove(errorid); + + final Throwable throwable = container.getExceptionThrown(); + pendingReq = container.getPendingRequest(); + + if (pendingReq != null) { + // build protocol-specific error message if possible + protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); + + // remove active user-session + transactionStorage.remove(pendingReq.getPendingRequestId()); + + return; + + } else { + protAuthService.handleErrorNoRedirect(throwable, req, resp, true); + + } + } else { + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), + req, resp, false); + + } + + } catch (final Throwable e) { + log.error(e.getMessage(), e); + protAuthService.handleErrorNoRedirect(e, req, resp, false); + + } finally { + // remove pending-request + if (pendingReq != null) { + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, + pendingReq.getUniqueTransactionIdentifier()); + + } + + } + + } else { + log.debug("Request contains NO ErrorId"); + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, + resp, false); + + } + + } + + /** + * End-Point to finalize authentication protocol. + * + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ + @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) + public void finalizeAuthProtocol(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + + // read pendingRequest from http request + final String pendingRequestID = StringEscapeUtils + .escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); + final IRequest pendingReq = requestStorage.getPendingRequest(pendingRequestID); + + if (pendingReq == null) { + log.error("No PendingRequest with ID " + pendingRequestID + " found.!"); + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, + new Object[] {pendingRequestID,}), + req, resp, false); + + } else { + protAuthService.finalizeAuthentication(req, resp, pendingReq); + } + + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java index 722a9304..ac0876c4 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.protocols; import java.io.Serializable; @@ -35,444 +28,459 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; - +import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.NonNull; -import org.springframework.lang.Nullable; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egiz.eaaf.core.impl.utils.HttpUtils; import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; - -public abstract class RequestImpl implements IRequest, Serializable{ - - private static final Logger log = LoggerFactory.getLogger(RequestImpl.class); - - public static final String DATAID_REQUESTER_IP_ADDRESS = "reqestImpl_requesterIPAddr"; - - private static final long serialVersionUID = 1L; - - private String module = null; - private String action = null; - - private String pendingRequestId = null; - private String processInstanceId; - private String internalSSOSessionId; - - private String uniqueTransactionIdentifer; - private String uniqueSessionIdentifer; - - private String requestedServiceProviderIdentifer; - private String idpAuthURL = null; - - private ISPConfiguration spConfiguration = null; - - private boolean passiv = false; - private boolean force = false; - private boolean isAbortedByUser = false; - - //every request needs authentication by default - private boolean needAuthentication = true; - - //every request is not authenticated by default - private boolean isAuthenticated = false; - - //every request needs no SSO by default - private boolean needSSO = false; - - private boolean needUserConsent = false; - - private final Map<String, Object> genericDataStorage = new HashMap<String, Object>(); - - - /** - * Initialize this pendingRequest object - * - * @param req {@link HttpServletRequest} - * @param authConfig {@link IConfiguration} - * @throws EAAFException - * - */ - public final void initialize(HttpServletRequest req, IConfigurationWithSP authConfig) throws EAAFException { - initialize(req, authConfig, null); - - } - - /** - * Initialize this pendingRequest object - * - * @param req {@link HttpServletRequest} - * @param authConfig {@link IConfiguration} - * @param transactionId transactionId that should be used in this pendingRequest for logging. If 'null' a new one will be generated - * - * @throws EAAFException - * - */ - public final void initialize(@NonNull HttpServletRequest req, @NonNull IConfigurationWithSP authConfig, @Nullable String transactionId) throws EAAFException { - //use external transactionId or create new one if empty or null - if (StringUtils.isNotEmpty(transactionId)) - uniqueTransactionIdentifer = transactionId; - else - uniqueTransactionIdentifer = Random.nextLongRandom(); - - //set unique transaction identifier for logging - TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); - - //initialize session object - genericDataStorage.put(EAAFConstants.AUTH_DATA_CREATED, new Date()); - //genericDataStorage.put(EAAFConstants.VALUE_SESSIONID, Random.nextLongRandom()); - - //check if End-Point is valid - final String authURLString = HTTPUtils.extractAuthURLFromRequest(req); - URL authReqURL; - try { - authReqURL = new URL(authURLString); - - } catch (final MalformedURLException e) { - log.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authURLString, e); - throw new EAAFAuthenticationException("errorId", new Object[]{authURLString}, e); - - } - this.idpAuthURL = authConfig.validateIDPURL(authReqURL); - if (this.idpAuthURL == null) { - log.warn("Extract AuthenticationServiceURL: " + authReqURL + " is NOT found in configuration."); - throw new EAAFAuthenticationException("errorId", new Object[]{authURLString}); - - } - - //set unique session identifier - final String uniqueID = (String) req.getAttribute(EAAFConstants.UNIQUESESSIONIDENTIFIER); - if (StringUtils.isNotEmpty(uniqueID)) - this.uniqueSessionIdentifer = uniqueID; - - else { - log.debug("Create new sessionIdentifier for this pendingRequest ... "); - this.uniqueSessionIdentifer = UUID.randomUUID().toString(); - - } - - //set requester's IP address - try { - setRawDataToTransaction(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); - - } catch (final EAAFStorageException e) { - log.info("Can NOT store remote IP address into 'pendingRequest'." , e); - - } - - } - - public final void setSPEntityId(String spIdentifier) { - this.requestedServiceProviderIdentifer = spIdentifier; - } - - @Override - public final String getSPEntityId() { - return this.requestedServiceProviderIdentifer; - } - - @Override - public final boolean isPassiv() { - return passiv; - } - - @Override - public final boolean forceAuth() { - return force; - } - - public final void setPassiv(boolean passiv) { - this.passiv = passiv; - } - - public final void setForce(boolean force) { - this.force = force; - } - - @Override - public final String requestedAction() { - return action; - } - - public final void setAction(String action) { - this.action = action; - } - - @Override - public final String requestedModule() { - return module; - } - - public final void setModule(String module) { - this.module = module; - } - - public final void setPendingRequestId(String pendingReqId) { - this.pendingRequestId = pendingReqId; - - } - - @Override - @NonNull - public final String getPendingRequestId() { - if (pendingRequestId == null) - throw new IllegalStateException("No PendingRequestId set!!!"); - - return pendingRequestId; - } - - @Override - public final String getInternalSSOSessionIdentifier() { - return this.internalSSOSessionId; - } - - @Override - public final void setInternalSSOSessionIdentifier(String internalSSOSessionId) { - this.internalSSOSessionId = internalSSOSessionId; - - } - - @Override - public final <T> T getSessionData(final Class<T> wrapper) { - if (wrapper != null) { - if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { - try { - return wrapper.getConstructor(Map.class).newInstance(this.genericDataStorage); - - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - log.error("Can NOT instance wrapper: " + wrapper.getName(), e); - - } - - } - - log.error("Can NOT wrap generic data into session data. " - + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); - throw new RuntimeException("Can NOT wrap generic data into session data. " - + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); - - } - - return null; - - } - - @Override - public final ISPConfiguration getServiceProviderConfiguration() { - return this.spConfiguration; - - - } - - @Override - public <T> T getServiceProviderConfiguration(final Class<T> decorator) { - if (this.spConfiguration != null) { - if (decorator.isAssignableFrom(this.spConfiguration.getClass())) { - return (T) this.spConfiguration; - - } else - log.error("Can not decorate SP configuration by '" + decorator.getName() + "'."); - throw new RuntimeException("Can not decorate SP configuration by '" + decorator.getName() + "'."); - - } - - return null; - - } - - public void setOnlineApplicationConfiguration(ISPConfiguration spConfig) { - this.spConfiguration = spConfig; - - } - - @Override - public final String getUniqueTransactionIdentifier() { - return this.uniqueTransactionIdentifer; - - } - - @Override - public final String getUniqueSessionIdentifier() { - return this.uniqueSessionIdentifer; - - } - - @Override - public final String getProcessInstanceId() { - return this.processInstanceId; - - } - - public final void setUniqueTransactionIdentifier(String id) { - this.uniqueTransactionIdentifer = id; - - } - - public final void setUniqueSessionIdentifier(String id) { - this.uniqueSessionIdentifer = id; - - } - - public void setProcessInstanceId(String id) { - this.processInstanceId = id; - - } - - @Override - public final String getAuthURL() { - return this.idpAuthURL; - } - - @Override - public final String getAuthURLWithOutSlash() { - if (this.idpAuthURL.endsWith("/")) - return this.idpAuthURL.substring(0, this.idpAuthURL.length()-1); - else - return this.idpAuthURL; - - } - - @Override - public final boolean isNeedAuthentication() { - return needAuthentication; - } - - public final void setNeedAuthentication(boolean needAuthentication) { - this.needAuthentication = needAuthentication; - } - - @Override - public final boolean isAuthenticated() { - return isAuthenticated; - } - - @Override - public final void setAuthenticated(boolean isAuthenticated) { - this.isAuthenticated = isAuthenticated; - } - - @Override - public final boolean needSingleSignOnFunctionality() { - return needSSO; - } - @Override - public final void setNeedSingleSignOnFunctionality(boolean needSSO) { - this.needSSO = needSSO; - - } - - @Override - public final boolean isNeedUserConsent() { - return this.needUserConsent; - - } - - @Override - public final void setNeedUserConsent(boolean needConsent) { - this.needUserConsent = needConsent; - - } - - @Override - public final boolean isAbortedByUser() { - return this.isAbortedByUser; - } - - @Override - public final void setAbortedByUser(boolean isAborted) { - this.isAbortedByUser = isAborted; - - } - - @Override - public final Object getRawData(String key) { - if (StringUtils.isNotEmpty(key)) { - return genericDataStorage.get(key); - - } - - log.info("Can not load generic request-data with key='null'"); - return null; - } - - @Override - public final <T> T getRawData(String key, final Class<T> clazz) { - if (StringUtils.isNotEmpty(key)) { - final Object data = genericDataStorage.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - final - T test = (T) data; - return test; - - } catch (final Exception e) { - log.warn("Generic request-data object can not be casted to requested type", e); - return null; - - } - - } - - log.info("Can not load generic request-data with key='null'"); - return null; - - } - - @Override - public final void setRawDataToTransaction(String key, Object object) throws EAAFStorageException { - if (StringUtils.isEmpty(key)) { - log.info("Generic request-data can not be stored with a 'null' key"); - throw new EAAFStorageException("Generic request-data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - log.warn("Generic request-data can only store objects which implements the 'Seralizable' interface"); - throw new EAAFStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorage.containsKey(key)) - log.trace("Overwrite generic request-data with key:" + key); - else - log.trace("Add generic request-data with key:" + key + " to session."); - - genericDataStorage.put(key, object); - - } - - @Override - public final void setRawDataToTransaction(Map<String, Object> map) throws EAAFStorageException { - if (map == null) { - log.info("Generic request-data can not be stored with a 'null' map"); - throw new EAAFStorageException("Generic request-data can not be stored with a 'null' map", null); - - } - - //validate and store values - for (final Entry<String, Object> el : map.entrySet()) - setRawDataToTransaction(el.getKey(), el.getValue()); - - } - +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; + +public abstract class RequestImpl implements IRequest, Serializable { + + private static final Logger log = LoggerFactory.getLogger(RequestImpl.class); + + public static final String DATAID_REQUESTER_IP_ADDRESS = "reqestImpl_requesterIPAddr"; + + private static final long serialVersionUID = 1L; + + private String module = null; + private String action = null; + + private String pendingRequestId = null; + private String processInstanceId; + private String internalSsoSessionId; + + private String uniqueTransactionIdentifer; + private String uniqueSessionIdentifer; + + private String requestedServiceProviderIdentifer; + private String idpAuthUrl = null; + + private IspConfiguration spConfiguration = null; + + private boolean passiv = false; + private boolean force = false; + private boolean isAbortedByUser = false; + + // every request needs authentication by default + private boolean needAuthentication = true; + + // every request is not authenticated by default + private boolean isAuthenticated = false; + + // every request needs no SSO by default + private boolean needSso = false; + + private boolean needUserConsent = false; + + private final Map<String, Object> genericDataStorage = new HashMap<>(); + + + /** + * Initialize this pendingRequest object. + * + * @param req {@link HttpServletRequest} + * @param authConfig {@link IConfiguration} + * @throws EaafException + * + */ + public final void initialize(final HttpServletRequest req, final IConfigurationWithSP authConfig) + throws EaafException { + initialize(req, authConfig, null); + + } + + /** + * Initialize this pendingRequest object. + * + * @param req {@link HttpServletRequest} + * @param authConfig {@link IConfiguration} + * @param transactionId transactionId that should be used in this pendingRequest for logging. If + * 'null' a new one will be generated + * + * @throws EaafException + * + */ + public final void initialize(@NonNull final HttpServletRequest req, + @NonNull final IConfigurationWithSP authConfig, @Nullable final String transactionId) + throws EaafException { + // use external transactionId or create new one if empty or null + if (StringUtils.isNotEmpty(transactionId)) { + uniqueTransactionIdentifer = transactionId; + } else { + uniqueTransactionIdentifer = Random.nextLongRandom(); + } + + // set unique transaction identifier for logging + TransactionIdUtils.setTransactionId(uniqueTransactionIdentifer); + + // initialize session object + genericDataStorage.put(EAAFConstants.AUTH_DATA_CREATED, new Date()); + // genericDataStorage.put(EAAFConstants.VALUE_SESSIONID, Random.nextLongRandom()); + + // check if End-Point is valid + final String authUrlString = HttpUtils.extractAuthUrlFromRequest(req); + URL authReqUrl; + try { + authReqUrl = new URL(authUrlString); + + } catch (final MalformedURLException e) { + log.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authUrlString, e); + throw new EaafAuthenticationException("errorId", new Object[] {authUrlString}, e); + + } + this.idpAuthUrl = authConfig.validateIdpUrl(authReqUrl); + if (this.idpAuthUrl == null) { + log.warn( + "Extract AuthenticationServiceURL: " + authReqUrl + " is NOT found in configuration."); + throw new EaafAuthenticationException("errorId", new Object[] {authUrlString}); + + } + + // set unique session identifier + final String uniqueID = (String) req.getAttribute(EAAFConstants.UNIQUESESSIONIDENTIFIER); + if (StringUtils.isNotEmpty(uniqueID)) { + this.uniqueSessionIdentifer = uniqueID; + } else { + log.debug("Create new sessionIdentifier for this pendingRequest ... "); + this.uniqueSessionIdentifer = UUID.randomUUID().toString(); + + } + + // set requester's IP address + try { + setRawDataToTransaction(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); + + } catch (final EaafStorageException e) { + log.info("Can NOT store remote IP address into 'pendingRequest'.", e); + + } + + } + + public final void setSpEntityId(final String spIdentifier) { + this.requestedServiceProviderIdentifer = spIdentifier; + } + + @Override + public final String getSpEntityId() { + return this.requestedServiceProviderIdentifer; + } + + @Override + public final boolean isPassiv() { + return passiv; + } + + @Override + public final boolean forceAuth() { + return force; + } + + public final void setPassiv(final boolean passiv) { + this.passiv = passiv; + } + + public final void setForce(final boolean force) { + this.force = force; + } + + @Override + public final String requestedAction() { + return action; + } + + public final void setAction(final String action) { + this.action = action; + } + + @Override + public final String requestedModule() { + return module; + } + + public final void setModule(final String module) { + this.module = module; + } + + public final void setPendingRequestId(final String pendingReqId) { + this.pendingRequestId = pendingReqId; + + } + + @Override + @NonNull + public final String getPendingRequestId() { + if (pendingRequestId == null) { + throw new IllegalStateException("No PendingRequestId set!!!"); + } + + return pendingRequestId; + } + + @Override + public final String getInternalSsoSessionIdentifier() { + return this.internalSsoSessionId; + } + + @Override + public final void setInternalSsoSessionIdentifier(final String internalSsoSessionId) { + this.internalSsoSessionId = internalSsoSessionId; + + } + + @Override + @Nonnull + public final <T> T getSessionData(@Nonnull final Class<T> wrapper) { + Assert.notNull(wrapper, "Wrapper must NOT null"); + if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { + try { + return wrapper.getConstructor(Map.class).newInstance(this.genericDataStorage); + + } catch (NoSuchMethodException | SecurityException | InstantiationException + | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + log.error("Can NOT instance wrapper: " + wrapper.getName(), e); + + } + + } + + log.error("Can NOT wrap generic data into session data. " + "Reason: Wrapper " + + wrapper.getName() + " is NOT a valid wrapper"); + throw new RuntimeException("Can NOT wrap generic data into session data. " + "Reason: Wrapper " + + wrapper.getName() + " is NOT a valid wrapper"); + + } + + @Override + public final IspConfiguration getServiceProviderConfiguration() { + return this.spConfiguration; + + + } + + @Override + public <T> T getServiceProviderConfiguration(final Class<T> decorator) { + if (this.spConfiguration != null) { + if (decorator.isAssignableFrom(this.spConfiguration.getClass())) { + return (T) this.spConfiguration; + + } else { + log.error("Can not decorate SP configuration by '" + decorator.getName() + "'."); + } + throw new RuntimeException( + "Can not decorate SP configuration by '" + decorator.getName() + "'."); + + } + + return null; + + } + + public void setOnlineApplicationConfiguration(final IspConfiguration spConfig) { + this.spConfiguration = spConfig; + + } + + @Override + public final String getUniqueTransactionIdentifier() { + return this.uniqueTransactionIdentifer; + + } + + @Override + public final String getUniqueSessionIdentifier() { + return this.uniqueSessionIdentifer; + + } + + @Override + public final String getProcessInstanceId() { + return this.processInstanceId; + + } + + public final void setUniqueTransactionIdentifier(final String id) { + this.uniqueTransactionIdentifer = id; + + } + + public final void setUniqueSessionIdentifier(final String id) { + this.uniqueSessionIdentifer = id; + + } + + public void setProcessInstanceId(final String id) { + this.processInstanceId = id; + + } + + @Override + public final String getAuthUrl() { + return this.idpAuthUrl; + } + + @Override + public final String getAuthUrlWithOutSlash() { + if (this.idpAuthUrl.endsWith("/")) { + return this.idpAuthUrl.substring(0, this.idpAuthUrl.length() - 1); + } else { + return this.idpAuthUrl; + } + + } + + @Override + public final boolean isNeedAuthentication() { + return needAuthentication; + } + + public final void setNeedAuthentication(final boolean needAuthentication) { + this.needAuthentication = needAuthentication; + } + + @Override + public final boolean isAuthenticated() { + return isAuthenticated; + } + + @Override + public final void setAuthenticated(final boolean isAuthenticated) { + this.isAuthenticated = isAuthenticated; + } + + @Override + public final boolean needSingleSignOnFunctionality() { + return needSso; + } + + @Override + public final void setNeedSingleSignOnFunctionality(final boolean needSso) { + this.needSso = needSso; + + } + + @Override + public final boolean isNeedUserConsent() { + return this.needUserConsent; + + } + + @Override + public final void setNeedUserConsent(final boolean needConsent) { + this.needUserConsent = needConsent; + + } + + @Override + public final boolean isAbortedByUser() { + return this.isAbortedByUser; + } + + @Override + public final void setAbortedByUser(final boolean isAborted) { + this.isAbortedByUser = isAborted; + + } + + @Override + public final Object getRawData(final String key) { + if (StringUtils.isNotEmpty(key)) { + return genericDataStorage.get(key); + + } + + log.info("Can not load generic request-data with key='null'"); + return null; + } + + @Override + public final <T> T getRawData(final String key, final Class<T> clazz) { + if (StringUtils.isNotEmpty(key)) { + final Object data = genericDataStorage.get(key); + + if (data == null) { + return null; + } + + try { + @SuppressWarnings("unchecked") + final T test = (T) data; + return test; + + } catch (final Exception e) { + log.warn("Generic request-data object can not be casted to requested type", e); + return null; + + } + + } + + log.info("Can not load generic request-data with key='null'"); + return null; + + } + + @Override + public final void setRawDataToTransaction(final String key, final Object object) + throws EaafStorageException { + if (StringUtils.isEmpty(key)) { + log.info("Generic request-data can not be stored with a 'null' key"); + throw new EaafStorageException("Generic request-data can not be stored with a 'null' key", + null); + + } + + if (object != null) { + if (!Serializable.class.isInstance(object)) { + log.warn( + "Generic request-data can only store objects which implements the 'Seralizable' interface"); + throw new EaafStorageException( + "Generic request-data can only store objects which implements the 'Seralizable' interface", + null); + + } + } + + if (genericDataStorage.containsKey(key)) { + log.trace("Overwrite generic request-data with key:" + key); + } else { + log.trace("Add generic request-data with key:" + key + " to session."); + } + + genericDataStorage.put(key, object); + + } + + @Override + public final void setRawDataToTransaction(final Map<String, Object> map) + throws EaafStorageException { + if (map == null) { + log.info("Generic request-data can not be stored with a 'null' map"); + throw new EaafStorageException("Generic request-data can not be stored with a 'null' map", + null); + + } + + // validate and store values + for (final Entry<String, Object> el : map.entrySet()) { + setRawDataToTransaction(el.getKey(), el.getValue()); + } + + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java index 6b5f1a4c..3c8fd604 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java @@ -13,77 +13,85 @@ import org.slf4j.LoggerFactory; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.data.EAAFEventCodes; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; public abstract class AbstractLocaleAuthServletTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(AbstractLocaleAuthServletTask.class); - - public static final String PROP_REQ_PARAM_LOCALE = "lang"; - - @Override - public final void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - final Serializable changeLangFlag = executionContext.get(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE); - final String localeParam = StringEscapeUtils.escapeHtml4(request.getParameter(PROP_REQ_PARAM_LOCALE)); - if (StringUtils.isNotEmpty(localeParam) && - (changeLangFlag == null || !((Boolean)changeLangFlag)) ) { - log.debug("Find {} parameter. Reload last task with new locale: {}", PROP_REQ_PARAM_LOCALE, localeParam); - executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, true); - - - - } else { - log.trace("Find {} parameter. Processing this task ... ",PROP_REQ_PARAM_LOCALE); - executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, false); - - if (parseFlagFromHttpRequest(request, EAAFConstants.PARAM_HTTP_STOP_PROCESS, false)) { - log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); - stopProcessFromUserDecision(executionContext, request, response); - - } else - executeWithLocale(executionContext, request, response); - - } - - } - - protected void stopProcessFromUserDecision(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - try { - revisionsLogger.logEvent(pendingReq, EAAFEventCodes.PROCESS_STOPPED_BY_USER); - pendingReq.setAbortedByUser(true); - pendingReq.setAuthenticated(false); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - log.trace("Set process-cancelation flag"); - executionContext.setCanceleProcessFlag(); - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("Stopping auth.process FAILED", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } - - protected boolean parseFlagFromHttpRequest(HttpServletRequest httpReq, String httpParamName, boolean defaultValue) { - final String flag = httpReq.getParameter(httpParamName); - log.trace("Get httpParam: {} with value: {}", httpParamName, flag); - if (StringUtils.isNotEmpty(httpParamName)) { - return Boolean.parseBoolean(flag); - - } else { - return defaultValue; - } - - } - - protected abstract void executeWithLocale(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; + private static final Logger log = LoggerFactory.getLogger(AbstractLocaleAuthServletTask.class); + + public static final String PROP_REQ_PARAM_LOCALE = "lang"; + + @Override + public final void execute(final ExecutionContext executionContext, + final HttpServletRequest request, final HttpServletResponse response) + throws TaskExecutionException { + + final Serializable changeLangFlag = + executionContext.get(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE); + final String localeParam = + StringEscapeUtils.escapeHtml4(request.getParameter(PROP_REQ_PARAM_LOCALE)); + if (StringUtils.isNotEmpty(localeParam) + && (changeLangFlag == null || !((Boolean) changeLangFlag))) { + log.debug("Find {} parameter. Reload last task with new locale: {}", PROP_REQ_PARAM_LOCALE, + localeParam); + executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, true); + + + + } else { + log.trace("Find {} parameter. Processing this task ... ", PROP_REQ_PARAM_LOCALE); + executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, false); + + if (parseFlagFromHttpRequest(request, EAAFConstants.PARAM_HTTP_STOP_PROCESS, false)) { + log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); + stopProcessFromUserDecision(executionContext, request, response); + + } else { + executeWithLocale(executionContext, request, response); + } + + } + + } + + protected void stopProcessFromUserDecision(final ExecutionContext executionContext, + final HttpServletRequest request, final HttpServletResponse response) + throws TaskExecutionException { + try { + revisionsLogger.logEvent(pendingReq, EAAFEventCodes.PROCESS_STOPPED_BY_USER); + pendingReq.setAbortedByUser(true); + pendingReq.setAuthenticated(false); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + log.trace("Set process-cancelation flag"); + executionContext.setCanceleProcessFlag(); + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("Stopping auth.process FAILED", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } + + protected boolean parseFlagFromHttpRequest(final HttpServletRequest httpReq, + final String httpParamName, final boolean defaultValue) { + final String flag = httpReq.getParameter(httpParamName); + log.trace("Get httpParam: {} with value: {}", httpParamName, flag); + if (StringUtils.isNotEmpty(httpParamName)) { + return Boolean.parseBoolean(flag); + + } else { + return defaultValue; + } + + } + + protected abstract void executeWithLocale(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java index b12a69b2..7991c093 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java @@ -1,81 +1,79 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.tasks; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** + * Finalize the authentication process-flow. + * * @author tlenz * */ @Component("FinalizeAuthenticationTask") public class FinalizeAuthenticationTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(FinalizeAuthenticationTask.class); - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - try { - //set pending request to authenticated - pendingReq.setAuthenticated(true); - revisionsLogger.logEvent(pendingReq, IAuthenticationManager.EVENT_AUTHENTICATION_PROCESS_FINISHED); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } finally { - executionContext.remove(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID); - - } - - } + private static final Logger log = LoggerFactory.getLogger(FinalizeAuthenticationTask.class); + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process. + * api.ExecutionContext, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + + try { + // set pending request to authenticated + pendingReq.setAuthenticated(true); + revisionsLogger.logEvent(pendingReq, + IAuthenticationManager.EVENT_AUTHENTICATION_PROCESS_FINISHED); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("FinalizeAuthenticationTask has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } finally { + executionContext.remove(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID); + + } + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java index 5ea5baa1..7a2c5f08 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java @@ -1,121 +1,122 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.tasks; import java.util.Set; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.ModuleRegistration; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** + * Restart the authentication process-flow. + * * @author tlenz * */ @Component("RestartAuthProzessManagement") -public class RestartAuthProzessManagement extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(RestartAuthProzessManagement.class); - - @Autowired ProcessEngine processEngine; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - - if (this.pendingReq.isAbortedByUser()) { - log.debug("AuthProcess was stopped. Forward to finalization ... "); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - } else { - //create a new execution context and copy all elements to new context - final ExecutionContext newec = new ExecutionContextImpl(); - final Set<String> entries = executionContext.keySet(); - for (final String key : entries) { - newec.put(key, executionContext.get(key)); - - } - - log.debug("Select new auth.-process and restart restart process-engine ... "); - - // select and create new process instance - final String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec, pendingReq); - if (processDefinitionId == null) { - log.warn("No suitable authentication process found for SessionID " + pendingReq.getPendingRequestId()); - throw new EAAFException("process.02", new Object[] { pendingReq.getPendingRequestId()}); - } - - final String processInstanceId = processEngine.createProcessInstance(processDefinitionId, newec); - - // keep process instance id in moa session - ((RequestImpl)pendingReq).setProcessInstanceId(processInstanceId); - - // make sure pending request has been persisted before running the process - try { - requestStoreage.storePendingRequest(pendingReq); - - } catch (final EAAFException e) { - log.error("Database Error! MOASession is not stored!"); - throw new EAAFException("internal.02", null); - - } - - log.info("Restart process-engine with auth.process:" + processDefinitionId); - - // start process - processEngine.start(pendingReq); - - } - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("RestartAuthProzessManagement has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } +public class RestartAuthProzessManagement extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(RestartAuthProzessManagement.class); + + @Autowired ProcessEngine processEngine; + @Autowired ModuleRegistration moduleRegistration; + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process. + * api.ExecutionContext, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + try { + + if (this.pendingReq.isAbortedByUser()) { + log.debug("AuthProcess was stopped. Forward to finalization ... "); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + } else { + // create a new execution context and copy all elements to new context + final ExecutionContext newec = new ExecutionContextImpl(); + final Set<String> entries = executionContext.keySet(); + for (final String key : entries) { + newec.put(key, executionContext.get(key)); + + } + + log.debug("Select new auth.-process and restart restart process-engine ... "); + + // select and create new process instance + final String processDefinitionId = + moduleRegistration.selectProcess(newec, pendingReq); + if (processDefinitionId == null) { + log.warn("No suitable authentication process found for SessionID " + + pendingReq.getPendingRequestId()); + throw new EaafException("process.02", new Object[] {pendingReq.getPendingRequestId()}); + } + + final String processInstanceId = + processEngine.createProcessInstance(processDefinitionId, newec); + + // keep process instance id in moa session + ((RequestImpl) pendingReq).setProcessInstanceId(processInstanceId); + + // make sure pending request has been persisted before running the process + try { + requestStoreage.storePendingRequest(pendingReq); + + } catch (final EaafException e) { + log.error("Database Error! MOASession is not stored!"); + throw new EaafException("internal.02", null); + + } + + log.info("Restart process-engine with auth.process:" + processDefinitionId); + + // start process + processEngine.start(pendingReq); + + } + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("RestartAuthProzessManagement has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } } |