diff --git a/pom.xml b/pom.xml
index 7278b9324..11becf139 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,7 +7,7 @@
eusurvey
eusurvey
war
- 1.4.4
+ 1.4.5
1.8
4.3.20.RELEASE
diff --git a/sonar-project.properties b/sonar-project.properties
index e5391deea..338bbf1d5 100644
--- a/sonar-project.properties
+++ b/sonar-project.properties
@@ -1,6 +1,6 @@
sonar.projectKey=EUSURVEY
sonar.projectName=eusurvey
-sonar.projectVersion=1.4.4
+sonar.projectVersion=1.4.5
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional if sonar.modules is set.
diff --git a/src/main/java/com/ec/survey/controller/AddressBookController.java b/src/main/java/com/ec/survey/controller/AddressBookController.java
index a822cae8e..922406944 100644
--- a/src/main/java/com/ec/survey/controller/AddressBookController.java
+++ b/src/main/java/com/ec/survey/controller/AddressBookController.java
@@ -316,7 +316,7 @@ public ModelAndView batchEdit(HttpServletRequest request) throws Exception {
}
@RequestMapping(value = "/batchEdit", method = RequestMethod.POST)
- public ModelAndView batchEditPOST(HttpServletRequest request, Locale locale) throws IntrusionException, NotAgreedToTosException {
+ public ModelAndView batchEditPOST(HttpServletRequest request, Locale locale) throws IntrusionException, NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
boolean userChanged = false;
@@ -1349,7 +1349,7 @@ public ModelAndView edit(@PathVariable("id") String id, HttpServletRequest reque
}
@RequestMapping( value = "/configureAttributes", method = RequestMethod.POST)
- public String configureAttributes(HttpServletRequest request) throws NotAgreedToTosException {
+ public String configureAttributes(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Map parameterMap = Ucs2Utf8.requestToHashMap(request);
@@ -1389,7 +1389,7 @@ public String configureAttributes(HttpServletRequest request) throws NotAgreedTo
}
@RequestMapping(value = "/configureAttributesJSON", headers="Accept=*/*", method=RequestMethod.GET)
- public @ResponseBody List configureAttributesJSON(HttpServletRequest request, HttpServletResponse response ) throws NotAgreedToTosException {
+ public @ResponseBody List configureAttributesJSON(HttpServletRequest request, HttpServletResponse response ) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Map parameterMap = Ucs2Utf8.requestToHashMap(request);
diff --git a/src/main/java/com/ec/survey/controller/AdministrationController.java b/src/main/java/com/ec/survey/controller/AdministrationController.java
index 1530b3606..1b0c3c79e 100644
--- a/src/main/java/com/ec/survey/controller/AdministrationController.java
+++ b/src/main/java/com/ec/survey/controller/AdministrationController.java
@@ -12,6 +12,7 @@
import com.ec.survey.tools.RecreateAllOLAPTablesExecutor;
import com.ec.survey.tools.Tools;
import com.ec.survey.tools.UpdateAllOLAPTablesExecutor;
+import com.ec.survey.tools.WeakAuthenticationException;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
@@ -116,7 +117,7 @@ public class AdministrationController extends BasicController {
}
@RequestMapping(value = "/saveUserConfiguration", method = {RequestMethod.POST})
- public @ResponseBody String saveUserConfiguration(HttpServletRequest request) throws NotAgreedToTosException {
+ public @ResponseBody String saveUserConfiguration(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
int userId = sessionService.getCurrentUser(request).getId();
UsersConfiguration usersConfiguration = administrationService.getUsersConfiguration(userId);
diff --git a/src/main/java/com/ec/survey/controller/BasicController.java b/src/main/java/com/ec/survey/controller/BasicController.java
index d8985ba0b..851aab1ce 100644
--- a/src/main/java/com/ec/survey/controller/BasicController.java
+++ b/src/main/java/com/ec/survey/controller/BasicController.java
@@ -28,6 +28,7 @@
import org.springframework.web.servlet.ModelAndView;
import com.ec.survey.exception.ForbiddenURLException;
+import com.ec.survey.exception.FrozenSurveyException;
import com.ec.survey.exception.InvalidURLException;
import com.ec.survey.exception.MessageException;
import com.ec.survey.exception.NoFormLoadedException;
@@ -58,6 +59,7 @@
import com.ec.survey.tools.ConversionTools;
import com.ec.survey.tools.InvalidXHTMLException;
import com.ec.survey.tools.NotAgreedToTosException;
+import com.ec.survey.tools.WeakAuthenticationException;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.multitype.MultiTypeCaptchaService;
@@ -133,6 +135,8 @@ public class BasicController implements BeanFactoryAware {
public @Value("${ecashost}") String ecashost;
public @Value("${sender}") String sender;
public @Value("${captcha.bypass:@null}") String bypassCaptcha;
+ public @Value("${ui.enablepublicsurveys}") String enablepublicsurveys;
+
//OCAS
public @Value("${casoss}") String cassOss;
protected @Value("${contextpath}") String contextpath;
@@ -190,6 +194,22 @@ public boolean isByPassCaptcha(){
return bypassCaptcha !=null && bypassCaptcha.equalsIgnoreCase("true");
}
+ @ExceptionHandler(com.ec.survey.tools.Bad2faCredentialsException.class)
+ public ModelAndView handleBad2faCredentialsException(Exception e, HttpServletRequest request) {
+ logger.info(e.getLocalizedMessage(), e);
+ ModelAndView model = new ModelAndView("redirect:/errors/2fa.html");
+ model.addObject("contextpath", contextpath);
+ return model;
+ }
+
+ @ExceptionHandler(com.ec.survey.tools.FrozenCredentialsException.class)
+ public ModelAndView handleFrozenCredentialsException(Exception e, HttpServletRequest request) {
+ logger.info(e.getLocalizedMessage(), e);
+ ModelAndView model = new ModelAndView("redirect:/errors/frozen.html");
+ model.addObject("contextpath", contextpath);
+ return model;
+ }
+
@ExceptionHandler(InvalidURLException.class)
public ModelAndView handleInvalidURLException(Exception e, HttpServletRequest request) {
logger.info(e.getLocalizedMessage(), e);
@@ -199,6 +219,16 @@ public ModelAndView handleInvalidURLException(Exception e, HttpServletRequest re
return model;
}
+ @ExceptionHandler(FrozenSurveyException.class)
+ public ModelAndView handleFrozenSurveyException(Exception e, HttpServletRequest request, Locale locale) {
+ logger.error(e.getLocalizedMessage(), e);
+ ModelAndView model = new ModelAndView("error/generic");
+ String message = resources.getMessage("error.FrozenSurvey", null, "This survey has been blocked due to an infringement to our policy. We are sorry for the inconvenience this may cause. Please try again later.", locale);
+ model.addObject("message", message);
+ model.addObject("contextpath", contextpath);
+ return model;
+ }
+
@ExceptionHandler(ForbiddenURLException.class)
public ModelAndView handleForbiddenURLException(Exception e, HttpServletRequest request) {
logger.info(e.getLocalizedMessage(), e);
@@ -214,6 +244,16 @@ public ModelAndView handleNotAgreedToTosException(Exception e, HttpServletReques
return model;
}
+ @ExceptionHandler(WeakAuthenticationException.class)
+ public ModelAndView handleWeakAuthenticationException(Exception e, HttpServletRequest request, Locale locale) {
+ logger.error(e.getLocalizedMessage(), e);
+ ModelAndView model = new ModelAndView("error/generic");
+ String message = resources.getMessage("error.WeakAuthentication", null, "Please log in using two factor authentication in order to access the system.", locale);
+ model.addObject("message", message);
+ model.addObject("contextpath", contextpath);
+ return model;
+ }
+
@ExceptionHandler(TooManyFiltersException.class)
public ModelAndView handleTooManyFiltersException(Exception e, HttpServletRequest request, Locale locale) {
logger.error(e.getLocalizedMessage(), e);
diff --git a/src/main/java/com/ec/survey/controller/ContributionController.java b/src/main/java/com/ec/survey/controller/ContributionController.java
index 76c7a39a7..af19f5aec 100644
--- a/src/main/java/com/ec/survey/controller/ContributionController.java
+++ b/src/main/java/com/ec/survey/controller/ContributionController.java
@@ -19,6 +19,8 @@
import com.ec.survey.tools.QuizHelper;
import com.ec.survey.tools.SurveyHelper;
import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
+
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
@@ -57,7 +59,7 @@ public class ContributionController extends BasicController {
private @Value("${export.fileDir}") String fileDir;
private @Value("${server.prefix}") String serverPrefix;
- public AnswerSet getAnswerSet(String code, HttpServletRequest request) throws NotAgreedToTosException
+ public AnswerSet getAnswerSet(String code, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException
{
AnswerSet answerSet = null;
User user = sessionService.getCurrentUser(request);
diff --git a/src/main/java/com/ec/survey/controller/DashboardController.java b/src/main/java/com/ec/survey/controller/DashboardController.java
index b6618d2c9..86fbe3d58 100644
--- a/src/main/java/com/ec/survey/controller/DashboardController.java
+++ b/src/main/java/com/ec/survey/controller/DashboardController.java
@@ -68,6 +68,8 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m
archiveService.delete(archive);
}
+ //check user (e.g. weak authentication)
+ sessionService.getCurrentUser(request);
ModelAndView result = new ModelAndView("dashboard");
if (request.getParameter("archived") != null)
@@ -82,6 +84,12 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m
result.addObject("deleted", shortname);
}
+ if (request.getParameter("frozen") != null)
+ {
+ String shortname = request.getParameter("frozen");
+ result.addObject("frozen", shortname);
+ }
+
result.addObject("filter", new ArchiveFilter());
return result;
@@ -281,8 +289,18 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m
filter.setSortOrder(request.getParameter("asc") != null && request.getParameter("asc").equalsIgnoreCase("true") ? "ASC" : "DESC");
}
+ if (request.getParameter("reported") != null)
+ {
+ filter.setSurveys("REPORTED");
+ }
+
+ if (request.getParameter("frozen") != null)
+ {
+ filter.setSurveys("FROZEN");
+ }
+
SqlPagination paging = new SqlPagination(page, 10);
- List result = surveyService.getSurveysIncludingTranslationLanguages(filter, paging, false);
+ List result = surveyService.getSurveysIncludingTranslationLanguages(filter, paging, false, false);
surveyService.generateAccessInformation(result, u);
diff --git a/src/main/java/com/ec/survey/controller/ExportsController.java b/src/main/java/com/ec/survey/controller/ExportsController.java
index 00ed041c1..0e7e0a42f 100644
--- a/src/main/java/com/ec/survey/controller/ExportsController.java
+++ b/src/main/java/com/ec/survey/controller/ExportsController.java
@@ -13,6 +13,7 @@
import com.ec.survey.service.SurveyService;
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.StringUtils;
import org.apache.poi.util.IOUtils;
@@ -225,7 +226,7 @@ public class ExportsController extends BasicController {
@RequestMapping(value = "/list")
- public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
sessionService.getCurrentUser(request);
//default
@@ -251,7 +252,7 @@ public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosExcept
}
@RequestMapping(value = "/exportsjson", method = {RequestMethod.GET, RequestMethod.HEAD})
- public @ResponseBody List exportsjson(HttpServletRequest request) throws NotAgreedToTosException {
+ public @ResponseBody List exportsjson(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
int itemsPerPage = -1;
int page = -1;
@@ -396,7 +397,7 @@ public ResponseEntity downloadExport(@PathVariable int exportId, HttpSer
}
@RequestMapping(value = "/recreate/{exportId}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView recreateExport(@PathVariable int exportId, HttpServletRequest request, Locale locale) throws NotAgreedToTosException {
+ public ModelAndView recreateExport(@PathVariable int exportId, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
Export export = exportService.getExport(exportId, true);
if (export == null || !(sessionService.checkUser(export.getUserId(), request) || sessionService.getCurrentUser(request).getGlobalPrivileges().get(GlobalPrivilege.FormManagement).equals(2))) {
return new ModelAndView("error/generic", "message", "Access denied");
@@ -406,7 +407,7 @@ public ModelAndView recreateExport(@PathVariable int exportId, HttpServletReques
}
@RequestMapping(value = "/recreateMany/{exportIdList}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView recreateExport(@PathVariable String exportIdList, HttpServletRequest request, Locale locale) throws NotAgreedToTosException {
+ public ModelAndView recreateExport(@PathVariable String exportIdList, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
String[] exportIds = exportIdList.split("-");
List exports = new ArrayList<>();
diff --git a/src/main/java/com/ec/survey/controller/HomeController.java b/src/main/java/com/ec/survey/controller/HomeController.java
index 58759711a..e1460322d 100644
--- a/src/main/java/com/ec/survey/controller/HomeController.java
+++ b/src/main/java/com/ec/survey/controller/HomeController.java
@@ -1,5 +1,6 @@
package com.ec.survey.controller;
+import com.ec.survey.exception.InvalidURLException;
import com.ec.survey.model.*;
import com.ec.survey.model.administration.User;
import com.ec.survey.model.survey.Survey;
@@ -626,7 +627,7 @@ public ModelAndView processSubmit(HttpServletRequest request, Locale locale) {
Survey survey = surveyService.getSurvey(Integer.parseInt(request.getParameter("survey.id")), false, true);
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
AnswerSet answerSet = SurveyHelper.parseAndMergeAnswerSet(request, survey, fileDir, uniqueCode, oldAnswerSet, oldAnswerSet.getLanguageCode(), user, fileService);
saveAnswerSet(answerSet, fileDir, null, -1);
@@ -670,6 +671,11 @@ public ModelAndView publicsurveysrunner(HttpServletRequest request) throws Excep
public ModelAndView publicsurveys(HttpServletRequest request) throws Exception {
+ if (!enablepublicsurveys.equalsIgnoreCase("true"))
+ {
+ throw new InvalidURLException();
+ }
+
SurveyFilter filter = sessionService.getSurveyFilter(request, false);
filter.setUser(null);
String newPage = request.getParameter("newPage");
@@ -723,6 +729,11 @@ else if (sortKey.equalsIgnoreCase("popularity"))
@RequestMapping(value = "/home/publicsurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD})
public @ResponseBody List publicsurveysjson(HttpServletRequest request) throws Exception {
+ if (!enablepublicsurveys.equalsIgnoreCase("true"))
+ {
+ throw new InvalidURLException();
+ }
+
int itemsPerPage = 10;
int newPage = 1;
@@ -753,7 +764,7 @@ else if (sortKey.equalsIgnoreCase("popularity"))
SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lastPublicSurveyFilter");
SqlPagination sqlPagination = new SqlPagination(newPage, itemsPerPage);
- return surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false);
+ return surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, false);
}
@RequestMapping(value = "/validate/{id}/{code}", method = {RequestMethod.GET, RequestMethod.HEAD})
@@ -811,4 +822,82 @@ public void notifyError(HttpServletRequest request, Locale locale, HttpServletRe
machineTranslationService.saveErrorResponse(requestId,targetLanguage,errorCode,errorMessage);
}
+ @RequestMapping(value = "/home/reportAbuse", method = RequestMethod.GET)
+ public String reportAbuse (HttpServletRequest request, Locale locale, Model model) throws InvalidURLException {
+ model.addAttribute("lang", locale.getLanguage());
+ model.addAttribute("runnermode", true);
+
+ String surveyid = request.getParameter("survey");
+ if (surveyid == null || surveyid.trim().length() == 0)
+ {
+ throw new InvalidURLException();
+ }
+
+ try {
+ int id = Integer.parseInt(surveyid);
+
+ Survey survey = surveyService.getSurvey(id);
+
+ if (survey == null)
+ {
+ throw new InvalidURLException();
+ }
+
+ model.addAttribute("AbuseSurvey", survey.getUniqueId());
+ model.addAttribute("AbuseType", "");
+ model.addAttribute("AbuseText", "");
+ model.addAttribute("AbuseEmail", "");
+
+ } catch (NumberFormatException e)
+ {
+ throw new InvalidURLException();
+ }
+
+ return "home/reportabuse";
+ }
+
+ @RequestMapping(value = "home/reportAbuse", method = RequestMethod.POST)
+ public ModelAndView reportAbusePOST(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NumberFormatException, Exception {
+ ModelAndView model = new ModelAndView("home/reportabuse");
+
+ String uid = request.getParameter("abuseSurvey");
+ String type = request.getParameter("abuseType");
+ String text = request.getParameter("abuseText");
+ String email = request.getParameter("abuseEmail");
+
+ Survey survey = surveyService.getSurveyByUniqueId(uid, false, true);
+
+ if (survey == null)
+ {
+ throw new InvalidURLException();
+ }
+
+ if (!checkCaptcha(request)) {
+ model.addObject("wrongcaptcha", true);
+ model.addObject("contextpath", contextpath);
+
+ model.addObject("AbuseSurvey", uid);
+ model.addObject("AbuseType", type);
+ model.addObject("AbuseText", text);
+ model.addObject("AbuseEmail", email);
+
+ return model;
+ }
+
+ logger.info("HomeController.reportAbuse called with abuseType " + type);
+
+ surveyService.reportAbuse(survey, type, text, email);
+
+ model = new ModelAndView("error/info");
+ String message = resources.getMessage("info.ReportAbuseSent", null, "The abuse has been reported to the team in charge of the service.", locale);
+
+ model.addObject("message", message);
+ model.addObject("contextpath", contextpath);
+
+ String link = serverPrefix + "runner/" + survey.getShortname();
+ model.addObject("SurveyLink", link);
+
+ return model;
+ }
+
}
diff --git a/src/main/java/com/ec/survey/controller/HttpErrorController.java b/src/main/java/com/ec/survey/controller/HttpErrorController.java
index b80cdf3ae..f51175461 100644
--- a/src/main/java/com/ec/survey/controller/HttpErrorController.java
+++ b/src/main/java/com/ec/survey/controller/HttpErrorController.java
@@ -51,6 +51,18 @@ public ModelAndView handleException(HttpServletRequest request){
request.getSession().setAttribute("lastErrorTime", new Date());
request.getSession().setAttribute("lastErrorURL", request.getAttribute("javax.servlet.error.request_uri"));
return new ModelAndView("error/500","error","exception" );
+ }
+
+ @RequestMapping(value = "/2fa.html")
+ @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
+ public ModelAndView handle2fa(HttpServletRequest request){
+ return new ModelAndView("error/2fa","error","exception" );
+ }
+
+ @RequestMapping(value = "/frozen.html")
+ @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
+ public ModelAndView handlefrozen(HttpServletRequest request){
+ return new ModelAndView("error/frozen","error","exception" );
}
}
diff --git a/src/main/java/com/ec/survey/controller/LoginLogoutController.java b/src/main/java/com/ec/survey/controller/LoginLogoutController.java
index 8c925fa81..7653690cc 100644
--- a/src/main/java/com/ec/survey/controller/LoginLogoutController.java
+++ b/src/main/java/com/ec/survey/controller/LoginLogoutController.java
@@ -9,6 +9,7 @@
import com.ec.survey.service.SessionService;
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -76,7 +77,7 @@ public String getLoginPageRunnerMode(@RequestParam(value="error", required=false
}
@RequestMapping(value = "/auth/login", method = {RequestMethod.GET, RequestMethod.HEAD})
- public String getLoginPage(@RequestParam(value="error", required=false) boolean error, HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException {
+ public String getLoginPage(@RequestParam(value="error", required=false) boolean error, HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
if (isShowEcas()) model.put("showecas", true);
if (isCasOss()) model.put("casoss", true);
@@ -138,7 +139,7 @@ public void surveylogin(@RequestParam(value="error", required=false) boolean err
}
@RequestMapping(value = "/auth/logout", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView getLogoutPage(HttpServletRequest request) {
+ public ModelAndView getLogoutPage(HttpServletRequest request) throws WeakAuthenticationException {
ModelAndView result = new ModelAndView("home/welcome");
result.addObject("page", "welcome");
User user = null;
@@ -146,6 +147,8 @@ public ModelAndView getLogoutPage(HttpServletRequest request) {
user = sessionService.getCurrentUser(request);
} catch (NotAgreedToTosException e) {
//ignore
+ } catch (WeakAuthenticationException e) {
+ //ignore
}
if (user != null && user.getType().equalsIgnoreCase(User.ECAS))
diff --git a/src/main/java/com/ec/survey/controller/ManagementController.java b/src/main/java/com/ec/survey/controller/ManagementController.java
index 87218f9ce..e8f642e54 100644
--- a/src/main/java/com/ec/survey/controller/ManagementController.java
+++ b/src/main/java/com/ec/survey/controller/ManagementController.java
@@ -1,6 +1,7 @@
package com.ec.survey.controller;
import com.ec.survey.exception.ForbiddenURLException;
+import com.ec.survey.exception.FrozenSurveyException;
import com.ec.survey.exception.InvalidURLException;
import com.ec.survey.exception.NoFormLoadedException;
import com.ec.survey.model.*;
@@ -59,8 +60,7 @@ public class ManagementController extends BasicController {
public @Value("${opc.users}") String opcusers;
public @Value("${opc.department:@null}") String opcdepartments;
public @Value("${opc.template}") String opctemplatesurvey;
- public @Value("${ui.enablepublicsurveys}") String enablepublicsurveys;
-
+
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat(ConversionTools.DateFormat);
@@ -194,6 +194,7 @@ public ModelAndView overview(@PathVariable String shortname, HttpServletRequest
Survey survey = surveyService.getSurveyByShortname(shortname, true, user, request, false, true, true, false);
survey.setNumberOfAnswerSetsPublished(surveyService.getNumberPublishedAnswersFromMaterializedView(survey.getUniqueId()));
+ survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId()));
form = new Form(resources);
@@ -341,7 +342,7 @@ public ModelAndView exportSurvey(@PathVariable String answers, @PathVariable Str
paging.moveTo("1");
SqlPagination sqlPagination = paginationMapper.toSqlPagination(paging);
- List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false);
+ List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, false);
paging.setItems(surveys);
result = new ModelAndView("forms/forms", "paging", paging);
@@ -2594,6 +2595,11 @@ public ModelAndView test(@PathVariable String shortname, HttpServletRequest requ
User u = sessionService.getCurrentUser(request);
Survey survey = surveyService.getSurveyByShortname(shortname, true, u, request, true, true, true, false);
+ if (survey.getIsFrozen())
+ {
+ throw new FrozenSurveyException();
+ }
+
sessionService.upgradePrivileges(survey, u, request);
Form form = new Form(survey, translationService.getTranslationsForSurvey(survey.getId(), true), survey.getLanguage(), resources,contextpath);
diff --git a/src/main/java/com/ec/survey/controller/PDFController.java b/src/main/java/com/ec/survey/controller/PDFController.java
index 3ce56dff5..48a908ad5 100644
--- a/src/main/java/com/ec/survey/controller/PDFController.java
+++ b/src/main/java/com/ec/survey/controller/PDFController.java
@@ -14,6 +14,7 @@
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.SurveyExecutor;
import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang.StringUtils;
@@ -328,7 +329,7 @@ private void SendFile(Survey survey, HttpServletRequest request, Locale locale,
}
@RequestMapping(value = "/answer/{code}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView answer(@PathVariable String code, HttpServletRequest request, Locale locale, HttpServletResponse response) throws InvalidURLException, NotAgreedToTosException, ForbiddenURLException {
+ public ModelAndView answer(@PathVariable String code, HttpServletRequest request, Locale locale, HttpServletResponse response) throws InvalidURLException, NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
if (user == null)
diff --git a/src/main/java/com/ec/survey/controller/RunnerController.java b/src/main/java/com/ec/survey/controller/RunnerController.java
index 450233c5b..6f8744e9e 100644
--- a/src/main/java/com/ec/survey/controller/RunnerController.java
+++ b/src/main/java/com/ec/survey/controller/RunnerController.java
@@ -1,6 +1,7 @@
package com.ec.survey.controller;
import com.ec.survey.exception.ForbiddenURLException;
+import com.ec.survey.exception.FrozenSurveyException;
import com.ec.survey.exception.InvalidURLException;
import com.ec.survey.exception.SmtpServerNotConfiguredException;
import com.ec.survey.model.*;
@@ -118,7 +119,7 @@ public ModelAndView confirmation(HttpServletRequest request, HttpServletResponse
}
@RequestMapping(value = "/invited/{group}/{unique}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView invited(@PathVariable String group, @PathVariable String unique, HttpServletRequest request, Locale locale, Integer draftSurveyId, Device device) {
+ public ModelAndView invited(@PathVariable String group, @PathVariable String unique, HttpServletRequest request, Locale locale, Integer draftSurveyId, Device device) throws WeakAuthenticationException {
boolean readonlyMode = false;
String p = request.getParameter("readonly");
@@ -230,9 +231,14 @@ public ModelAndView invited(@PathVariable String group, @PathVariable String uni
if (draftSurvey.getIsDeleted() || draftSurvey.getArchived()) {
throw new InvalidURLException();
}
-
+
if (!readonlyMode) return getEscapePageModel(draftSurvey, request, device);
}
+
+ if (draftSurvey.getIsFrozen())
+ {
+ throw new FrozenSurveyException();
+ }
Form f = new Form(survey, translationService.getTranslationsForSurvey(survey.getId(), true), survey.getLanguage(), resources, contextpath);
@@ -367,7 +373,7 @@ public ModelAndView invited(@PathVariable String group, @PathVariable String uni
}
@RequestMapping(value = "/{shortname}/{token}", method = RequestMethod.POST)
- public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariable String token, HttpServletRequest request, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException {
+ public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariable String token, HttpServletRequest request, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException, FrozenSurveyException {
Survey survey = surveyService.getSurveyByShortname(shortname, false, null, request, true, true, true, true); //(shortname, false, true, false, false, null, true);
@@ -387,6 +393,11 @@ public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariabl
}
}
+ if (survey.getIsFrozen())
+ {
+ throw new FrozenSurveyException();
+ }
+
try {
// check for token
@@ -458,7 +469,7 @@ public ModelAndView invitedPOST(@PathVariable String group, @PathVariable String
}
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
AnswerSet answerSet = SurveyHelper.parseAnswerSet(request, survey, fileDir, uniqueCode, false, lang, user, fileService);
if (survey != null) {
@@ -737,7 +748,7 @@ public ModelAndView preparesurvey(@PathVariable String id, HttpServletRequest re
}
@RequestMapping(value = "/{uidorshortname}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView runner(@PathVariable String uidorshortname, HttpServletRequest request, HttpServletResponse response, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException {
+ public ModelAndView runner(@PathVariable String uidorshortname, HttpServletRequest request, HttpServletResponse response, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException, WeakAuthenticationException, FrozenSurveyException {
ModelAndView modelReturn= new ModelAndView();
boolean internalUsersOnly = false;
@@ -806,7 +817,7 @@ public ModelAndView runner(@PathVariable String uidorshortname, HttpServletReque
{
try {
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
boolean ecasauthenticated = request.getSession().getAttribute("ECASSURVEY") != null && request.getSession().getAttribute("ECASSURVEY").toString().startsWith(uidorshortname);
@@ -953,7 +964,7 @@ private ModelAndView getEscapePageModel(Survey survey, HttpServletRequest reques
}
}
- private ModelAndView loadSurvey(Survey survey, HttpServletRequest request, HttpServletResponse response, Locale locale, String action, boolean passwordauthenticated, Device device, boolean readonlyMode) throws ForbiddenURLException {
+ private ModelAndView loadSurvey(Survey survey, HttpServletRequest request, HttpServletResponse response, Locale locale, String action, boolean passwordauthenticated, Device device, boolean readonlyMode) throws ForbiddenURLException, WeakAuthenticationException {
if (survey != null) {
String draftid = request.getParameter("draftid");
@@ -1290,7 +1301,7 @@ public ModelAndView processDraftSubmit(@PathVariable String mode, HttpServletReq
if (!mode.equalsIgnoreCase("preview"))
{
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
String draftid = request.getParameter("draftid");
Draft draft = null;
@@ -1401,7 +1412,7 @@ public ModelAndView processDraftSubmit(@PathVariable String mode, HttpServletReq
} else if (mode.equalsIgnoreCase("test")) {
url = serverPrefix + survey.getShortname() + "/management/test?draftid=" + uid;
} else if (mode.equalsIgnoreCase("runner")) {
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
if (survey.getEcasSecurity() && user != null)
{
url = serverPrefix + "runner/" + survey.getUniqueId();
@@ -1459,7 +1470,7 @@ public ModelAndView DraftSubmit(@PathVariable String draftid, HttpServletRequest
String invitationId = draft.getAnswerSet().getInvitationId();
String uniqueCode = draft.getAnswerSet().getUniqueCode();
String lang = draft.getAnswerSet().getLanguageCode();
- String url = answerService.getDraftURL(draft.getAnswerSet(), draftid, sessionService.getCurrentUser(request, false));
+ String url = answerService.getDraftURL(draft.getAnswerSet(), draftid, sessionService.getCurrentUser(request, false, false));
ModelAndView result = new ModelAndView("thanksdraftrunner", "url", url);
@@ -1587,7 +1598,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl
ModelAndView err = testDraftAlreadySubmittedByUniqueCode(origsurvey, uniqueCode, locale);
if (err != null) return err;
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
AnswerSet answerSet = SurveyHelper.parseAnswerSet(request, origsurvey, fileDir, uniqueCode, false, lang, user, fileService);
String newlang = request.getParameter("newlang");
@@ -1959,7 +1970,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl
}
@RequestMapping(value = "/elements/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public @ResponseBody List element(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException {
+ public @ResponseBody List element(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException {
String ids = request.getParameter("ids");
if (ids == null) return null;
@@ -1975,7 +1986,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl
boolean hasGlobalAdminRights = false;
if (foreditor) {
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
if (user != null)
{
hasGlobalAdminRights = user.getGlobalPrivileges().get(GlobalPrivilege.FormManagement) == 2;
diff --git a/src/main/java/com/ec/survey/controller/SettingsController.java b/src/main/java/com/ec/survey/controller/SettingsController.java
index 33e13492d..d58444924 100644
--- a/src/main/java/com/ec/survey/controller/SettingsController.java
+++ b/src/main/java/com/ec/survey/controller/SettingsController.java
@@ -11,6 +11,8 @@
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.Tools;
import com.ec.survey.tools.Ucs2Utf8;
+import com.ec.survey.tools.WeakAuthenticationException;
+
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@@ -50,19 +52,43 @@ public class SettingsController extends BasicController {
@Autowired private LocaleResolver localeResolver;
@RequestMapping(method = {RequestMethod.GET, RequestMethod.HEAD})
- public String root(Locale locale, Model model) {
+ public String root(HttpServletRequest request, Locale locale, Model model) throws NotAgreedToTosException, WeakAuthenticationException {
+ //check user (e.g. weak authentication)
+ sessionService.getCurrentUser(request);
model.addAttribute("languages", surveyService.getLanguages());
return "settings/skin";
}
@RequestMapping(value = "/myAccount", method = {RequestMethod.GET, RequestMethod.HEAD})
- public String myAccount(ModelMap model){
+ public String myAccount(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
model.addAttribute("languages", surveyService.getLanguages());
+
+ String message = request.getParameter("message");
+ if (message != null)
+ {
+ switch(message)
+ {
+ case "password":
+ model.addAttribute("message", resources.getMessage("info.PasswordChanged", null, "The password has been changed", locale));
+ break;
+ case "email":
+ model.addAttribute("message", resources.getMessage("message.NewEmailAddressSend", null, "The email address will be changed after confirmation", locale));
+ break;
+ case "language":
+ User user = sessionService.getCurrentUser(request);
+ model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", new Locale(user.getLanguage())));
+ break;
+ case "pivot":
+ model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", locale));
+ break;
+ }
+ }
+
return "settings/myAccount";
}
@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
- public String changePassword(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{
+ public String changePassword(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
String oldPassword = request.getParameter("oldpassword");
String newPassword = request.getParameter("newpassword");
@@ -103,14 +129,13 @@ public String changePassword(HttpServletRequest request, ModelMap model, Locale
user.setPassword(Tools.hash(newPassword + user.getPasswordSalt()));
administrationService.updateUser(user);
- sessionService.setCurrentUser(request, user);
+ sessionService.setCurrentUser(request, user);
- model.addAttribute("message", resources.getMessage("info.PasswordChanged", null, "The password has been changed", locale));
- return "settings/myAccount";
+ return "redirect:/settings/myAccount?message=password";
}
@RequestMapping(value = "/changeEmail", method = RequestMethod.POST)
- public String changeEmail(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{
+ public String changeEmail(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
String password = request.getParameter("password");
String email = request.getParameter("newemail");
@@ -157,12 +182,11 @@ public String changeEmail(HttpServletRequest request, ModelMap model, Locale loc
return "settings/myAccount";
}
- model.addAttribute("message", resources.getMessage("message.NewEmailAddressSend", null, "The email address will be changed after confirmation", locale));
- return "settings/myAccount";
+ return "redirect:/settings/myAccount?message=email";
}
@RequestMapping(value = "/changeLanguage", method = RequestMethod.POST)
- public String changeLanguage(HttpServletRequest request, HttpServletResponse response, ModelMap model, Locale locale) throws NotAgreedToTosException{
+ public String changeLanguage(HttpServletRequest request, HttpServletResponse response, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
String lang = request.getParameter("change-lang");
User user = sessionService.getCurrentUser(request);
@@ -173,13 +197,12 @@ public String changeLanguage(HttpServletRequest request, HttpServletResponse res
sessionService.setCurrentUser(request, user);
localeResolver.setLocale(request, response, new Locale(user.getLanguage()));
- model.addAttribute("languages", surveyService.getLanguages());
- model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", new Locale(user.getLanguage())));
- return "settings/myAccount";
+
+ return "redirect:/settings/myAccount?message=language";
}
@RequestMapping(value = "/changePivotLanguage", method = RequestMethod.POST)
- public String changePivotLanguage(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{
+ public String changePivotLanguage(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
String lang = request.getParameter("change-lang");
User user = sessionService.getCurrentUser(request);
@@ -188,13 +211,11 @@ public String changePivotLanguage(HttpServletRequest request, ModelMap model, Lo
administrationService.updateUser(user);
sessionService.setCurrentUser(request, user);
- model.addAttribute("languages", surveyService.getLanguages());
- model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", locale));
- return "settings/myAccount";
+ return "redirect:/settings/myAccount?message=pivot";
}
@RequestMapping(value = "/shares")
- public ModelAndView shares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{
+ public ModelAndView shares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
User user = sessionService.getCurrentUser(request);
String delete = request.getParameter("delete");
@@ -230,7 +251,7 @@ public ModelAndView shares(HttpServletRequest request, Locale locale) throws Not
}
@RequestMapping(value = "/shareEdit/{pid}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest request, Locale locale) throws NotAgreedToTosException{
+ public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
int id = Integer.parseInt(pid);
User user = sessionService.getCurrentUser(request);
Share share = attendeeService.getShare(id);
@@ -280,7 +301,7 @@ public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest reque
}
@RequestMapping(value = "/createStaticShare", method = RequestMethod.POST)
- public ModelAndView createShares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{
+ public ModelAndView createShares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
User user = sessionService.getCurrentUser(request);
diff --git a/src/main/java/com/ec/survey/controller/SkinController.java b/src/main/java/com/ec/survey/controller/SkinController.java
index 4fa08e6b1..1817661a4 100644
--- a/src/main/java/com/ec/survey/controller/SkinController.java
+++ b/src/main/java/com/ec/survey/controller/SkinController.java
@@ -12,6 +12,8 @@
import com.ec.survey.tools.FileUtils;
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.Ucs2Utf8;
+import com.ec.survey.tools.WeakAuthenticationException;
+
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Controller;
@@ -51,7 +53,7 @@ public class SkinController extends BasicController {
private SessionFactory sessionFactory;
@RequestMapping(value = "/skin", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{
+ public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{
User user = sessionService.getCurrentUser(request);
List skins = null;
@@ -97,7 +99,7 @@ public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotA
}
@RequestMapping(value = "/skin/new", method = {RequestMethod.GET, RequestMethod.HEAD})
- public String newSkin(Locale locale, Model model, HttpServletRequest request) throws NotAgreedToTosException {
+ public String newSkin(Locale locale, Model model, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false);
Form form = new Form(resources);
@@ -111,7 +113,7 @@ public String newSkin(Locale locale, Model model, HttpServletRequest request) th
}
@RequestMapping(value = "/skin/edit/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false);
@@ -132,7 +134,7 @@ public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServlet
}
@RequestMapping(value = "/skin/delete/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
@@ -156,7 +158,7 @@ public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServl
}
@RequestMapping(value = "/skin/copy/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false);
@@ -185,7 +187,7 @@ public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServlet
}
@RequestMapping(value = "/skin/save", method = RequestMethod.POST)
- public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingresult, HttpServletRequest request, Locale locale) throws NotAgreedToTosException {
+ public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingresult, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Map parameterMap = Ucs2Utf8.requestToHashMap(request);
@@ -261,7 +263,7 @@ public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingres
}
@RequestMapping(value = "/skin/download/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView download(@PathVariable String id, Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException {
+ public ModelAndView download(@PathVariable String id, Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
int skinId = Integer.parseInt(id);
@@ -293,7 +295,7 @@ public ModelAndView download(@PathVariable String id, Locale locale, HttpServlet
}
@RequestMapping(value = "/skin/upload")
- public void upload(Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException {
+ public void upload(Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
String error = resources.getMessage("error.FileImportFailed", null, "The file could not be imported.", locale);
diff --git a/src/main/java/com/ec/survey/controller/SurveyController.java b/src/main/java/com/ec/survey/controller/SurveyController.java
index ae9bc2aa7..ef5c6e7f4 100644
--- a/src/main/java/com/ec/survey/controller/SurveyController.java
+++ b/src/main/java/com/ec/survey/controller/SurveyController.java
@@ -92,7 +92,7 @@ public ModelAndView surveys(HttpServletRequest request) throws NumberFormatExcep
paging.moveTo(newPage);
SqlPagination sqlPagination = paginationMapper.toSqlPagination(paging);
- List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false);
+ List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, true);
surveyService.generateAccessInformation(surveys, user);
@@ -146,7 +146,7 @@ public ModelAndView surveys(HttpServletRequest request) throws NumberFormatExcep
SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lastSurveyFilter");
SqlPagination sqlPagination = new SqlPagination(newPage, itemsPerPage);
- List result = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false);
+ List result = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, true);
surveyService.generateAccessInformation(result, sessionService.getCurrentUser(request));
diff --git a/src/main/java/com/ec/survey/controller/SurveySearchController.java b/src/main/java/com/ec/survey/controller/SurveySearchController.java
index 53b4d6eba..a5f8bf935 100644
--- a/src/main/java/com/ec/survey/controller/SurveySearchController.java
+++ b/src/main/java/com/ec/survey/controller/SurveySearchController.java
@@ -18,6 +18,7 @@
import com.ec.survey.tools.ConversionTools;
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.RestoreExecutor;
+import com.ec.survey.tools.WeakAuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@@ -64,10 +65,8 @@ public class SurveySearchController extends BasicController {
@RequestMapping(value = "/administration/surveysearch", method = {RequestMethod.GET, RequestMethod.HEAD})
public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale locale) {
- ModelAndView result = new ModelAndView("administration/surveysearch");
-
- SurveyFilter sfilter = new SurveyFilter();
-
+ ModelAndView result = new ModelAndView("administration/surveysearch");
+ SurveyFilter sfilter = new SurveyFilter();
result.addObject("archivedfilter", new ArchiveFilter());
@@ -82,6 +81,28 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale
result.addObject("deletedfilter", new DeletedSurveysFilter());
}
+ if (request.getParameter("reported") != null)
+ {
+ result.addObject("reported", true);
+ SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstreportedfilter");
+ if (filter == null) filter = new SurveyFilter();
+ result.addObject("reportedfilter", filter);
+ result.addObject("mode", "reported");
+ } else {
+ result.addObject("reportedfilter", new SurveyFilter());
+ }
+
+ if (request.getParameter("frozen") != null)
+ {
+ result.addObject("frozen", true);
+ SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstfrozenfilter");
+ if (filter == null) filter = new SurveyFilter();
+ result.addObject("frozenfilter", filter);
+ result.addObject("mode", "frozen");
+ } else {
+ result.addObject("frozenfilter", new SurveyFilter());
+ }
+
if (request.getParameter("normaldeleted") != null)
{
String shortname = request.getParameter("normaldeleted");
@@ -102,6 +123,28 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale
}
}
+ if (request.getParameter("frozen") != null)
+ {
+ try {
+ result.addObject("frozen", true);
+ sfilter = (SurveyFilter) request.getSession().getAttribute("surveysearchfilter");
+ result.addObject("mode", "existing");
+ } catch (Exception e){
+ //ignore
+ }
+ }
+
+ if (request.getParameter("unfrozen") != null)
+ {
+ try {
+ result.addObject("unfrozen", true);
+ sfilter = (SurveyFilter) request.getSession().getAttribute("surveysearchfilter");
+ result.addObject("mode", "existing");
+ } catch (Exception e){
+ //ignore
+ }
+ }
+
result.addObject("filter", sfilter);
List domains = ldapDBService.getDomains(true, true, resources, locale);
@@ -111,11 +154,13 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale
}
@RequestMapping(value = "/administration/surveysearch", method = {RequestMethod.POST})
- public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException {
+ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
String mode = request.getParameter("surveys");
SurveyFilter filter = new SurveyFilter();
+ SurveyFilter reportedFilter = new SurveyFilter();
+ SurveyFilter frozenFilter = new SurveyFilter();
ArchiveFilter archivedFilter = new ArchiveFilter();
DeletedSurveysFilter deletedSurveysFilter = new DeletedSurveysFilter();
@@ -141,6 +186,30 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo
deletedSurveysFilter.setDeletedTo(ConversionTools.getDate(request.getParameter("deleteddeletedTo")));
request.getSession().setAttribute("lstdeletedfilter", deletedSurveysFilter);
+ } else if (mode.equalsIgnoreCase("reported"))
+ {
+ reportedFilter.setUser(sessionService.getCurrentUser(request));
+ reportedFilter.setShortname(request.getParameter("reportedshortname"));
+ reportedFilter.setUid(request.getParameter("reporteduid"));
+ reportedFilter.setTitle(request.getParameter("reportedtitle"));
+ reportedFilter.setOwner(request.getParameter("reportedowner"));
+ reportedFilter.setPublishedFrom(ConversionTools.getDate(request.getParameter("reportedpublishedFrom")));
+ reportedFilter.setPublishedTo(ConversionTools.getDate(request.getParameter("reportedpublishedTo")));
+ reportedFilter.setFirstPublishedFrom(ConversionTools.getDate(request.getParameter("reportedfirstPublishedFrom")));
+ reportedFilter.setFirstPublishedTo(ConversionTools.getDate(request.getParameter("reportedfirstPublishedTo")));
+ request.getSession().setAttribute("lstreportedfilter", reportedFilter);
+ } else if (mode.equalsIgnoreCase("frozen"))
+ {
+ frozenFilter.setUser(sessionService.getCurrentUser(request));
+ frozenFilter.setShortname(request.getParameter("frozenshortname"));
+ frozenFilter.setUid(request.getParameter("frozenuid"));
+ frozenFilter.setTitle(request.getParameter("frozentitle"));
+ frozenFilter.setOwner(request.getParameter("frozenowner"));
+ frozenFilter.setPublishedFrom(ConversionTools.getDate(request.getParameter("frozenpublishedFrom")));
+ frozenFilter.setPublishedTo(ConversionTools.getDate(request.getParameter("frozenpublishedTo")));
+ frozenFilter.setFirstPublishedFrom(ConversionTools.getDate(request.getParameter("frozenfirstPublishedFrom")));
+ frozenFilter.setFirstPublishedTo(ConversionTools.getDate(request.getParameter("frozenfirstPublishedTo")));
+ request.getSession().setAttribute("lstfrozenfilter", frozenFilter);
} else {
filter.setUser(sessionService.getCurrentUser(request));
filter.setShortname(request.getParameter("shortname"));
@@ -159,6 +228,8 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo
result.addObject("filter", filter);
result.addObject("archivedfilter", archivedFilter);
result.addObject("deletedfilter", deletedSurveysFilter);
+ result.addObject("reportedfilter", reportedFilter);
+ result.addObject("frozenfilter", frozenFilter);
List domains = ldapDBService.getDomains(true, true, resources, locale);
result.addObject("domains", domains);
@@ -166,6 +237,35 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo
return result;
}
+ @RequestMapping(value = "/administration/freezesurvey", method = {RequestMethod.POST})
+ public ModelAndView freezesurvey(HttpServletRequest request, Model model, Locale locale) throws Exception {
+ String surveyId = request.getParameter("surveyId");
+ String emailText = request.getParameter("emailText");
+
+ if (surveyId == null || surveyId.length() == 0 || emailText == null || emailText.length() == 0)
+ {
+ throw new Exception("invalid parameters");
+ }
+
+ surveyService.freeze(surveyId, emailText);
+
+ return new ModelAndView("redirect:/administration/surveysearch?frozen=1");
+ }
+
+ @RequestMapping(value = "/administration/unfreezesurvey", method = {RequestMethod.POST})
+ public ModelAndView unfreezesurvey(HttpServletRequest request, Model model, Locale locale) throws Exception {
+ String surveyId = request.getParameter("surveyId");
+
+ if (surveyId == null || surveyId.length() == 0)
+ {
+ throw new Exception("invalid parameters");
+ }
+
+ surveyService.unfreeze(surveyId);
+
+ return new ModelAndView("redirect:/administration/surveysearch?unfrozen=1");
+ }
+
@RequestMapping(value = "/administration/surveysearchJSON", method = {RequestMethod.GET, RequestMethod.HEAD})
public @ResponseBody List resultsJSON(HttpServletRequest request) {
@@ -269,8 +369,76 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo
return surveys;
}
+ @RequestMapping(value = "/administration/reportedsurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD})
+ public @ResponseBody List reportedsurveysjson(HttpServletRequest request) throws Exception {
+ try {
+
+ String rows = request.getParameter("rows");
+ if (rows == null) return null;
+ String page = request.getParameter("page");
+ if (page == null) return null;
+
+ SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstreportedfilter");
+ if (filter == null) return null;
+
+ filter.setSurveys("REPORTED");
+
+ SqlPagination sqlPagination = new SqlPagination(Integer.parseInt(page), Integer.parseInt(rows));
+ List surveys = surveyService.getSurveysIncludingPublicationDates(filter, sqlPagination);
+
+ for (Survey survey: surveys)
+ {
+ survey.setTitle(survey.cleanTitle());
+ survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId()));
+ survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId()));
+ }
+
+ return surveys;
+ }
+ catch (Exception e)
+ {
+ logger.error(e.getLocalizedMessage(), e);
+ }
+
+ return null;
+ }
+
+ @RequestMapping(value = "/administration/frozensurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD})
+ public @ResponseBody List frozensurveysjson(HttpServletRequest request) throws Exception {
+ try {
+
+ String rows = request.getParameter("rows");
+ if (rows == null) return null;
+ String page = request.getParameter("page");
+ if (page == null) return null;
+
+ SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstfrozenfilter");
+ if (filter == null) return null;
+
+ filter.setSurveys("FROZEN");
+
+ SqlPagination sqlPagination = new SqlPagination(Integer.parseInt(page), Integer.parseInt(rows));
+ List surveys = surveyService.getSurveysIncludingPublicationDates(filter, sqlPagination);
+
+ for (Survey survey: surveys)
+ {
+ survey.setTitle(survey.cleanTitle());
+ survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId()));
+ survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId()));
+ }
+
+ return surveys;
+ }
+ catch (Exception e)
+ {
+ logger.error(e.getLocalizedMessage(), e);
+ }
+
+ return null;
+ }
+
@RequestMapping(value = "/administration/changeowner", method = {RequestMethod.POST})
- public @ResponseBody boolean changeowner(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException {
+ public @ResponseBody boolean changeowner(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
User u = sessionService.getCurrentUser(request);
if (u.getGlobalPrivileges().get(GlobalPrivilege.SystemManagement) < 2)
diff --git a/src/main/java/com/ec/survey/controller/SystemController.java b/src/main/java/com/ec/survey/controller/SystemController.java
index f5d8f83ed..4176720b6 100644
--- a/src/main/java/com/ec/survey/controller/SystemController.java
+++ b/src/main/java/com/ec/survey/controller/SystemController.java
@@ -6,10 +6,14 @@
import com.ec.survey.model.administration.ComplexityParameters;
import com.ec.survey.model.administration.GlobalPrivilege;
import com.ec.survey.model.administration.User;
+import com.ec.survey.service.MailService;
import com.ec.survey.service.SessionService;
import com.ec.survey.service.SettingsService;
import com.ec.survey.service.SystemService;
import com.ec.survey.tools.NotAgreedToTosException;
+import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
+
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -40,7 +44,7 @@ public class SystemController extends BasicController {
private SettingsService settingsService;
@RequestMapping(value = "/message", method = {RequestMethod.GET, RequestMethod.HEAD})
- public @ResponseBody Message getSystemMessage(HttpServletRequest request) throws NotAgreedToTosException {
+ public @ResponseBody Message getSystemMessage(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
User user = sessionService.getCurrentUser(request);
Message message;
@@ -79,7 +83,7 @@ public class SystemController extends BasicController {
}
@RequestMapping(value = "/deletemessage", method = {RequestMethod.GET, RequestMethod.HEAD})
- public @ResponseBody String deleteMessage(HttpServletRequest request) throws NotAgreedToTosException
+ public @ResponseBody String deleteMessage(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException
{
User user = sessionService.getCurrentUser(request);
String sid = request.getParameter("id");
@@ -94,16 +98,16 @@ public class SystemController extends BasicController {
}
@RequestMapping(value = "/messages/runner", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView getSystemMessagesRunner(HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView getSystemMessagesRunner(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
return getSystemMessages(request, true);
}
@RequestMapping(value = "/messages", method = {RequestMethod.GET, RequestMethod.HEAD})
- public ModelAndView getSystemMessages(HttpServletRequest request) throws NotAgreedToTosException {
+ public ModelAndView getSystemMessages(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
return getSystemMessages(request, false);
}
- private ModelAndView getSystemMessages(HttpServletRequest request, boolean runnermode) throws NotAgreedToTosException {
+ private ModelAndView getSystemMessages(HttpServletRequest request, boolean runnermode) throws NotAgreedToTosException, WeakAuthenticationException {
Message message = systemService.getMessage();
User user = sessionService.getCurrentUser(request);
@@ -146,10 +150,197 @@ public ModelAndView system(HttpServletRequest request, Model model) {
complexityParameterList.put(cp.getKey(), settingsService.get(cp.getKey()));
}
m.addObject("complexityParameters", complexityParameterList);
+
+ m.addObject("reportMaxNumber", settingsService.get(Setting.MaxReports));
+ m.addObject("reportMessageText", settingsService.get(Setting.ReportText));
+ m.addObject("reportRecipients", settingsService.get(Setting.ReportRecipients));
+
+ m.addObject("banUserMessageText", settingsService.get(Setting.FreezeUserTextAdminBan));
+ m.addObject("unbanUserMessageText", settingsService.get(Setting.FreezeUserTextAdminUnban));
+ m.addObject("bannedUserRecipients", settingsService.get(Setting.BannedUserRecipients));
+
+ m.addObject("bannedUserMessageText", settingsService.get(Setting.FreezeUserTextBan));
+ m.addObject("unbannedUserMessageText", settingsService.get(Setting.FreezeUserTextUnban));
+
+ m.addObject("trustIndicatorCreatorInternal", settingsService.get(Setting.TrustValueCreatorInternal));
+ m.addObject("trustIndicatorMinimumPassMark", settingsService.get(Setting.TrustValueMinimumPassMark));
+ m.addObject("trustIndicatorPastSurveys", settingsService.get(Setting.TrustValuePastSurveys));
+ m.addObject("trustIndicatorPrivilegedUser", settingsService.get(Setting.TrustValuePrivilegedUser));
+ m.addObject("trustIndicatorNbContributions", settingsService.get(Setting.TrustValueNbContributions));
return m;
}
+ @RequestMapping(value ="/configureBanUsers", method = RequestMethod.POST)
+ public ModelAndView configureBanUsers( HttpServletRequest request, Locale locale) throws Exception {
+ String banUserMessageText = request.getParameter("banUserMessageText");
+
+ if (banUserMessageText == null || banUserMessageText.length() == 0)
+ {
+ throw new Exception("banUserMessageText must not be empty");
+ }
+
+ String unbanUserMessageText = request.getParameter("unbanUserMessageText");
+
+ if (unbanUserMessageText == null || unbanUserMessageText.length() == 0)
+ {
+ throw new Exception("unbanUserMessageText must not be empty");
+ }
+
+ String bannedUserMessageText = request.getParameter("bannedUserMessageText");
+
+ if (bannedUserMessageText == null || bannedUserMessageText.length() == 0)
+ {
+ throw new Exception("bannedUserMessageText must not be empty");
+ }
+
+ String unbannedUserMessageText = request.getParameter("unbannedUserMessageText");
+
+ if (unbannedUserMessageText == null || unbannedUserMessageText.length() == 0)
+ {
+ throw new Exception("unbannedUserMessageText must not be empty");
+ }
+
+ String[] emails = request.getParameterValues("messageEmail");
+ String recipients = "";
+ if (emails != null)
+ {
+ for (String email : emails) {
+ if (email.trim().length() > 0)
+ {
+ if (!MailService.isValidEmailAddress(email))
+ {
+ throw new Exception("invalid email address:" + email);
+ }
+
+ if (recipients.length() > 0)
+ {
+ recipients += ";";
+ }
+ recipients += email;
+ }
+ }
+ }
+
+ settingsService.update(Setting.BannedUserRecipients, recipients);
+ settingsService.update(Setting.FreezeUserTextAdminBan, banUserMessageText);
+ settingsService.update(Setting.FreezeUserTextAdminUnban, unbanUserMessageText);
+ settingsService.update(Setting.FreezeUserTextBan, bannedUserMessageText);
+ settingsService.update(Setting.FreezeUserTextUnban, unbannedUserMessageText);
+
+ return new ModelAndView("redirect:/administration/system");
+ }
+
+ @RequestMapping(value ="/configureTrustIndicator", method = RequestMethod.POST)
+ public ModelAndView configureTrustIndicator( HttpServletRequest request, Locale locale) throws Exception {
+ String trustIndicatorCreatorInternal = request.getParameter("trustIndicatorCreatorInternal");
+
+ if (trustIndicatorCreatorInternal == null || trustIndicatorCreatorInternal.length() == 0)
+ {
+ throw new Exception("trustIndicatorCreatorInternal must not be empty");
+ }
+ if (!Tools.isInteger(trustIndicatorCreatorInternal))
+ {
+ throw new Exception("trustIndicatorCreatorInternal must be an integer");
+ }
+
+ String trustIndicatorMinimumPassMark = request.getParameter("trustIndicatorMinimumPassMark");
+
+ if (trustIndicatorMinimumPassMark == null || trustIndicatorMinimumPassMark.length() == 0)
+ {
+ throw new Exception("trustIndicatorMinimumPassMark must not be empty");
+ }
+ if (!Tools.isInteger(trustIndicatorMinimumPassMark))
+ {
+ throw new Exception("trustIndicatorMinimumPassMark must be an integer");
+ }
+
+ String trustIndicatorPastSurveys = request.getParameter("trustIndicatorPastSurveys");
+
+ if (trustIndicatorPastSurveys == null || trustIndicatorPastSurveys.length() == 0)
+ {
+ throw new Exception("trustIndicatorPastSurveys must not be empty");
+ }
+ if (!Tools.isInteger(trustIndicatorPastSurveys))
+ {
+ throw new Exception("trustIndicatorPastSurveys must be an integer");
+ }
+
+ String trustIndicatorPrivilegedUser = request.getParameter("trustIndicatorPrivilegedUser");
+
+ if (trustIndicatorPrivilegedUser == null || trustIndicatorPrivilegedUser.length() == 0)
+ {
+ throw new Exception("trustIndicatorPrivilegedUser must not be empty");
+ }
+ if (!Tools.isInteger(trustIndicatorPrivilegedUser))
+ {
+ throw new Exception("trustIndicatorPrivilegedUser must be an integer");
+ }
+
+ String trustIndicatorNbContributions = request.getParameter("trustIndicatorNbContributions");
+
+ if (trustIndicatorNbContributions == null || trustIndicatorNbContributions.length() == 0)
+ {
+ throw new Exception("trustIndicatorNbContributions must not be empty");
+ }
+ if (!Tools.isInteger(trustIndicatorNbContributions))
+ {
+ throw new Exception("trustIndicatorNbContributions must be an integer");
+ }
+
+ settingsService.update(Setting.TrustValueCreatorInternal, trustIndicatorCreatorInternal);
+ settingsService.update(Setting.TrustValuePastSurveys, trustIndicatorPastSurveys);
+ settingsService.update(Setting.TrustValuePrivilegedUser, trustIndicatorPrivilegedUser);
+ settingsService.update(Setting.TrustValueMinimumPassMark, trustIndicatorMinimumPassMark);
+ settingsService.update(Setting.TrustValueNbContributions, trustIndicatorNbContributions);
+
+ return new ModelAndView("redirect:/administration/system");
+ }
+
+ @RequestMapping(value ="/configureReports", method = RequestMethod.POST)
+ public ModelAndView configureReports( HttpServletRequest request, Locale locale) throws Exception {
+ String number = request.getParameter("maxNumber");
+
+ if (number == null || !Tools.isInteger(number))
+ {
+ throw new Exception("Invalid number");
+ }
+
+ String text = request.getParameter("messageText");
+
+ if (text == null || text.length() == 0)
+ {
+ throw new Exception("text must not be empty");
+ }
+
+ String[] emails = request.getParameterValues("messageEmail");
+ String recipients = "";
+ if (emails != null)
+ {
+ for (String email : emails) {
+ if (email.trim().length() > 0)
+ {
+ if (!MailService.isValidEmailAddress(email))
+ {
+ throw new Exception("invalid email address:" + email);
+ }
+
+ if (recipients.length() > 0)
+ {
+ recipients += ";";
+ }
+ recipients += email;
+ }
+ }
+ }
+
+ settingsService.update(Setting.MaxReports, number);
+ settingsService.update(Setting.ReportText, text);
+ settingsService.update(Setting.ReportRecipients, recipients);
+
+ return new ModelAndView("redirect:/administration/system");
+ }
+
@RequestMapping(value ="/configureLogging", method = RequestMethod.POST)
public ModelAndView configureLogging(@RequestParam("enabled") String enabled, HttpServletRequest request, Locale locale) {
settingsService.update(Setting.ActivityLoggingEnabled, enabled);
diff --git a/src/main/java/com/ec/survey/controller/TranslationController.java b/src/main/java/com/ec/survey/controller/TranslationController.java
index 39473a03d..e4a90a2ef 100644
--- a/src/main/java/com/ec/survey/controller/TranslationController.java
+++ b/src/main/java/com/ec/survey/controller/TranslationController.java
@@ -398,7 +398,7 @@ public void deletetranslations(HttpServletRequest request, Locale locale, HttpSe
}
@RequestMapping(value = "/translatetranslations", method = RequestMethod.GET)
- public void translateTranslations(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NotAgreedToTosException, ForbiddenURLException {
+ public void translateTranslations(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException {
String idsString = request.getParameter("translationIds");
String[] ids = idsString.split("\\|");
User user = sessionService.getCurrentUser(request);
@@ -454,7 +454,7 @@ public void cancelTranslation(HttpServletRequest request, Locale locale, HttpSer
}
@RequestMapping(value = "/activatetranslation", method = RequestMethod.POST)
- public @ResponseBody SimpleResult activatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException {
+ public @ResponseBody SimpleResult activatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
String id = request.getParameter("id");
SimpleResult result = new SimpleResult();
@@ -484,7 +484,7 @@ public void cancelTranslation(HttpServletRequest request, Locale locale, HttpSer
}
@RequestMapping(value = "/deactivatetranslation", method = RequestMethod.POST)
- public @ResponseBody SimpleResult deactivatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException {
+ public @ResponseBody SimpleResult deactivatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException {
String id = request.getParameter("id");
SimpleResult result = new SimpleResult();
@@ -824,7 +824,7 @@ public ModelAndView addtranslations(@PathVariable String shortname, HttpServletR
}
@RequestMapping(value = "/importtranslation", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
- public @ResponseBody String importtranslation(@PathVariable String shortname, HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException, NotAgreedToTosException, ForbiddenURLException {
+ public @ResponseBody String importtranslation(@PathVariable String shortname, HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException, NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException {
ImportTranslationResult result = new ImportTranslationResult();
ObjectMapper mapper = new ObjectMapper();
diff --git a/src/main/java/com/ec/survey/controller/UserController.java b/src/main/java/com/ec/survey/controller/UserController.java
index 7c0bf7e84..5f81c7054 100644
--- a/src/main/java/com/ec/survey/controller/UserController.java
+++ b/src/main/java/com/ec/survey/controller/UserController.java
@@ -1,6 +1,7 @@
package com.ec.survey.controller;
import com.ec.survey.model.Paging;
+import com.ec.survey.model.Setting;
import com.ec.survey.model.SqlPagination;
import com.ec.survey.model.UserFilter;
import com.ec.survey.model.UsersConfiguration;
@@ -79,7 +80,36 @@ public ModelAndView users(HttpServletRequest request, Model model) throws Except
if (usersConfiguration == null) usersConfiguration = new UsersConfiguration();
m.addObject("usersConfiguration", usersConfiguration);
- return m;
+ m.addObject("freezeusertext", settingsService.get(Setting.FreezeUserTextBan));
+ m.addObject("unfreezeusertext", settingsService.get(Setting.FreezeUserTextUnban));
+
+ return m;
+ }
+
+ @RequestMapping(value = "/banuser", method = RequestMethod.POST)
+ public ModelAndView banuser(@RequestParam("userId") String userId, @RequestParam("emailText") String emailText, HttpServletRequest request, Model model) throws Exception {
+
+ if (userId == null || userId.length() == 0 || emailText == null || emailText.length() == 0)
+ {
+ throw new Exception("invalid input data");
+ }
+
+ administrationService.banUser(userId, emailText);
+
+ return new ModelAndView("redirect:/administration/users?frozen=1");
+ }
+
+ @RequestMapping(value = "/unbanuser", method = RequestMethod.POST)
+ public ModelAndView unbanuser(@RequestParam("userId") String userId, HttpServletRequest request, Model model) throws Exception {
+
+ if (userId == null || userId.length() == 0)
+ {
+ throw new Exception("invalid input data");
+ }
+
+ administrationService.unbanUser(userId);
+
+ return new ModelAndView("redirect:/administration/users?unfrozen=1");
}
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
@@ -100,7 +130,7 @@ public ModelAndView createUser(@RequestParam("add-login") String login, @Request
if (Tools.isPasswordWeak(password))
{
model.addAttribute("error", resources.getMessage("error.PasswordWeak", null, "This password does not fit our password policy. Please choose a password between 8 and 16 characters with at least one digit and one non-alphanumeric characters (e.g. !?$&%...).", locale));
- } else {
+ } else {
User user = new User();
user.setValidated(true);
user.setLogin(login);
@@ -114,19 +144,24 @@ public ModelAndView createUser(@RequestParam("add-login") String login, @Request
user.setLanguage(language);
user.setType(User.SYSTEM);
- if (roles != null && roles.length() > 0)
+ if (!administrationService.checkEmailsNotBanned(user.getAllEmailAddresses()))
{
- String[] ids = roles.split(";");
- Map rolesById = administrationService.getAllRolesAsMap();
- for (String id : ids) {
- if (rolesById.containsKey(Integer.parseInt(id)))
- {
- user.getRoles().add(rolesById.get(Integer.parseInt(id)));
- }
- }
+ model.addAttribute("error", resources.getMessage("error.EmailBanned", null, "This email adress belongs to a banned user.", locale));
+ } else {
+ if (roles != null && roles.length() > 0)
+ {
+ String[] ids = roles.split(";");
+ Map rolesById = administrationService.getAllRolesAsMap();
+ for (String id : ids) {
+ if (rolesById.containsKey(Integer.parseInt(id)))
+ {
+ user.getRoles().add(rolesById.get(Integer.parseInt(id)));
+ }
+ }
+ }
+
+ administrationService.createUser(user);
}
-
- administrationService.createUser(user);
}
} else {
model.addAttribute("error", resources.getMessage("error.LoginExists", null, "This login already exists. Please choose a unique login.", locale));
@@ -201,5 +236,5 @@ public ModelAndView deleteUser(@RequestParam("id") String id, HttpServletRequest
}
return users(request, model);
}
-
+
}
diff --git a/src/main/java/com/ec/survey/exception/FrozenSurveyException.java b/src/main/java/com/ec/survey/exception/FrozenSurveyException.java
new file mode 100644
index 000000000..a998a6d8f
--- /dev/null
+++ b/src/main/java/com/ec/survey/exception/FrozenSurveyException.java
@@ -0,0 +1,11 @@
+package com.ec.survey.exception;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ResponseStatus;
+
+@ResponseStatus(value = HttpStatus.NOT_FOUND)
+public class FrozenSurveyException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+
+}
diff --git a/src/main/java/com/ec/survey/model/Abuse.java b/src/main/java/com/ec/survey/model/Abuse.java
new file mode 100644
index 000000000..5cb9cb6d9
--- /dev/null
+++ b/src/main/java/com/ec/survey/model/Abuse.java
@@ -0,0 +1,93 @@
+package com.ec.survey.model;
+
+import org.apache.log4j.Logger;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import com.ec.survey.tools.ConversionTools;
+
+import java.util.Date;
+
+import javax.persistence.*;
+
+/**
+ * Represents a abuse information for
+ * a survey
+ */
+@Entity
+@Table(name = "SURABUSE", indexes = {@Index(name="IDX_SURABUSE",columnList = "SURABUSE_SURVEY, SURABUSE_DATE")})
+@Cacheable
+@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
+public class Abuse {
+
+ private int id;
+ private String surveyUid;
+ private String type;
+ private String text;
+ private String email;
+ private Date created;
+
+ protected static final Logger logger = Logger.getLogger(Abuse.class);
+
+ public Abuse(String surveyUid, String type, String text, String email)
+ {
+ this.surveyUid = surveyUid;
+ this.type = type;
+ this.text = text;
+ this.email = email;
+ this.created = new Date();
+ }
+
+ @Id
+ @Column(name = "SURABUSE_ID")
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern=ConversionTools.DateTimeFormat)
+ @Column(name = "SURABUSE_DATE")
+ public Date getCreated() {
+ return created;
+ }
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ @Column(name = "SURABUSE_SURVEY")
+ public String getSurveyUid() {
+ return surveyUid;
+ }
+ public void setSurveyUid(String surveyUid) {
+ this.surveyUid = surveyUid;
+ }
+
+ @Column(name = "SURABUSE_TYPE")
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ @Column(name = "SURABUSE_TEXT")
+ public String getText() {
+ return text;
+ }
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ @Column(name = "SURABUSE_EMAIL")
+ public String getEmail() {
+ return email;
+ }
+ public void setEmail(String email) {
+ this.email = email;
+ }
+}
diff --git a/src/main/java/com/ec/survey/model/Setting.java b/src/main/java/com/ec/survey/model/Setting.java
index 50fbd4a31..212f284bf 100644
--- a/src/main/java/com/ec/survey/model/Setting.java
+++ b/src/main/java/com/ec/survey/model/Setting.java
@@ -38,7 +38,24 @@ public class Setting {
public final static String ReportingMigrationStart = "ReportingMigrationStart";
public final static String ReportingMigrationTime = "ReportingMigrationTime";
public final static String ReportingMigrationSurveyToMigrate = "ReportingMigrationSurveyToMigrate";
-
+
+ public final static String WeakAuthenticationDisabled = "WeakAuthenticationDisabled";
+ public final static String MaxReports = "MaxReports";
+ public final static String ReportText = "ReportText";
+ public final static String ReportRecipients = "ReportRecipients";
+
+ public final static String FreezeUserTextAdminBan = "FreezeUserTextAdminBan";
+ public final static String FreezeUserTextAdminUnban = "FreezeUserTextAdminUnban";
+ public final static String FreezeUserTextBan = "FreezeUserTextBan";
+ public final static String FreezeUserTextUnban = "FreezeUserTextUnban";
+ public final static String BannedUserRecipients = "BannedUserRecipients";
+
+ public final static String TrustValueCreatorInternal = "TrustValueCreatorInternal";
+ public final static String TrustValuePastSurveys = "TrustValuePastSurveys";
+ public final static String TrustValuePrivilegedUser = "TrustValuePrivilegedUser";
+ public final static String TrustValueNbContributions = "TrustValueNbContributions";
+ public final static String TrustValueMinimumPassMark = "TrustValueMinimumPassMark";
+
@Id
@Column(name = "SETTINGS_ID")
@GeneratedValue
diff --git a/src/main/java/com/ec/survey/model/UserFilter.java b/src/main/java/com/ec/survey/model/UserFilter.java
index ec9ef4d86..419eef37d 100644
--- a/src/main/java/com/ec/survey/model/UserFilter.java
+++ b/src/main/java/com/ec/survey/model/UserFilter.java
@@ -4,6 +4,8 @@ public class UserFilter {
private String login;
private String email;
private String comment;
+ private Boolean banned;
+ private Boolean unbanned;
private Boolean ECAS;
private Boolean system;
private Boolean ECASaccess;
@@ -115,4 +117,17 @@ public Boolean getNoECaccess() {
public void setNoECaccess(Boolean noECaccess) {
NoECaccess = noECaccess;
}
+
+ public Boolean getBanned() {
+ return banned;
+ }
+ public void setBanned(Boolean banned) {
+ this.banned = banned;
+ }
+ public Boolean getUnbanned() {
+ return this.unbanned;
+ }
+ public void setUnbanned(Boolean unbanned) {
+ this.unbanned = unbanned;
+ }
}
diff --git a/src/main/java/com/ec/survey/model/UsersConfiguration.java b/src/main/java/com/ec/survey/model/UsersConfiguration.java
index 5b4f5dcfb..e2bc5b034 100644
--- a/src/main/java/com/ec/survey/model/UsersConfiguration.java
+++ b/src/main/java/com/ec/survey/model/UsersConfiguration.java
@@ -25,6 +25,7 @@ public class UsersConfiguration implements java.io.Serializable {
private boolean showLanguage = true;
private boolean showRoles = false;
private boolean showComment = false;
+ private boolean showBanned = true;
@Id
@Column(name = "UC_ID")
@@ -92,4 +93,12 @@ public void setShowComment(boolean showComment) {
this.showComment = showComment;
}
+ @Column(name = "UC_BANNED")
+ public boolean getShowBanned() {
+ return showBanned;
+ }
+ public void setShowBanned(Boolean showBanned) {
+ this.showBanned = showBanned != null ? showBanned : true;
+ }
+
}
diff --git a/src/main/java/com/ec/survey/model/administration/User.java b/src/main/java/com/ec/survey/model/administration/User.java
index 17b0bfce0..2c3ccb9ea 100644
--- a/src/main/java/com/ec/survey/model/administration/User.java
+++ b/src/main/java/com/ec/survey/model/administration/User.java
@@ -49,6 +49,7 @@ public class User implements java.io.Serializable {
private boolean agreedToToS;
private Integer lastEditedSurvey;
private boolean canCreateSurveys = true;
+ private boolean isFrozen = false;
public static final String ECAS = "ECAS";
public static final String SYSTEM = "SYSTEM";
@@ -290,6 +291,14 @@ public void setLastEditedSurvey(Integer lastEditedSurvey) {
this.lastEditedSurvey = lastEditedSurvey;
}
+ @Column(name = "USER_FROZEN")
+ public boolean isFrozen() {
+ return isFrozen;
+ }
+ public void setFrozen(Boolean isFrozen) {
+ this.isFrozen = isFrozen != null ? isFrozen : false;
+ }
+
@Transient
public String getName()
{
@@ -442,7 +451,7 @@ public boolean isCanCreateSurveys() {
public void setCanCreateSurveys(boolean canCreateSurveys) {
this.canCreateSurveys = canCreateSurveys;
}
-
+
@Transient
public List getAllEmailAddresses() {
List result = new ArrayList();
diff --git a/src/main/java/com/ec/survey/model/survey/Survey.java b/src/main/java/com/ec/survey/model/survey/Survey.java
index 19afe7dd9..0477a37d4 100644
--- a/src/main/java/com/ec/survey/model/survey/Survey.java
+++ b/src/main/java/com/ec/survey/model/survey/Survey.java
@@ -91,6 +91,7 @@ public class Survey implements java.io.Serializable {
private int numberOfDrafts;
private int numberOfInvitations;
private int numberOfAnswerSetsPublished;
+ private int numberOfReports;
private int compulsoryStyle;
private boolean isActive; // true if the survey is accessible on the web, isActive is valid for draft and survey objects
private boolean isDraft;
@@ -121,6 +122,7 @@ public class Survey implements java.io.Serializable {
private boolean wcagCompliance;
private boolean isArchived;
private Boolean isDeleted;
+ private Boolean isFrozen;
private boolean ecasSecurity;
private String ecasMode;
private Boolean logoInInfo;
@@ -138,6 +140,7 @@ public class Survey implements java.io.Serializable {
private boolean accessResultsRights = true;
private Integer allowedContributionsPerUser = 1;
private boolean canCreateSurveys = true;
+ private Integer trustScore;
@Id
@Column(name = "SURVEY_ID", nullable = false)
@@ -1126,6 +1129,14 @@ public void setNumberOfAnswerSetsPublished(int numberOfAnswerSetsPublished) {
this.numberOfAnswerSetsPublished = numberOfAnswerSetsPublished;
}
+ @Transient
+ public int getNumberOfReports() {
+ return numberOfReports;
+ }
+ public void setNumberOfReports(int numberOfReports) {
+ this.numberOfReports = numberOfReports;
+ }
+
//this property is not used anymore but has to stay because of backward compatibility
@Column(name = "COMPULSORYSTYLE")
public Integer getCompulsoryStyle() {
@@ -1154,6 +1165,14 @@ public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted != null ? isDeleted : false;
}
+ @Column(name = "FROZEN")
+ public Boolean getIsFrozen() {
+ return isFrozen != null ? isFrozen : false;
+ }
+ public void setIsFrozen(Boolean isFrozen) {
+ this.isFrozen = isFrozen != null ? isFrozen : false;
+ }
+
@Column(name = "ECASSEC")
public Boolean getEcasSecurity() {
return ecasSecurity;
@@ -1260,6 +1279,14 @@ public void setAllowedContributionsPerUser(Integer allowedContributionsPerUser)
this.allowedContributionsPerUser = allowedContributionsPerUser;
}
+ @Column(name = "TRUSTSCORE")
+ public Integer getTrustScore() {
+ return trustScore;
+ }
+ public void setTrustScore(Integer trustScore) {
+ this.trustScore = trustScore;
+ }
+
@Transient
public String serialize(boolean elementOrderOnly) {
StringBuilder result = new StringBuilder();
@@ -2104,13 +2131,11 @@ public void setAccessResultsRights(boolean accessResultsRights) {
this.accessResultsRights = accessResultsRights;
}
-
@Transient
public boolean isCanCreateSurveys() {
return canCreateSurveys;
}
public void setCanCreateSurveys(boolean canCreateSurveys) {
this.canCreateSurveys = canCreateSurveys;
- }
-
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/ec/survey/model/survey/base/File.java b/src/main/java/com/ec/survey/model/survey/base/File.java
index d53cbd410..d9f7fdbe0 100644
--- a/src/main/java/com/ec/survey/model/survey/base/File.java
+++ b/src/main/java/com/ec/survey/model/survey/base/File.java
@@ -123,4 +123,10 @@ public Integer getAnswerId() {
public void setAnswerId(Integer answerId) {
this.answerId = answerId;
}
+
+ @Transient
+ public String getNameForExport()
+ {
+ return getName().replace(";", "").replace("|", "");
+ }
}
diff --git a/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java b/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java
index 2fc71ea77..bb6b4a51e 100644
--- a/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java
+++ b/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java
@@ -6,8 +6,10 @@
import com.ec.survey.service.AdministrationService;
import com.ec.survey.service.LdapService;
import com.ec.survey.service.SessionService;
+import com.ec.survey.tools.Bad2faCredentialsException;
import com.ec.survey.tools.BadSurveyCredentialsException;
import com.ec.survey.tools.EcasHelper;
+import com.ec.survey.tools.FrozenCredentialsException;
import com.ec.survey.tools.Tools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
@@ -72,126 +74,148 @@ public Authentication authenticate(Authentication auth)
logger.debug("authenticate".toUpperCase() +" GET THE TICKET TO CHECK VALUE " + ValidationURL +" THE TICKET IS " + ticket);
- try{
+ boolean weakAuthentication = false;
+ sessionService.initializeProxy();
+ logger.debug("authenticate".toUpperCase() +" PROXY INITIALZED");
+ String xmlValidationAnswer = EcasHelper.getSourceContents(ValidationURL);
+ logger.info("authenticate".toUpperCase() +" GET THE SOURCE CONTENT " + xmlValidationAnswer);
+ if (xmlValidationAnswer.contains("")) {
+ String username = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:user");
+ String type = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:employeeType");
+ String strength = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:strength");
- sessionService.initializeProxy();
- logger.debug("authenticate".toUpperCase() +" PROXY INITIALZED");
- String xmlValidationAnswer = EcasHelper.getSourceContents(ValidationURL);
- logger.info("authenticate".toUpperCase() +" GET THE SOURCE CONTENT " + xmlValidationAnswer);
- if (xmlValidationAnswer.contains("")) {
- String username = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:user");
- String type = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:employeeType");
-
- if (auth.getName() != null && auth.getName().startsWith("oldLogin:"))
+ if (auth.getName() != null && auth.getName().startsWith("oldLogin:"))
+ {
+ String oldlogin = auth.getName().substring(9);
+ if (!oldlogin.equals(username))
{
- String oldlogin = auth.getName().substring(9);
- if (!oldlogin.equals(username))
- {
- logger.warn("replacing user " + oldlogin + " by user " + username);
- }
+ logger.warn("replacing user " + oldlogin + " by user " + username);
}
+ }
+
+ try {
+ logger.debug("authenticate".toUpperCase() +" START TO GET USER INFORMATION FROM DB FOR USERNAME " + username);
+ user = administrationService.getUserForLogin(username, true);
+ } catch (Exception e)
+ {
+ //if an ecas user logs in for the first time there is no db entry for him yes
+ }
+
+ logger.debug("authenticate".toUpperCase() +" Get All Roles From AdminService");
+ List Roles = administrationService.getAllRoles();
+ Role ecRole = null;
+ Role intRole = null;
+ for (Role role : Roles) {
+ if (role.getName().equalsIgnoreCase("Form Manager (EC)")) ecRole = role;
+ if (role.getName().equalsIgnoreCase("Form Manager")) intRole = role;
+ }
+
+ if (user == null)
+ {
+ user = new User();
+ user.setLogin(username);
+ user.setType(User.ECAS);
+ user.setLanguage("EN");
+ user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email"));
+ user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName"));
+ user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName"));
- try {
- logger.debug("authenticate".toUpperCase() +" START TO GET USER INFORMATION FROM DB FOR USERNAME " + username);
- user = administrationService.getUserForLogin(username, true);
- } catch (Exception e)
- {
- //if an ecas user logs in for the first time there is no db entry for him yes
- }
+ if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c"))
+ {
+ user.getRoles().add(ecRole);
+ } else {
+ if (strength.equalsIgnoreCase("PASSWORD") || strength.equalsIgnoreCase("STRONG"))
+ {
+ weakAuthentication = true;
+ if (!surveyLoginMode)
+ {
+ throw new Bad2faCredentialsException("Ecas user does not use two factor authentication!");
+ }
+ }
+
+ user.getRoles().add(intRole);
+ }
- logger.debug("authenticate".toUpperCase() +" Get All Roles From AdminService");
- List Roles = administrationService.getAllRoles();
- Role ecRole = null;
- Role intRole = null;
- for (Role role : Roles) {
- if (role.getName().equalsIgnoreCase("Form Manager (EC)")) ecRole = role;
- if (role.getName().equalsIgnoreCase("Form Manager")) intRole = role;
- }
+ try {
+ administrationService.createUser(user);
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ throw new BadCredentialsException("Ecas user cannot be created!");
+ }
+ } else {
+ String oldEmail = user.getEmail();
- if (user == null)
- {
- user = new User();
- user.setLogin(username);
- user.setType(User.ECAS);
- user.setLanguage("EN");
- user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email"));
- user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName"));
- user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName"));
-
- if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c"))
+ user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email"));
+ user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName"));
+ user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName"));
+
+ if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c"))
+ {
+ if (ecRole != null)
{
- user.getRoles().add(ecRole);
- } else {
- user.getRoles().add(intRole);
+ if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), ecRole.getId()))
+ {
+ user.getRoles().clear();
+ user.getRoles().add(ecRole);
+ administrationService.updateUser(user);
+ }
}
-
- administrationService.createUser(user);
} else {
- String oldEmail = user.getEmail();
-
- user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email"));
- user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName"));
- user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName"));
-
- if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c"))
+ if (intRole != null)
{
- if (ecRole != null)
- {
- if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), ecRole.getId()))
- {
- user.getRoles().clear();
- user.getRoles().add(ecRole);
- administrationService.updateUser(user);
- }
+ if (strength.equalsIgnoreCase("PASSWORD") || strength.equalsIgnoreCase("STRONG"))
+ {
+ weakAuthentication = true;
+ if (!surveyLoginMode)
+ {
+ throw new Bad2faCredentialsException("Ecas user does not use two factor authentication!");
+ }
}
- } else {
- if (intRole != null)
+
+ if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), intRole.getId()))
{
- if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), intRole.getId()))
- {
- user.getRoles().clear();
- user.getRoles().add(intRole);
- administrationService.updateUser(user);
- }
+ user.getRoles().clear();
+ user.getRoles().add(intRole);
+ administrationService.updateUser(user);
}
}
-
- if (!oldEmail.equalsIgnoreCase(user.getEmail()))
+ }
+
+ if (!oldEmail.equalsIgnoreCase(user.getEmail()))
+ {
+ if (user.getOtherEmail() == null)
{
- if (user.getOtherEmail() == null)
+ user.setOtherEmail(oldEmail);
+ } else {
+ if (!user.getOtherEmail().endsWith(";"))
{
- user.setOtherEmail(oldEmail);
+ user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail);
} else {
- if (!user.getOtherEmail().endsWith(";"))
- {
- user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail);
- } else {
- user.setOtherEmail(user.getOtherEmail() + oldEmail);
- }
+ user.setOtherEmail(user.getOtherEmail() + oldEmail);
}
- administrationService.updateUser(user);
}
+ administrationService.updateUser(user);
}
-
- Collection authorities = getAuthorities(user, true);
-
- if (surveyLoginMode)
- {
- authorities.add(new SimpleGrantedAuthority("ROLE_ECAS_SURVEY_" + survey));
- }
-
- return new UsernamePasswordAuthenticationToken(
- username,
- "",
- authorities);
+ }
+
+ Collection authorities = getAuthorities(user, true, weakAuthentication);
+
+ if (surveyLoginMode)
+ {
+ authorities.add(new SimpleGrantedAuthority("ROLE_ECAS_SURVEY_" + survey));
+ }
+
+ checkUserNotBanned(user);
+
+ return new UsernamePasswordAuthenticationToken(
+ username,
+ "",
+ authorities);
} else{
logger.error("cas:authenticationSuccess NOT FOUND IN XMLVALIDATION");
}
- } catch (Exception e)
- {
- logger.error("error on getValidation "+e.getLocalizedMessage(), e);
- }
+
logger.error("Ecas user cannot be validated!");
@@ -233,13 +257,27 @@ public Authentication authenticate(Authentication auth)
throw new BadCredentialsException("User not validated!");
}
+ checkUserNotBanned(user);
+
user.setBadLoginAttempts(0);
administrationService.updateUser(user);
return new UsernamePasswordAuthenticationToken(
auth.getName(),
auth.getCredentials(),
- getAuthorities(user, false));
+ getAuthorities(user, false, false));
+ }
+
+ private void checkUserNotBanned(User user)
+ {
+ if (user.isFrozen()) {
+ throw new FrozenCredentialsException("User is banned!");
+ }
+
+ if (!administrationService.checkEmailsNotBanned(user.getAllEmailAddresses()))
+ {
+ throw new FrozenCredentialsException("User is banned!");
+ }
}
/**
@@ -249,8 +287,13 @@ public Authentication authenticate(Authentication auth)
* @param ecas
* @return
*/
- public Collection getAuthorities(User user, boolean ecas) {
+ public Collection getAuthorities(User user, boolean ecas, boolean weakAuthentication) {
List authList = new ArrayList<>();
+
+ if (weakAuthentication)
+ {
+ authList.add(new SimpleGrantedAuthority("ROLE_WEAK_AUTHENTICATION"));
+ }
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
diff --git a/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java b/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java
index bc969cb2c..2da46ded9 100644
--- a/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java
+++ b/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java
@@ -50,6 +50,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
User user = null;
try {
boolean ecas = false;
+ boolean weakAuthentication = false;
for (GrantedAuthority auth: securityContext.getAuthentication().getAuthorities())
{
if (auth.getAuthority().equalsIgnoreCase("ROLE_ECAS_USER"))
@@ -57,6 +58,11 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
ecas = true;
}
+ if (auth.getAuthority().equalsIgnoreCase("ROLE_WEAK_AUTHENTICATION"))
+ {
+ weakAuthentication = true;
+ }
+
if (auth.getAuthority().startsWith("ROLE_ECAS_SURVEY_"))
{
request.getSession().setAttribute("ECASSURVEY", auth.getAuthority().substring(17));
@@ -93,6 +99,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
}
request.getSession().setAttribute("USER", user);
+ request.getSession().setAttribute("WEAKAUTHENTICATION", weakAuthentication);
localeResolver.setLocale(request, response, new Locale(user.getLanguage()));
} catch (Exception e) {
diff --git a/src/main/java/com/ec/survey/service/ActivityService.java b/src/main/java/com/ec/survey/service/ActivityService.java
index a305afed7..7d2dccdcc 100644
--- a/src/main/java/com/ec/survey/service/ActivityService.java
+++ b/src/main/java/com/ec/survey/service/ActivityService.java
@@ -56,6 +56,9 @@ public void log(Map activitiesToLog, Integer userId, String s
activity.setLogID(logId);
activity.setOldValue(oldnew[counter++]);
activity.setNewValue(oldnew[counter++]);
+
+ checkValueSizes(activity);
+
activity.setUserId(userId);
activity.setSurveyUID(surveyUID);
session.save(activity);
@@ -89,6 +92,9 @@ public void logTranslations(int activityCode, String code, Map o
activity.setLogID(activityCode);
activity.setOldValue(code + " " + key + ": " + oldValue);
activity.setNewValue(code + " " + key + ": " + newValue);
+
+ checkValueSizes(activity);
+
activity.setUserId(userId);
activity.setSurveyUID(surveyUID);
session.save(activity);
@@ -105,6 +111,9 @@ public void logTranslations(int activityCode, String code, Map o
activity.setLogID(activityCode);
activity.setOldValue(code + " " + key + ":");
activity.setNewValue(code + " " + key + ": " + info.get(key));
+
+ checkValueSizes(activity);
+
activity.setUserId(userId);
activity.setSurveyUID(surveyUID);
session.save(activity);
@@ -146,6 +155,9 @@ public void log(int activityCode, String oldValue, String newValue, int userId,
activity.setLogID(activityCode);
activity.setOldValue(oldValue);
activity.setNewValue(newValue);
+
+ checkValueSizes(activity);
+
activity.setUserId(userId);
activity.setSurveyUID(surveyUID);
activity.setType(type);
@@ -163,15 +175,30 @@ public void log(int activityCode, String oldValue, String newValue, int userId,
activity.setLogID(activityCode);
activity.setOldValue(oldValue);
activity.setNewValue(newValue);
+
+ checkValueSizes(activity);
+
activity.setUserId(userId);
activity.setSurveyUID(surveyUID);
activity.setType(type);
session.save(activity);
}
}
+ }
+ }
+
+ private void checkValueSizes(Activity activity)
+ {
+ if (activity.getOldValue() != null && activity.getOldValue().length() > 65000)
+ {
+ activity.setOldValue(activity.getOldValue().substring(0, 65000) + "...");
}
- }
+ if (activity.getNewValue() != null && activity.getNewValue().length() > 65000)
+ {
+ activity.setNewValue(activity.getNewValue().substring(0, 65000) + "...");
+ }
+ }
@Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public void log(int activityCode, String oldValue, String newValue, int userId, String surveyUID)
diff --git a/src/main/java/com/ec/survey/service/AdministrationService.java b/src/main/java/com/ec/survey/service/AdministrationService.java
index 437dc8cfe..9733f2d67 100644
--- a/src/main/java/com/ec/survey/service/AdministrationService.java
+++ b/src/main/java/com/ec/survey/service/AdministrationService.java
@@ -3,6 +3,7 @@
import com.ec.survey.model.*;
import com.ec.survey.model.administration.*;
import com.ec.survey.model.survey.Survey;
+import com.ec.survey.tools.ConversionTools;
import com.ec.survey.tools.LoginAlreadyExistsException;
import com.ec.survey.tools.Tools;
@@ -25,46 +26,42 @@
@Service("administrationService")
public class AdministrationService extends BasicService {
-
- @Resource(name="sessionService")
- private SessionService sessionService;
-
- @Resource(name="mailService")
+
+ @Resource(name = "sessionService")
+ private SessionService sessionService;
+
+ @Resource(name = "mailService")
private MailService mailService;
-
+
@Autowired
private SqlQueryService sqlQueryService;
-
+
private @Value("${admin.user}") String adminuser;
private @Value("${admin.password}") String adminpassword;
private @Value("${stress.user}") String stressuser;
- private @Value("${stress.password}") String stresspassword;
+ private @Value("${stress.password}") String stresspassword;
- private @Value("${smtpserver}") String smtpServer;
+ private @Value("${smtpserver}") String smtpServer;
private @Value("${smtp.port}") String smtpPort;
- private @Value("${sender}") String sender;
+ private @Value("${sender}") String sender;
private @Value("${server.prefix}") String host;
-
- public String getAdminUser()
- {
+
+ public String getAdminUser() {
return adminuser;
}
-
- public String getAdminPassword()
- {
+
+ public String getAdminPassword() {
return adminpassword;
}
-
- public String getStressUser()
- {
+
+ public String getStressUser() {
return stressuser;
}
-
- public String getStressPassword()
- {
+
+ public String getStressPassword() {
return stresspassword;
}
-
+
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List getAllRoles() {
@@ -115,7 +112,7 @@ public List getAllUsers() {
Query query = session.createQuery("FROM User");
return query.list();
}
-
+
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List getAllUserIDs() {
@@ -123,16 +120,16 @@ public List getAllUserIDs() {
Query query = session.createQuery("SELECT u.id FROM User u");
return query.list();
}
-
+
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List getUsers(UserFilter filter, SqlPagination sqlPagination) throws Exception {
Session session = sessionFactory.getCurrentSession();
-
+
HashMap parameters = new HashMap<>();
Query query = session.createQuery(getHql(filter, parameters));
sqlQueryService.setParameters(query, parameters);
-
+
return query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).setFirstResult(sqlPagination.getFirstResult()).setMaxResults(sqlPagination.getMaxResult()).list();
}
@@ -145,47 +142,46 @@ public User getUser(Integer id) {
@Transactional
public void createUser(User user) throws Exception {
Session session = sessionFactory.getCurrentSession();
-
+
Query query = session.createQuery("FROM User u where u.login = :login").setString("login", user.getLogin());
@SuppressWarnings("unchecked")
List list = query.list();
-
- if (list.size() > 0) throw new LoginAlreadyExistsException();
-
+
+ if (list.size() > 0)
+ throw new LoginAlreadyExistsException();
+
session.save(user);
}
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void updateUser(User user) {
Session session = sessionFactory.getCurrentSession();
user = (User) session.merge(user);
-
+
String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled);
- if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0)
- {
+ if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) {
user.setCanCreateSurveys(false);
}
-
+
session.setReadOnly(user, false);
session.update(user);
}
-
+
@Transactional
- public boolean checkUserPassword(User user, String rawPassword)
- {
- logger.debug("CHECKUSERPASSWORD CALLED " +user.getPassword() +" " + rawPassword);
-
+ public boolean checkUserPassword(User user, String rawPassword) {
+ logger.debug("CHECKUSERPASSWORD CALLED " + user.getPassword() + " " + rawPassword);
+
String md5hash = Tools.md5hash(rawPassword);
-
+
if (user.getPassword().equals(md5hash)) {
- //replace md5 hash by salted SHA-512 hash
- Session session = sessionFactory.getCurrentSession();
+ // replace md5 hash by salted SHA-512 hash
+ Session session = sessionFactory.getCurrentSession();
user.setPasswordSalt(Tools.newSalt());
user.setPassword(Tools.hash(rawPassword + user.getPasswordSalt()));
session.update(user);
return true;
}
-
+
return false;
}
@@ -201,25 +197,25 @@ public String deleteUser(int id) {
@Transactional(readOnly = true)
public String[] getLoginsForPrefix(String term, String emailterm, boolean forPrivileges) {
Session session = sessionFactory.getCurrentSession();
-
+
Query query = null;
- if (term.length() > 0 && (emailterm != null && emailterm.length() > 0 ))
- {
- query = session.createQuery("FROM User u where u.login like :login and u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("login", "%" + term + "%").setString("email", "%" + emailterm + "%");
+ if (term.length() > 0 && (emailterm != null && emailterm.length() > 0)) {
+ query = session.createQuery("FROM User u where u.login like :login and u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM)
+ .setString("login", "%" + term + "%").setString("email", "%" + emailterm + "%");
} else if (emailterm != null && emailterm.length() > 0) {
query = session.createQuery("FROM User u where u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("email", "%" + emailterm + "%");
} else {
query = session.createQuery("FROM User u where u.login like :login and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("login", "%" + term + "%");
}
-
+
@SuppressWarnings("unchecked")
List list = query.setMaxResults(100).list();
String[] result = new String[list.size()];
int counter = 0;
for (User user : list) {
- if (forPrivileges)
- {
- result[counter++] = "" + user.getLogin() + " | " + (user.getGivenName() == null ? " " : user.getGivenName()) + " | " + (user.getSurName() == null ? " " : user.getSurName()) + " | |
";
+ if (forPrivileges) {
+ result[counter++] = "" + user.getLogin() + " | "
+ + (user.getGivenName() == null ? " " : user.getGivenName()) + " | " + (user.getSurName() == null ? " " : user.getSurName()) + " | |
";
} else {
result[counter++] = user.getLogin();
}
@@ -227,69 +223,67 @@ public String[] getLoginsForPrefix(String term, String emailterm, boolean forPri
return result;
}
-
+
@Transactional(readOnly = true)
public User getUserForLogin(String login) {
Session session = sessionFactory.getCurrentSession();
-
+
String hql = "FROM User u where u.login = :login";
-
- Query query = session.createQuery(hql).setString("login", login);
+
+ Query query = session.createQuery(hql).setString("login", login);
@SuppressWarnings("unchecked")
List list = query.list();
if (list.size() > 0)
- return list.get(0);
-
+ return list.get(0);
+
return null;
}
-
+
@Transactional(readOnly = true)
public Map getECASUserLoginsByEmail() {
Session session = sessionFactory.getCurrentSession();
-
- Query query = session.createSQLQuery("SELECT USER_EMAIL, USER_LOGIN FROM USERS WHERE USER_TYPE = 'ECAS'");
+
+ Query query = session.createSQLQuery("SELECT USER_EMAIL, USER_LOGIN FROM USERS WHERE USER_TYPE = 'ECAS'");
@SuppressWarnings("rawtypes")
List res = query.list();
-
+
HashMap result = new HashMap<>();
-
- for (Object o: res)
- {
+
+ for (Object o : res) {
Object[] a = (Object[]) o;
if (!result.containsKey((String) a[0])) {
result.put((String) a[0], (String) a[1]);
}
}
-
+
return result;
}
@Transactional(readOnly = true)
public User getUserForLogin(String login, boolean ecas) throws Exception {
- logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER " + login +" IS ECAS " + ecas );
+ logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER " + login + " IS ECAS " + ecas);
Session session = sessionFactory.getCurrentSession();
-
+
String hql = "FROM User u where u.login = :login AND u.type = :type";
-
- Query query = session.createQuery(hql).setString("login", login);
-
- if (ecas)
- {
+
+ Query query = session.createQuery(hql).setString("login", login);
+
+ if (ecas) {
query.setString("type", User.ECAS);
} else {
query.setString("type", User.SYSTEM);
}
- logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER LAUNCH QUERY ");
+ logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER LAUNCH QUERY ");
@SuppressWarnings("unchecked")
List list = query.list();
-
- logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER QUERY EXECUTED WITH RESULT SIZE " + list.size());
+
+ logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER QUERY EXECUTED WITH RESULT SIZE " + list.size());
if (list.size() == 0)
throw new Exception("No user found for login " + login);
@@ -298,114 +292,108 @@ public User getUserForLogin(String login, boolean ecas) throws Exception {
return list.get(0);
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
- public void save(UsersConfiguration userConfiguration)
- {
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ public void save(UsersConfiguration userConfiguration) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(userConfiguration);
}
-
+
@Transactional(readOnly = true)
- public UsersConfiguration getUsersConfiguration(int userId)
- {
+ public UsersConfiguration getUsersConfiguration(int userId) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM UsersConfiguration c where c.userId = :userId").setInteger("userId", userId);
-
+
@SuppressWarnings("unchecked")
List list = query.list();
if (list.size() == 0)
return null;
-
+
return list.get(0);
}
@Transactional(readOnly = false)
public void sendValidationEmail(User user) throws NumberFormatException, Exception {
Session session = sessionFactory.getCurrentSession();
-
+
user.setValidationCode(UUID.randomUUID().toString());
user.setValidationCodeGeneration(new Date());
session.update(user);
-
+
String link = host + "validate/" + user.getId() + "/" + user.getValidationCode();
-
+
String body = "Dear " + user.getLogin() + ",
Please validate your account by clicking the link below:
" + link + "";
-
+
mailService.SendHtmlMail(user.getEmail(), sender, sender, "EUSurvey Registration", body, smtpServer, Integer.parseInt(smtpPort), null);
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public boolean sendNewEmailAdressValidationEmail(User user) {
- try {
+ try {
Session session = sessionFactory.getCurrentSession();
user.setValidationCode(UUID.randomUUID().toString());
user.setValidationCodeGeneration(new Date());
session.update(user);
-
+
String link = host + "validateNewEmail/" + user.getId() + "/" + user.getValidationCode();
-
+
String body = "Dear " + user.getLogin() + ",
Please confirm your email change by clicking the link below:
" + link + "";
-
+
InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html");
- String text = IOUtils.toString(inputStream, "UTF-8").replace("[CONTENT]", body).replace("[HOST]", host);
-
+ String text = IOUtils.toString(inputStream, "UTF-8").replace("[CONTENT]", body).replace("[HOST]", host);
+
mailService.SendHtmlMail(user.getEmailToValidate(), sender, sender, "EUSurvey Confirmation", text, smtpServer, Integer.parseInt(smtpPort), null);
- } catch (Exception ex) {
- logger.error(ex.getLocalizedMessage(), ex);
- return false;
- }
+ } catch (Exception ex) {
+ logger.error(ex.getLocalizedMessage(), ex);
+ return false;
+ }
return true;
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public boolean validateUser(int id, String code) {
Session session = sessionFactory.getCurrentSession();
User user = (User) session.get(User.class, id);
-
- if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code))
- {
+
+ if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code)) {
user.setValidated(true);
session.update(user);
-
+
return true;
}
-
+
return false;
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public boolean validateNewEmail(HttpServletRequest request, int id, String code) {
Session session = sessionFactory.getCurrentSession();
User user = (User) session.get(User.class, id);
-
- if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code) && user.getEmailToValidate() != null)
- {
+
+ if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code) && user.getEmailToValidate() != null) {
String oldEmail = user.getEmail();
- if (user.getOtherEmail() == null)
- {
+ if (user.getOtherEmail() == null) {
user.setOtherEmail(oldEmail);
} else {
- if (!user.getOtherEmail().endsWith(";"))
- {
+ if (!user.getOtherEmail().endsWith(";")) {
user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail);
} else {
user.setOtherEmail(user.getOtherEmail() + oldEmail);
}
}
-
+
user.setEmail(user.getEmailToValidate());
user.setEmailToValidate(null);
user.setValidationCode(null);
- session.update(user);
+ session.update(user);
sessionService.setCurrentUser(request, user);
return true;
}
-
+
return false;
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public OneTimePasswordResetCode createOneTimePasswordResetCode(User user) {
OneTimePasswordResetCode code = new OneTimePasswordResetCode(user);
Session session = sessionFactory.getCurrentSession();
@@ -416,7 +404,7 @@ public OneTimePasswordResetCode createOneTimePasswordResetCode(User user) {
@Transactional(readOnly = true)
public OneTimePasswordResetCode getOneTimePasswordResetCode(String code) throws Exception {
Session session = sessionFactory.getCurrentSession();
-
+
Query query = session.createQuery("FROM OneTimePasswordResetCode c where c.code = :code").setString("code", code);
@SuppressWarnings("unchecked")
List list = query.list();
@@ -428,40 +416,36 @@ public OneTimePasswordResetCode getOneTimePasswordResetCode(String code) throws
return list.get(0);
}
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void add(EcasUser eu) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(eu);
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void removeUserGroups(Integer id) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createSQLQuery("DELETE FROM ECASGROUPS where eg_id = :id").setInteger("id", id);
query.executeUpdate();
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
- public void deactivateEcasUser(int id)
- {
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ public void deactivateEcasUser(int id) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("UPDATE EcasUser u SET u.deactivated = true WHERE u.id = :id").setInteger("id", id);
- query.executeUpdate();
+ query.executeUpdate();
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
- public void deactivateEcasUsers(List ids)
- {
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ public void deactivateEcasUsers(List ids) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("UPDATE EcasUser u SET u.deactivated = true WHERE u.id = :id");
int counter = 0;
- for (int id : ids)
- {
+ for (int id : ids) {
query.setInteger("id", id);
query.executeUpdate();
- counter+=1;
- if (counter % 10000 == 0)
- {
+ counter += 1;
+ if (counter % 10000 == 0) {
logger.info(counter + " EcasUsers deactivated");
}
}
@@ -470,193 +454,254 @@ public void deactivateEcasUsers(List ids)
@Transactional(readOnly = true)
public int getNumberOfUsers(UserFilter filter) {
Session session = sessionFactory.getCurrentSession();
-
+
HashMap parameters = new HashMap<>();
Query query = session.createQuery(getHql(filter, parameters));
-
+
for (String attrib : parameters.keySet()) {
Object value = parameters.get(attrib);
- if (value instanceof String)
- {
- query.setString(attrib, (String)parameters.get(attrib));
- } else if (value instanceof Integer)
- {
- query.setInteger(attrib, (Integer)parameters.get(attrib));
- } else if (value instanceof Date)
- {
- query.setDate(attrib, (Date)parameters.get(attrib));
+ if (value instanceof String) {
+ query.setString(attrib, (String) parameters.get(attrib));
+ } else if (value instanceof Integer) {
+ query.setInteger(attrib, (Integer) parameters.get(attrib));
+ } else if (value instanceof Date) {
+ query.setDate(attrib, (Date) parameters.get(attrib));
}
}
-
+
return query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).list().size();
}
-
- private String getHql(UserFilter filter, HashMap parameters)
- {
+
+ private String getHql(UserFilter filter, HashMap parameters) {
StringBuilder hql = new StringBuilder("SELECT DISTINCT u FROM User u LEFT JOIN u.roles as r WHERE u.id > 0");
-
- if (filter.getLogin() != null && filter.getLogin().length() > 0)
- {
+
+ if (filter.getLogin() != null && filter.getLogin().length() > 0) {
hql.append(" AND u.login like :login");
parameters.put("login", "%" + filter.getLogin() + "%");
}
-
- if (filter.getEmail() != null && filter.getEmail().length() > 0)
- {
+
+ if (filter.getEmail() != null && filter.getEmail().length() > 0) {
hql.append(" AND u.email like :email");
parameters.put("email", "%" + filter.getEmail() + "%");
}
-
- if (filter.getComment() != null && filter.getComment().length() > 0)
- {
+
+ if (filter.getComment() != null && filter.getComment().length() > 0) {
hql.append(" AND u.comment like :comment");
parameters.put("comment", "%" + filter.getComment() + "%");
}
-
- if (filter.getLanguages() != null)
- {
+
+ if (filter.getLanguages() != null) {
int i = 0;
hql.append(" AND (");
- for (String lang : filter.getLanguages())
- {
- if (lang.trim().length() > 0)
- {
+ for (String lang : filter.getLanguages()) {
+ if (lang.trim().length() > 0) {
String l = "lang" + i++;
-
- if (i > 1)
- {
+
+ if (i > 1) {
hql.append(" OR");
}
-
+
hql.append(" ( u.language like :").append(l).append(")");
parameters.put(l, lang.trim());
}
}
hql.append(" )");
}
-
- if (filter.getECAS() != null && filter.getSystem() != null)
- if (filter.getECAS() && !filter.getSystem())
- {
- hql.append(" AND u.type = 'ECAS'");
- } else if (!filter.getECAS() && filter.getSystem())
- {
- hql.append(" AND u.type = 'SYSTEM'");
+
+ if (filter.getECAS() != null && filter.getSystem() != null) {
+ if (filter.getECAS() && !filter.getSystem()) {
+ hql.append(" AND u.type = 'ECAS'");
+ } else if (!filter.getECAS() && filter.getSystem()) {
+ hql.append(" AND u.type = 'SYSTEM'");
+ }
}
- if (filter.getRoles() != null)
- {
+ if (filter.getBanned() != null && filter.getBanned() && filter.getUnbanned() != null && filter.getUnbanned()) {
+ //show all
+ } else if (filter.getBanned() != null && filter.getBanned()) {
+ hql.append(" AND u.frozen = true");
+ } else if (filter.getUnbanned() != null && filter.getUnbanned()) {
+ hql.append(" AND u.frozen = false");
+ }
+
+ if (filter.getRoles() != null) {
int i = 0;
hql.append(" AND (");
- for (String role : filter.getRoles())
- {
- if (role.trim().length() > 0)
- {
+ for (String role : filter.getRoles()) {
+ if (role.trim().length() > 0) {
String l = "role" + i++;
-
- if (i > 1)
- {
+
+ if (i > 1) {
hql.append(" OR");
}
-
+
hql.append(" r.id like :").append(l);
-
+
parameters.put(l, Integer.parseInt(role.trim()));
}
}
hql.append(" )");
}
-
- if (filter.getECASaccess() != null && filter.getNoECASaccess() != null)
- if (filter.getECASaccess() && !filter.getNoECASaccess())
- {
- hql.append(" AND u.canAccessEcasFunctionality = true");
- } else if (!filter.getECASaccess() && filter.getNoECASaccess())
- {
- hql.append(" AND u.canAccessEcasFunctionality = false");
- }
-
- if (filter.getECaccess() != null && filter.getNoECaccess() != null)
- if (filter.getECaccess() && !filter.getNoECaccess())
- {
- hql.append(" AND u.canAccessECFunctionality = true");
- } else if (!filter.getECaccess() && filter.getNoECaccess())
- {
- hql.append(" AND u.canAccessECFunctionality = false");
- }
-
- if (filter.getSortKey() != null && filter.getSortKey().length() > 0)
- {
-
+
+ if (filter.getECASaccess() != null && filter.getNoECASaccess() != null)
+ if (filter.getECASaccess() && !filter.getNoECASaccess()) {
+ hql.append(" AND u.canAccessEcasFunctionality = true");
+ } else if (!filter.getECASaccess() && filter.getNoECASaccess()) {
+ hql.append(" AND u.canAccessEcasFunctionality = false");
+ }
+
+ if (filter.getECaccess() != null && filter.getNoECaccess() != null)
+ if (filter.getECaccess() && !filter.getNoECaccess()) {
+ hql.append(" AND u.canAccessECFunctionality = true");
+ } else if (!filter.getECaccess() && filter.getNoECaccess()) {
+ hql.append(" AND u.canAccessECFunctionality = false");
+ }
+
+ if (filter.getSortKey() != null && filter.getSortKey().length() > 0) {
+
hql.append(" ORDER BY u.").append(filter.getSortKey());
-
- if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0)
- {
+
+ if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) {
hql.append(" ").append(filter.getSortOrder());
} else {
hql.append(" DESC");
}
-
+
}
-
+
return hql.toString();
}
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void createDummyEcasUsers(int counter) {
Session session = sessionFactory.getCurrentSession();
-
- for (int i = 0; i < 100000; i++)
- {
+
+ for (int i = 0; i < 100000; i++) {
EcasUser eu = new EcasUser();
eu.setDepartmentNumber("Department1");
- eu.setEcMoniker("newuserz"+counter+"#"+i);
+ eu.setEcMoniker("newuserz" + counter + "#" + i);
eu.setEmail("test@clam.dialogika.de");
- eu.setName("newnamez"+counter+"#"+i);
+ eu.setName("newnamez" + counter + "#" + i);
eu.setUserLDAPGroups(new HashSet<>());
eu.getUserLDAPGroups().add("Department1");
session.saveOrUpdate(eu);
}
}
-
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void createDummySurAccess() throws Exception {
Session session = sessionFactory.getCurrentSession();
-
+
User user = getUser(8);
-
+
SurveyFilter filter = new SurveyFilter();
filter.setUser(getUser(1));
- SqlPagination sqlPagination = new SqlPagination(0, 5000);
+ SqlPagination sqlPagination = new SqlPagination(0, 5000);
List surveys = surveyService.getSurveys(filter, sqlPagination);
-
+
for (Survey survey : surveys) {
- Access a = new Access();
- a.setSurvey(survey);
- a.setUser(user);
- a.getLocalPrivileges().put(LocalPrivilege.FormManagement, 1);
- session.saveOrUpdate(a);
+ Access a = new Access();
+ a.setSurvey(survey);
+ a.setUser(user);
+ a.getLocalPrivileges().put(LocalPrivilege.FormManagement, 1);
+ session.saveOrUpdate(a);
}
}
- public boolean isSmtpServerConfigured() {
- return !StringUtils.isEmpty(smtpServer);
- }
+ public boolean isSmtpServerConfigured() {
+ return !StringUtils.isEmpty(smtpServer);
+ }
- @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public User setLastEditedSurvey(User user, Integer surveyid) {
- Session session = sessionFactory.getCurrentSession();
- user = (User)session.merge(user);
-
- String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled);
- if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0)
- {
+ Session session = sessionFactory.getCurrentSession();
+ user = (User) session.merge(user);
+
+ String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled);
+ if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) {
user.setCanCreateSurveys(false);
}
-
- user.setLastEditedSurvey(surveyid);
+
+ user.setLastEditedSurvey(surveyid);
session.saveOrUpdate(user);
return user;
}
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ public void banUser(String userId, String mailText) throws Exception {
+ Session session = sessionFactory.getCurrentSession();
+ User user = getUser(Integer.parseInt(userId));
+
+ if (user == null) {
+ throw new Exception("user does not exist");
+ }
+
+ user.setFrozen(true);
+ session.saveOrUpdate(user);
+
+ // send email to user
+ InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html");
+ String mailtemplate = IOUtils.toString(inputStream, "UTF-8");
+ String mailtext = mailtemplate.replace("[CONTENT]", mailText).replace("[HOST]", host);
+ mailService.SendHtmlMail(user.getEmail(), sender, sender, "Your account has been banned", mailtext, smtpServer, Integer.parseInt(smtpPort), null);
+
+ // send email to admins
+ String recipients = settingsService.get(Setting.BannedUserRecipients);
+ mailtext = settingsService.get(Setting.FreezeUserTextAdminBan).replace("[LOGIN]", user.getLogin()).replace("[EMAIL]", user.getEmail());
+ mailtext = mailtemplate.replace("[CONTENT]", mailtext).replace("[HOST]", host);
+
+ String[] emails = recipients.split(";");
+ for (String recipient : emails) {
+ if (recipient.trim().length() > 0) {
+ mailService.SendHtmlMail(recipient, sender, sender, "User banned", mailtext, smtpServer, Integer.parseInt(smtpPort), null);
+ }
+ }
+ }
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ public void unbanUser(String userId) throws Exception {
+ Session session = sessionFactory.getCurrentSession();
+ User user = getUser(Integer.parseInt(userId));
+
+ if (user == null) {
+ throw new Exception("user does not exist");
+ }
+
+ user.setFrozen(false);
+ session.saveOrUpdate(user);
+
+ // send email to user
+ InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html");
+ String mailtemplate = IOUtils.toString(inputStream, "UTF-8");
+
+ String content = settingsService.get(Setting.FreezeUserTextUnban);
+
+ String mailtext = mailtemplate.replace("[CONTENT]", content).replace("[HOST]", host);
+ mailService.SendHtmlMail(user.getEmail(), sender, sender, "Your account has been unbanned", mailtext, smtpServer, Integer.parseInt(smtpPort), null);
+
+ // send email to admins
+ String recipients = settingsService.get(Setting.BannedUserRecipients);
+ mailtext = settingsService.get(Setting.FreezeUserTextAdminUnban).replace("[LOGIN]", user.getLogin()).replace("[EMAIL]", user.getEmail());
+ mailtext = mailtemplate.replace("[CONTENT]", mailtext).replace("[HOST]", host);
+
+ String[] emails = recipients.split(";");
+ for (String recipient : emails) {
+ if (recipient.trim().length() > 0) {
+ mailService.SendHtmlMail(recipient, sender, sender, "User unbanned", mailtext, smtpServer, Integer.parseInt(smtpPort), null);
+ }
+ }
+ }
+
+ @Transactional(readOnly = true)
+ public boolean checkEmailsNotBanned(List allEmailAddresses) {
+ Session session = sessionFactory.getCurrentSession();
+
+ Query query = session.createQuery("SELECT COUNT(u.id) FROM User u WHERE u.frozen = true AND u.email IN (:emails)");
+ query.setParameterList("emails", allEmailAddresses);
+
+ int count = ConversionTools.getValue(query.uniqueResult());
+
+ return count == 0;
+ }
+
}
diff --git a/src/main/java/com/ec/survey/service/AnswerService.java b/src/main/java/com/ec/survey/service/AnswerService.java
index 24836e5b7..d9ad7e5dd 100644
--- a/src/main/java/com/ec/survey/service/AnswerService.java
+++ b/src/main/java/com/ec/survey/service/AnswerService.java
@@ -17,6 +17,7 @@
import com.ec.survey.tools.InvalidEmailException;
import com.ec.survey.tools.NotAgreedToTosException;
import com.ec.survey.tools.Tools;
+import com.ec.survey.tools.WeakAuthenticationException;
import com.ec.survey.tools.export.StatisticsCreator;
import org.apache.commons.lang3.time.DateUtils;
@@ -1736,11 +1737,11 @@ public List getAnswersAndDrafts(int surveyId) {
return result;
}
- public String getDraftForEcasLogin(Survey survey, HttpServletRequest request) throws NotAgreedToTosException {
+ public String getDraftForEcasLogin(Survey survey, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT d.DRAFT_UID FROM DRAFTS d JOIN ANSWERS_SET a ON d.answerSet_ANSWER_SET_ID = a.ANSWER_SET_ID WHERE (a.RESPONDER_EMAIL = :email or a.RESPONDER_EMAIL = :email2) AND a.SURVEY_ID IN (:ids)";
SQLQuery query = session.createSQLQuery(sql);
- User user = sessionService.getCurrentUser(request, false);
+ User user = sessionService.getCurrentUser(request, false, false);
if (user == null)
return null;
diff --git a/src/main/java/com/ec/survey/service/FtpClient.java b/src/main/java/com/ec/survey/service/FtpClient.java
index ad73ca4f7..77be49c72 100644
--- a/src/main/java/com/ec/survey/service/FtpClient.java
+++ b/src/main/java/com/ec/survey/service/FtpClient.java
@@ -18,7 +18,6 @@
@Service("ftpClient")
public class FtpClient {
-
protected static final Logger logger = Logger.getLogger(FtpClient.class);
private final ProducerTemplate producerTemplate;
private final ConsumerTemplate consumerTemplate;
diff --git a/src/main/java/com/ec/survey/service/ReportingService.java b/src/main/java/com/ec/survey/service/ReportingService.java
index 961b315d2..06407d48f 100644
--- a/src/main/java/com/ec/survey/service/ReportingService.java
+++ b/src/main/java/com/ec/survey/service/ReportingService.java
@@ -115,7 +115,7 @@ public ToDoItem(int id, int type, String uid, String code)
}
}
- private String getWhereClause(ResultFilter filter, Map values, Survey survey) throws TooManyFiltersException
+ public String getWhereClause(ResultFilter filter, Map values, Survey survey) throws TooManyFiltersException
{
String where = "";
Map elementsByUniqueID = survey.getQuestionMapByUniqueId();
@@ -582,7 +582,7 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP
{
v += answerid;
} else {
- v += answer.getStrippedTitle();
+ v += answer.getTitle();
}
}
}
@@ -601,7 +601,7 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP
{
v += answerid;
} else {
- v += answer.getStrippedTitle();
+ v += answer.getTitle();
}
}
}
@@ -634,11 +634,11 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP
{
if (addlinks)
{
- v += "" + file.getName() + "
";
+ v += "" + file.getNameForExport() + "
";
} else if (forexport) {
- v += file.getUid() + "|" + file.getName() + ";";
+ v += file.getUid() + "|" + file.getNameForExport() + ";";
} else {
- v += file.getName() + "
";
+ v += file.getNameForExport() + "
";
}
}
}
@@ -738,7 +738,7 @@ public void deleteOLAPTable(String uid, boolean draftversion, boolean publishedv
while (OLAPTableExists(uid + "_" + counter, true))
{
- query = sessionReporting.createSQLQuery("DROP TABLE IF EXISTS T" + uid.replace("-", "") + "_" + counter);
+ query = sessionReporting.createSQLQuery("DROP TABLE IF EXISTS TD" + uid.replace("-", "") + "_" + counter);
query.executeUpdate();
counter++;
}
@@ -1331,16 +1331,42 @@ public void removeFromOLAPTable(String uid, String code, boolean publishedSurvey
}
@Transactional(readOnly = true, transactionManager = "transactionManagerReporting")
- public int getCount(Survey survey) {
+ public int getCount(Survey survey, String where, Map values) {
if (!isReportingDatabaseEnabled()) return -1;
Session sessionReporting = sessionFactoryReporting.getCurrentSession();
- SQLQuery query = sessionReporting.createSQLQuery("SELECT COUNT(*) FROM " + GetOLAPTableName(survey));
+
+ String sql = "SELECT COUNT(*) FROM " + GetOLAPTableName(survey);
+
+ if (where != null)
+ {
+ sql += where;
+ }
+
+ SQLQuery query = sessionReporting.createSQLQuery(sql);
+
+ if (where != null)
+ {
+ for (String attrib : values.keySet()) {
+ Object value = values.get(attrib);
+ if (value instanceof String)
+ {
+ query.setString(attrib, (String)values.get(attrib));
+ } else if (value instanceof Integer)
+ {
+ query.setInteger(attrib, (Integer)values.get(attrib));
+ } else if (value instanceof Date)
+ {
+ query.setTimestamp(attrib, (Date)values.get(attrib));
+ }
+ }
+ }
+
return ConversionTools.getValue(query.uniqueResult());
}
@Transactional(readOnly = true, transactionManager = "transactionManagerReporting")
- public int getCount(Survey survey, String quid, String auid, boolean noPrefixSearch) {
+ public int getCount(Survey survey, String quid, String auid, boolean noPrefixSearch, String where, Map values) {
if (!isReportingDatabaseEnabled()) return -1;
Session sessionReporting = sessionFactoryReporting.getCurrentSession();
@@ -1354,7 +1380,30 @@ public int getCount(Survey survey, String quid, String auid, boolean noPrefixSea
sql += " LIKE '%" + auid + "%'";
}
+ if (where != null)
+ {
+ sql += " AND QANSWERSETID IN (SELECT QANSWERSETID FROM " + GetOLAPTableName(survey) + " " + where + ")";
+ }
+
SQLQuery query = sessionReporting.createSQLQuery(sql);
+
+ if (where != null)
+ {
+ for (String attrib : values.keySet()) {
+ Object value = values.get(attrib);
+ if (value instanceof String)
+ {
+ query.setString(attrib, (String)values.get(attrib));
+ } else if (value instanceof Integer)
+ {
+ query.setInteger(attrib, (Integer)values.get(attrib));
+ } else if (value instanceof Date)
+ {
+ query.setTimestamp(attrib, (Date)values.get(attrib));
+ }
+ }
+ }
+
return ConversionTools.getValue(query.uniqueResult());
}
diff --git a/src/main/java/com/ec/survey/service/SchedulerService.java b/src/main/java/com/ec/survey/service/SchedulerService.java
index 69868819b..0ac4d5070 100644
--- a/src/main/java/com/ec/survey/service/SchedulerService.java
+++ b/src/main/java/com/ec/survey/service/SchedulerService.java
@@ -32,6 +32,7 @@
import com.ec.survey.tools.EcasUserUpdater;
import com.ec.survey.tools.ExportUpdater;
import com.ec.survey.tools.FileUpdater;
+import com.ec.survey.tools.SendReportedSurveysWorker;
import com.ec.survey.tools.SurveyUpdater;
import com.ec.survey.tools.ValidCodesRemover;
@@ -72,6 +73,9 @@ public class SchedulerService extends BasicService {
@Resource(name = "deleteInvalidStatisticsWorker")
private DeleteInvalidStatisticsWorker deleteInvalidStatisticsWorker;
+ @Resource(name = "sendReportedSurveysWorker")
+ private SendReportedSurveysWorker sendReportedSurveysWorker;
+
@Resource(name = "surveyWorker")
private SurveyUpdater surveyWorker;
@@ -472,7 +476,7 @@ public void migrateReportingSchedule() {
}
}
- @Scheduled(fixedDelay=1200000) //every 20 minutes
+ @Scheduled(fixedDelay=10000) //wait for 10 seconds between calls
public void doToDosSchedule() throws Exception {
if (!isReportingDatabaseEnabled()) return;
@@ -525,6 +529,7 @@ public void doNightlySchedule() {
deleteDraftsWorker.run();
deleteTemporaryFoldersWorker.run();
deleteInvalidStatisticsWorker.run();
+ sendReportedSurveysWorker.run();
logger.debug("End nightly schedule");
}
diff --git a/src/main/java/com/ec/survey/service/SchemaService.java b/src/main/java/com/ec/survey/service/SchemaService.java
index 1fd273829..4e306b43c 100644
--- a/src/main/java/com/ec/survey/service/SchemaService.java
+++ b/src/main/java/com/ec/survey/service/SchemaService.java
@@ -58,6 +58,118 @@ public boolean isOss()
@Resource(name = "domainWorker")
private DomainUpdater domaintWorker;
+ @Transactional
+ public void step93() {
+ Session session = sessionFactory.getCurrentSession();
+ Status status = getStatus();
+
+ settingsService.add(Setting.TrustValueCreatorInternal, "500", "int");
+ settingsService.add(Setting.TrustValuePastSurveys, "500", "int");
+ settingsService.add(Setting.TrustValuePrivilegedUser, "100", "int");
+ settingsService.add(Setting.TrustValueNbContributions, "50", "int");
+ settingsService.add(Setting.TrustValueMinimumPassMark, "100", "int");
+
+ status.setDbversion(93);
+ session.saveOrUpdate(status);
+ }
+
+ @Transactional
+ public void step92() {
+ Session session = sessionFactory.getCurrentSession();
+ Status status = getStatus();
+
+ String text = "Please be informed that the following user [LOGIN] having the email address: [EMAIL] has been banned from EUSurvey.
For more information please contact the EUSurvey team.
";
+ settingsService.add(Setting.FreezeUserTextAdminBan, text, "text");
+
+ text = "Please be informed that the following user [LOGIN] having the email address: [EMAIL] has been unbanned from EUSurvey.
For more information please contact the EUSurvey team.
";
+ settingsService.add(Setting.FreezeUserTextAdminUnban, text, "text");
+
+ text = "Dear Sir or Madam,
You have been banned from EUSurvey application due to infrigiment to our policy.
Reason: to specify
Please refer to our Terms of Service for more information.
Kind regards,
The EUSurvey Team
";
+ settingsService.add(Setting.FreezeUserTextBan, text, "text");
+
+ text = "Dear Sir or Madam,
You have just been unbanned and got back your access to the EUSurvey application. You can now connect to EUSurvey
Kind regards,
The EUSurvey Team
";
+ settingsService.add(Setting.FreezeUserTextUnban, text, "text");
+
+ Setting s = new Setting();
+ s.setKey(Setting.BannedUserRecipients);
+ s.setValue("");
+ s.setFormat("email addresses separated by ;");
+ session.saveOrUpdate(s);
+
+ status.setDbversion(92);
+ session.saveOrUpdate(status);
+ }
+
+ @Transactional
+ public void step91() {
+ Session session = sessionFactory.getCurrentSession();
+ Status status = getStatus();
+
+ SQLQuery query = session.createSQLQuery("ALTER TABLE SETTINGS MODIFY SETTINGS.SETTINGS_VALUE TEXT");
+ query.executeUpdate();
+
+ String newReportText = "The following survey:
" +
+ "
" +
+ "Published survey link: | [LINK] |
" +
+ "Alias: | [ALIAS] |
" +
+ "Title: | [TITLE] |
" +
+ "
" +
+ "has been reported as infringing our policy by [EMAIL] at [DATE].
" +
+ "The reason provided is the following: [TYPE].
" +
+ "So far, it has been reported [COUNT] time(s).
";
+
+ settingsService.update(Setting.ReportText, newReportText);
+
+ status.setDbversion(91);
+ session.saveOrUpdate(status);
+ }
+
+ @Transactional
+ public void step90() {
+ Session session = sessionFactory.getCurrentSession();
+ Status status = getStatus();
+ String existing = settingsService.get(Setting.MaxReports);
+ if (existing == null)
+ {
+ Setting s = new Setting();
+ s.setKey(Setting.MaxReports);
+ s.setValue("5");
+ s.setFormat("int");
+ session.saveOrUpdate(s);
+
+ s = new Setting();
+ s.setKey(Setting.ReportText);
+ s.setValue("Survey [ALIAS]
[TITLE] has been reported as infringing our policy by [EMAIL] at [DATE]. The reason provided is the following: [TYPE].
So far, it has been reported [COUNT] time(s).");
+ s.setFormat("text");
+ session.saveOrUpdate(s);
+
+ s = new Setting();
+ s.setKey(Setting.ReportRecipients);
+ s.setValue("");
+ s.setFormat("email addresses separated by ;");
+ session.saveOrUpdate(s);
+ }
+ status.setDbversion(90);
+ session.saveOrUpdate(status);
+ }
+
+ @Transactional
+ public void step89() {
+ Session session = sessionFactory.getCurrentSession();
+ Status status = getStatus();
+ String existing = settingsService.get(Setting.WeakAuthenticationDisabled);
+ if (existing == null)
+ {
+ Setting s = new Setting();
+ s.setKey(Setting.WeakAuthenticationDisabled);
+ s.setValue("true");
+ s.setFormat("true / false");
+ session.saveOrUpdate(s);
+ }
+ status.setDbversion(89);
+ session.saveOrUpdate(status);
+ }
+
@Transactional
public void step88() {
Session session = sessionFactory.getCurrentSession();
diff --git a/src/main/java/com/ec/survey/service/SessionService.java b/src/main/java/com/ec/survey/service/SessionService.java
index 8e70588f5..943e61194 100644
--- a/src/main/java/com/ec/survey/service/SessionService.java
+++ b/src/main/java/com/ec/survey/service/SessionService.java
@@ -15,6 +15,8 @@
import com.ec.survey.model.survey.Text;
import com.ec.survey.tools.ConversionTools;
import com.ec.survey.tools.NotAgreedToTosException;
+import com.ec.survey.tools.WeakAuthenticationException;
+
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.Query;
@@ -57,22 +59,30 @@ public class SessionService extends BasicService {
private @Value("${pdfserver.prefix}") String pdfServerPrefix;
private @Value("${proxy.nonProxyHosts}") String proxyNonProxyHosts;
- public User getCurrentUser(HttpServletRequest request) throws NotAgreedToTosException {
- return getCurrentUser(request, true);
+ public User getCurrentUser(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException {
+ return getCurrentUser(request, true, true);
}
- public User getCurrentUser(HttpServletRequest request, boolean checkTOS) throws NotAgreedToTosException {
+ public User getCurrentUser(HttpServletRequest request, boolean checkTOS, boolean checkWeakAuthentication) throws NotAgreedToTosException, WeakAuthenticationException {
if (request == null) return null;
User user = (User) request.getSession().getAttribute("USER");
+ Boolean weakAuthentication = (Boolean) request.getSession().getAttribute("WEAKAUTHENTICATION");
if (user != null)
{
Session session = sessionFactory.getCurrentSession();
user = (User) session.merge(user);
+ String weakAuthenticationDisabled = settingsService.get(Setting.WeakAuthenticationDisabled);
+
+ if (weakAuthenticationDisabled.equalsIgnoreCase("true") && checkWeakAuthentication && user.getType().equalsIgnoreCase(User.ECAS) && user.isExternal() && weakAuthentication)
+ {
+ throw new WeakAuthenticationException();
+ }
+
String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled);
- if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0)
+ if (disabled.equalsIgnoreCase("true") && user.isExternal())
{
user.setCanCreateSurveys(false);
}
@@ -294,7 +304,7 @@ public void updateSessionInfo(Survey survey, User user, HttpServletRequest reque
request.getSession().setAttribute("sessioninfo", new SessionInfo(survey.getId(), user.getId(), survey.getOwner().getId(), survey.getLanguage().getCode(),survey.getShortname()));
}
- public SurveyFilter getSurveyFilter(HttpServletRequest request, boolean forms) throws NotAgreedToTosException {
+ public SurveyFilter getSurveyFilter(HttpServletRequest request, boolean forms) throws NotAgreedToTosException, WeakAuthenticationException {
SurveyFilter filter = new SurveyFilter();
filter.setUser(getCurrentUser(request));
@@ -513,6 +523,9 @@ public UserFilter getUserFilter(HttpServletRequest request) {
filter.setLanguages(request.getParameterValues("languages"));
+ filter.setBanned(request.getParameter("banned") != null && request.getParameter("banned").equalsIgnoreCase("true"));
+ filter.setUnbanned(request.getParameter("unbanned") != null && request.getParameter("unbanned").equalsIgnoreCase("true"));
+
String roles[] = request.getParameterValues("roles");
if (roles != null && roles.length > 0)
{
diff --git a/src/main/java/com/ec/survey/service/SurveyService.java b/src/main/java/com/ec/survey/service/SurveyService.java
index 8f75885d9..45731997c 100644
--- a/src/main/java/com/ec/survey/service/SurveyService.java
+++ b/src/main/java/com/ec/survey/service/SurveyService.java
@@ -38,60 +38,61 @@
@Service("surveyService")
public class SurveyService extends BasicService {
-
+
private @Value("${publicsurveynotification}") String publicsurveynotification;
private @Value("${smtpserver}") String smtpServer;
private @Value("${smtp.port}") String smtpPort;
private @Value("${sender}") String sender;
private @Value("${server.prefix}") String host;
public @Value("${opc.notify}") String opcnotify;
-
+ private @Value("${monitoring.recipient}") String monitoringEmail;
+
@Autowired
protected SqlQueryService sqlQueryService;
-
+
+ @Autowired
+ protected LdapService ldapDBService;
+
@Transactional(readOnly = true)
- public int getNumberPublishedAnswersFromMaterializedView(String uid)
- {
+ public int getNumberPublishedAnswersFromMaterializedView(String uid) {
Session session = sessionFactory.getCurrentSession();
String sql = "SELECT npa.PUBLISHEDANSWERS FROM MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa WHERE npa.SURVEYUID = :uid";
SQLQuery query = session.createSQLQuery(sql);
query.setString("uid", uid);
List> res = (List>) query.list();
- if (res.size() > 0) return ConversionTools.getValue(res.get(0));
+ if (res.size() > 0)
+ return ConversionTools.getValue(res.get(0));
return 0;
}
-
+
private Map getLanguageMap() {
- return getLanguages()
- .stream()
- .collect(Collectors.toMap(Language::getId, l -> l));
+ return getLanguages().stream().collect(Collectors.toMap(Language::getId, l -> l));
}
-
+
@SuppressWarnings("unchecked")
private List