Index: lams_build/lib/lams/lams-monitoring.jar =================================================================== diff -u -raead34144651a924f76d7bca8645327e6820d226 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 Binary files differ Index: lams_build/lib/lams/lams.jar =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 Binary files differ Index: lams_central/src/java/org/lamsfoundation/lams/authoring/web/AuthoringAction.java =================================================================== diff -u -re15d2e51298e68fff7ee35cd7d85e34faf1951a2 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_central/src/java/org/lamsfoundation/lams/authoring/web/AuthoringAction.java (.../AuthoringAction.java) (revision e15d2e51298e68fff7ee35cd7d85e34faf1951a2) +++ lams_central/src/java/org/lamsfoundation/lams/authoring/web/AuthoringAction.java (.../AuthoringAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -60,9 +60,7 @@ import org.lamsfoundation.lams.learningdesign.service.ILearningDesignService; import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.monitoring.service.IMonitoringService; -import org.lamsfoundation.lams.monitoring.web.MonitoringAction; import org.lamsfoundation.lams.security.ISecurityService; -import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.tool.IToolVO; import org.lamsfoundation.lams.tool.ToolContentManager; import org.lamsfoundation.lams.tool.ToolOutputDefinition; @@ -489,12 +487,9 @@ String contentFolderID = request.getParameter(AttributeNames.PARAM_CONTENT_FOLDER_ID); Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); Integer userID = getUserId(); - - try { - getSecurityService().hasOrgRole(organisationID, userID, Role.MONITOR); - } catch (SecurityException e) { - log.error("Cannot add a lesson", e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given lesson"); + + if (!getSecurityService().isGroupMonitor(organisationID, userID, "create single activity lesson", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); return null; } Index: lams_central/src/java/org/lamsfoundation/lams/web/DisplayGroupAction.java =================================================================== diff -u -r38b5da8f9b986f835a4dde123bd09954a4b6e171 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_central/src/java/org/lamsfoundation/lams/web/DisplayGroupAction.java (.../DisplayGroupAction.java) (revision 38b5da8f9b986f835a4dde123bd09954a4b6e171) +++ lams_central/src/java/org/lamsfoundation/lams/web/DisplayGroupAction.java (.../DisplayGroupAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -49,7 +49,6 @@ import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.lesson.service.LessonService; import org.lamsfoundation.lams.security.ISecurityService; -import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.usermanagement.Organisation; import org.lamsfoundation.lams.usermanagement.OrganisationState; import org.lamsfoundation.lams.usermanagement.OrganisationType; @@ -92,15 +91,13 @@ if (org != null) { User user = getUser(request.getRemoteUser()); - try { - getSecurityService().hasOrgRole(orgId, user.getUserId(), Role.LEARNER, Role.MONITOR, Role.AUTHOR, - Role.GROUP_MANAGER); - } catch (SecurityException e) { - log.error("Cannot display group", e); + if (!getSecurityService().hasOrgRole(orgId, user.getUserId(), + new String[] { Role.LEARNER, Role.MONITOR, Role.AUTHOR }, "display group", false) + && !getSecurityService().isGroupManager(orgId, user.getUserId(), "display group", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a part of the organisation"); return null; } - + boolean allowSorting = false; List roles = new ArrayList(); List userOrganisationRoles = getService().getUserOrganisationRoles(orgId, Index: lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java =================================================================== diff -u -r38b5da8f9b986f835a4dde123bd09954a4b6e171 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java (.../HomeAction.java) (revision 38b5da8f9b986f835a4dde123bd09954a4b6e171) +++ lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java (.../HomeAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -58,7 +58,6 @@ import org.lamsfoundation.lams.lesson.service.ILessonService; import org.lamsfoundation.lams.lesson.util.LessonDTOComparator; import org.lamsfoundation.lams.security.ISecurityService; -import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.usermanagement.Organisation; import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.User; @@ -337,11 +336,8 @@ UserDTO userDTO = getUser(); Integer organisationID = new Integer(WebUtil.readIntParam(req, "organisationID")); - try { - getSecurityService().hasOrgRole(organisationID, userDTO.getUserID(), Role.MONITOR, Role.GROUP_MANAGER); - } catch (SecurityException e) { - HomeAction.log.error("Cannot add lesson", e); - res.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given lesson"); + if (!getSecurityService().isGroupMonitor(organisationID, userDTO.getUserID(), "add lesson", false)) { + res.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); return null; } Index: lams_common/src/java/org/lamsfoundation/lams/commonContext.xml =================================================================== diff -u -r38b5da8f9b986f835a4dde123bd09954a4b6e171 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/commonContext.xml (.../commonContext.xml) (revision 38b5da8f9b986f835a4dde123bd09954a4b6e171) +++ lams_common/src/java/org/lamsfoundation/lams/commonContext.xml (.../commonContext.xml) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -301,6 +301,7 @@ + @@ -309,7 +310,8 @@ true - PROPAGATION_REQUIRED,readOnly + PROPAGATION_REQUIRED,readOnly + PROPAGATION_REQUIRED,readOnly Index: lams_common/src/java/org/lamsfoundation/lams/security/ISecurityDAO.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/security/ISecurityDAO.java (.../ISecurityDAO.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_common/src/java/org/lamsfoundation/lams/security/ISecurityDAO.java (.../ISecurityDAO.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -31,9 +31,11 @@ boolean hasOrgRole(Integer orgId, Integer userId, String... roles); + boolean isGroupManager(Integer orgId, Integer userId); + boolean isLessonLearner(Long lessonId, Integer userId); - boolean isLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted, boolean groupManagerAccepted); + boolean isLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted); boolean isSysadmin(Integer userId); } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/security/ISecurityService.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/security/ISecurityService.java (.../ISecurityService.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_common/src/java/org/lamsfoundation/lams/security/ISecurityService.java (.../ISecurityService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -26,34 +26,39 @@ public interface ISecurityService { /** - * Checks if the user is a learner in the given lesson. + * Checks if the is a manager of the class or ogranisation. */ - void checkIsLessonLearner(Long lessonId, Integer userId) throws SecurityException; + boolean isGroupManager(Integer orgId, Integer userId, String action, boolean escalate) throws SecurityException; /** - * Checks if the user is a staff member in the given lesson. + * Checks if the is a manager or monitor in the organisation. */ - void checkIsLessonMonitor(Long lessonId, Integer userId) throws SecurityException; + boolean isGroupMonitor(Integer orgId, Integer userId, String action, boolean escalate) throws SecurityException; /** - * Checks if the user is a staff member or optionally the owner of the given lesson, or a group manager of the - * organisation the lesson belongs to. + * Checks if the user is a learner in the given lesson. */ - void checkIsLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted, boolean groupManagerAccepted) - throws SecurityException; + boolean isLessonLearner(Long lessonId, Integer userId, String action, boolean escalate) throws SecurityException; /** + * Checks if the user is a monitor or owner of the given lesson, or a group manager of the organisation. + */ + boolean isLessonMonitor(Long lessonId, Integer userId, String action, boolean escalate) throws SecurityException; + + /** * Checks if the user is either a learner or a staff member in the given lesson. */ - void checkIsLessonParticipant(Long lessonId, Integer userId) throws SecurityException; + boolean isLessonParticipant(Long lessonId, Integer userId, String action, boolean escalate) + throws SecurityException; /** * Checks if the user has a global role of SYSADMIN. */ - void checkIsSysadmin(Integer userId); + boolean isSysadmin(Integer userId, String action, boolean escalate); /** * Checks if the user has any of the given roles in the given organisation. */ - void hasOrgRole(Integer orgId, Integer userId, String... roles) throws SecurityException; + boolean hasOrgRole(Integer orgId, Integer userId, String[] roles, String action, boolean escalate) + throws SecurityException; } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/security/SecurityDAO.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/security/SecurityDAO.java (.../SecurityDAO.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_common/src/java/org/lamsfoundation/lams/security/SecurityDAO.java (.../SecurityDAO.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -84,6 +84,18 @@ } @Override + public boolean isGroupManager(Integer orgId, Integer userId) { + Organisation organisation = (Organisation) find(Organisation.class, orgId); + if (organisation == null) { + return false; + } + if (OrganisationType.CLASS_TYPE.equals(organisation.getOrganisationType().getOrganisationTypeId())) { + organisation = organisation.getParentOrganisation(); + } + return hasOrgRole(organisation.getOrganisationId(), userId, Role.GROUP_MANAGER); + } + + @Override public boolean isLessonLearner(Long lessonId, Integer userId) { SQLQuery query = getHibernateTemplate().getSessionFactory().getCurrentSession() .createSQLQuery(SecurityDAO.CHECK_LESSON_LEARNER); @@ -93,26 +105,14 @@ } @Override - public boolean isLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted, boolean groupManagerAccepted) { + public boolean isLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted) { boolean result = !getHibernateTemplate().find(SecurityDAO.CHECK_LESSON_MONITOR, new Object[] { lessonId, userId }).isEmpty(); Lesson lesson = null; if (!result && ownerAccepted) { lesson = (Lesson) find(Lesson.class, lessonId); - result = lesson != null && userId.equals(lesson.getUser().equals(userId)); + result = (lesson != null) && userId.equals(lesson.getUser().getUserId()); } - if (!result && groupManagerAccepted) { - if (lesson == null) { - lesson = (Lesson) find(Lesson.class, lessonId); - } - if (lesson != null) { - Organisation organisation = lesson.getOrganisation(); - if (OrganisationType.CLASS_TYPE.equals(organisation.getOrganisationType().getOrganisationTypeId())) { - organisation = organisation.getParentOrganisation(); - } - result = hasOrgRole(organisation.getOrganisationId(), userId, Role.GROUP_MANAGER); - } - } return result; } Index: lams_common/src/java/org/lamsfoundation/lams/security/SecurityService.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/security/SecurityService.java (.../SecurityService.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_common/src/java/org/lamsfoundation/lams/security/SecurityService.java (.../SecurityService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -28,111 +28,339 @@ import org.apache.log4j.Logger; import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.usermanagement.Role; +import org.lamsfoundation.lams.util.audit.IAuditService; +/** + * Contains methods for checking and logging user access to LAMS content. Should be used throughout the whole project. + * Calls with escalate=false are for soft checking in Actions. Onet with escalate=true are for checking in Services so + * the exception can bubble to Actions. + */ public class SecurityService implements ISecurityService { + private static Logger log = Logger.getLogger(SecurityService.class); + private static final String SECURITY_MODULE_NAME = "security"; + private ISecurityDAO securityDAO; + private IAuditService auditService; - private static Logger log = Logger.getLogger(SecurityService.class); - @Override - public void checkIsLessonLearner(Long lessonId, Integer userId) throws SecurityException { + public boolean isLessonLearner(Long lessonId, Integer userId, String action, boolean escalate) + throws SecurityException { if (lessonId == null) { - throw new SecurityException("Lesson ID is NULL"); + String error = "Missing lesson ID when checking if user " + userId + " is learner and can \"" + action + + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } if (userId == null) { - throw new SecurityException("User ID is NULL"); + String error = "Missing user ID when checking if is learner in lesson " + lessonId + " and can \"" + action + + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } Lesson lesson = (Lesson) securityDAO.find(Lesson.class, lessonId); if (lesson == null) { - throw new SecurityException("Could not find lesson with ID: " + lessonId); + String error = "Could not find lesson " + lessonId + " when checking if user " + userId + + " is learner and can \"" + action + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } - hasOrgRole(lesson.getOrganisation().getOrganisationId(), userId, Role.LEARNER, Role.MONITOR); + Integer orgId = lesson.getOrganisation().getOrganisationId(); + boolean hasSysadminRole = securityDAO.isSysadmin(userId); + boolean hasOrgRole = securityDAO.hasOrgRole(orgId, userId, Role.LEARNER); - if (!securityDAO.isSysadmin(userId) && !securityDAO.isLessonLearner(lessonId, userId)) { - throw new SecurityException("User with ID: " + userId + " is not a learner in lesson with ID: " + lessonId); + if (!hasSysadminRole && !(hasOrgRole && securityDAO.isLessonLearner(lessonId, userId))) { + String error = "User " + userId + " is not learner in lesson " + lessonId + " and can not \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } - } - @Override - public void checkIsLessonMonitor(Long lessonId, Integer userId) throws SecurityException { - checkIsLessonMonitor(lessonId, userId, false, false); + return true; } @Override - public void checkIsLessonMonitor(Long lessonId, Integer userId, boolean ownerAccepted, boolean groupManagerAccepted) + public boolean isLessonMonitor(Long lessonId, Integer userId, String action, boolean escalate) throws SecurityException { if (lessonId == null) { - throw new SecurityException("Lesson ID is NULL"); + String error = "Missing lesson ID when checking if user " + userId + " is monitor and can \"" + action + + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } if (userId == null) { - throw new SecurityException("User ID is NULL"); + String error = "Missing user ID when checking if is monitor in lesson " + lessonId + " and can \"" + action + + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } Lesson lesson = (Lesson) securityDAO.find(Lesson.class, lessonId); if (lesson == null) { - throw new SecurityException("Could not find lesson with ID: " + lessonId); + String error = "Could not find lesson " + lessonId + " when checking if user " + userId + + " is monitor and can \"" + action + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } - hasOrgRole(lesson.getOrganisation().getOrganisationId(), userId, Role.MONITOR, Role.GROUP_MANAGER); + Integer orgId = lesson.getOrganisation().getOrganisationId(); + boolean hasSysadminRole = securityDAO.isSysadmin(userId); + boolean hasGroupManagerRole = hasSysadminRole || securityDAO.isGroupManager(orgId, userId); + boolean hasMonitorRole = hasGroupManagerRole || securityDAO.hasOrgRole(orgId, userId, Role.MONITOR); - if (!securityDAO.isSysadmin(userId) - && !securityDAO.isLessonMonitor(lessonId, userId, ownerAccepted, groupManagerAccepted)) { - throw new SecurityException("User with ID: " + userId + " is not a monitor in lesson with ID: " + lessonId); + if (!hasGroupManagerRole && !(hasMonitorRole && securityDAO.isLessonMonitor(lessonId, userId, true))) { + String error = "User " + userId + " is not monitor in lesson " + lessonId + " and can not \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } + + return true; } @Override - public void checkIsLessonParticipant(Long lessonId, Integer userId) throws SecurityException { + public boolean isLessonParticipant(Long lessonId, Integer userId, String action, boolean escalate) + throws SecurityException { if (lessonId == null) { - throw new SecurityException("Lesson ID is NULL"); + String error = "Missing lesson ID when checking if user " + userId + " is participant and can \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } if (userId == null) { - throw new SecurityException("User ID is NULL"); + String error = "Missing user ID when checking if is participant in lesson " + lessonId + " and can \"" + + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } Lesson lesson = (Lesson) securityDAO.find(Lesson.class, lessonId); if (lesson == null) { - throw new SecurityException("Could not find lesson with ID: " + lessonId); + String error = "Could not find lesson " + lessonId + " when checking if user " + userId + + " is participant and can \"" + action + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } - hasOrgRole(lesson.getOrganisation().getOrganisationId(), userId, Role.LEARNER, Role.MONITOR, Role.GROUP_MANAGER); + Integer orgId = lesson.getOrganisation().getOrganisationId(); + boolean hasSysadminRole = securityDAO.isSysadmin(userId); + boolean hasGroupManagerRole = hasSysadminRole || securityDAO.isGroupManager(orgId, userId); + boolean hasRole = hasGroupManagerRole || securityDAO.hasOrgRole(orgId, userId, Role.LEARNER, Role.MONITOR); - if (!securityDAO.isSysadmin(userId) && !securityDAO.isLessonLearner(lessonId, userId) - && !securityDAO.isLessonMonitor(lessonId, userId, true, false)) { - throw new SecurityException("User with ID: " + userId + " is not a learner in lesson with ID: " + lessonId); + if (!hasGroupManagerRole + && !(hasRole && (securityDAO.isLessonLearner(lessonId, userId) || securityDAO.isLessonMonitor(lessonId, + userId, true)))) { + String error = "User " + userId + " is not participant in lesson " + lessonId + " and can not \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } + + return true; } @Override - public void checkIsSysadmin(Integer userId) { + public boolean isSysadmin(Integer userId, String action, boolean escalate) { if (userId == null) { - throw new SecurityException("User ID is NULL"); + String error = "Missing user ID when checking if is sysadmin and can \"" + action + "\""; + SecurityService.log.error(error); + throw new SecurityException(error); } if (!securityDAO.isSysadmin(userId)) { - throw new SecurityException("User with ID: " + userId + " is not a sysadmin."); + String error = "User " + userId + " is not sysadmin and can not \"" + action + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } + + return true; } @Override - public void hasOrgRole(Integer orgId, Integer userId, String... roles) throws SecurityException { + public boolean isGroupManager(Integer orgId, Integer userId, String action, boolean escalate) + throws SecurityException { if (orgId == null) { - throw new SecurityException("Organisation ID is NULL"); + String error = "Missing organisation ID when checking if user is a manager of organisation " + orgId + + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } if (userId == null) { - throw new SecurityException("User ID is NULL"); + String error = "Missing user ID when checking if user is a manager of organisation " + orgId + + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } + if (!securityDAO.isSysadmin(userId) && !securityDAO.isGroupManager(orgId, userId)) { + String error = "User " + userId + " is not a manager of organisation " + orgId + " and can not \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + + return true; + } + + @Override + public boolean isGroupMonitor(Integer orgId, Integer userId, String action, boolean escalate) + throws SecurityException { + if (orgId == null) { + String error = "Missing organisation ID when checking if user is a monitor in organisation " + orgId + + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + if (userId == null) { + String error = "Missing user ID when checking if user is a monitor in organisation " + orgId + + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + + if (!securityDAO.isSysadmin(userId) && !securityDAO.isGroupManager(orgId, userId) + && !securityDAO.hasOrgRole(orgId, userId, Role.MONITOR)) { + String error = "User " + userId + " is not a monitor in organisation " + orgId + " and can not \"" + action + + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + + return true; + } + + @Override + public boolean hasOrgRole(Integer orgId, Integer userId, String[] roles, String action, boolean escalate) + throws SecurityException { + if (orgId == null) { + String error = "Missing organisation ID when checking if user " + userId + " has any of " + + Arrays.toString(roles) + " roles in organisation " + orgId + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + if (userId == null) { + String error = "Missing user ID when checking if has any of " + Arrays.toString(roles) + + " roles in organisation " + orgId + " and can \"" + action + "\""; + SecurityService.log.error(error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } + } + if (!securityDAO.isSysadmin(userId) && !securityDAO.hasOrgRole(orgId, userId, roles)) { - throw new SecurityException("User with ID: " + userId + " is not any of " + Arrays.toString(roles) - + " in organisation with ID: " + orgId); + String error = "User " + userId + " does not have any of " + Arrays.toString(roles) + + " roles in organisation " + orgId + " and can not \"" + action + "\""; + SecurityService.log.error(error); + auditService.log(SecurityService.SECURITY_MODULE_NAME, error); + if (escalate) { + throw new SecurityException(error); + } else { + return false; + } } + + return true; } public void setSecurityDAO(ISecurityDAO securityDAO) { this.securityDAO = securityDAO; } + + public void setAuditService(IAuditService auditService) { + this.auditService = auditService; + } } \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java =================================================================== diff -u -r279ab8b6c6d02f80bb949e44011343f6c7150f6e -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java (.../ILamsCoreToolService.java) (revision 279ab8b6c6d02f80bb949e44011343f6c7150f6e) +++ lams_common/src/java/org/lamsfoundation/lams/tool/service/ILamsCoreToolService.java (.../ILamsCoreToolService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -77,24 +77,8 @@ */ ToolSession createToolSession(User learner, ToolActivity activity, Lesson lesson) throws DataIntegrityViolationException, RequiredGroupMissingException; - + /** - * Creates LAMS ToolSessions for a set of learners and activity. Checks to see if an appropriate tool session exists - * for each learner before creating the tool session. - *

- * If an appropriate tool session already exists for a learner, then it does not include the tool session in the - * returned set. - *

- * - * @param learners - * the learners who are running the activity. - * @param activity - * the requested activity. - * @return toolSessions set of newly created ToolSessions - */ - Set createToolSessions(Set learners, ToolActivity activity, Lesson lesson) throws LamsToolServiceException; - - /** * Returns the previously created ToolSession for a learner and activity. It is queried base on learner. * * @param learner Index: lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java =================================================================== diff -u -r279ab8b6c6d02f80bb949e44011343f6c7150f6e -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision 279ab8b6c6d02f80bb949e44011343f6c7150f6e) +++ lams_common/src/java/org/lamsfoundation/lams/tool/service/LamsCoreToolService.java (.../LamsCoreToolService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -156,23 +156,6 @@ } @Override - public Set createToolSessions(Set learners, ToolActivity activity, Lesson lesson) throws LamsToolServiceException { - Iterator iter = learners.iterator(); - Set newToolSessions = new HashSet(); - while (iter.hasNext()) { - // set up the new tool session. createToolSession() will see if it really - // needs to be created - if not will return an existing session. - User learner = (User) iter.next(); - ToolSession toolSession = createToolSession(learner, activity, lesson); - if (toolSession != null) { - newToolSessions.add(toolSession); - } - } - - return newToolSessions; - } - - @Override public ToolSession getToolSessionByLearner(User learner, Activity activity) throws LamsToolServiceException { return toolSessionDAO.getToolSessionByLearner(learner, activity); } Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java =================================================================== diff -u -r38b5da8f9b986f835a4dde123bd09954a4b6e171 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 38b5da8f9b986f835a4dde123bd09954a4b6e171) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -48,7 +48,6 @@ import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.lesson.service.ILessonService; import org.lamsfoundation.lams.security.ISecurityService; -import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.usermanagement.Organisation; import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.User; @@ -64,11 +63,10 @@ /** * @author lfoxton * - * Handles the general requests for content in gradebook + * Handles the general requests for content in gradebook * * - * @struts.action path="/gradebook" parameter="dispatch" - * scope="request" validate="false" + * @struts.action path="/gradebook" parameter="dispatch" scope="request" validate="false" * * @struts:action-forward name="error" path=".error" * @struts:action-forward name="message" path=".message" @@ -82,6 +80,7 @@ private static ILessonService lessonService; private static ISecurityService securityService; + @Override public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return null; @@ -92,11 +91,10 @@ * * This has two modes, userView and activityView * - * User view will get the grid data for a specified user, which is all their - * activity marks/outputs etc + * User view will get the grid data for a specified user, which is all their activity marks/outputs etc * - * Activity view will get the grid data for all activities, without user - * info, instead there is an average mark for each activity + * Activity view will get the grid data for all activities, without user info, instead there is an average mark for + * each activity * * @param mapping * @param form @@ -105,7 +103,6 @@ * @return * @throws Exception */ - @SuppressWarnings(value = { "unchecked", "unused" }) public ActionForward getActivityGridData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Getting the params passed in from the jqGrid @@ -120,53 +117,50 @@ GBGridView view = GradebookUtil.readGBGridViewParam(request, GradebookConstants.PARAM_VIEW, false); Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - + if (!getSecurityService().isLessonParticipant(lessonID, getUser().getUserID(), "get activity gradebook data", + false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a learner in the lesson"); + return null; + } + // Getting userID param, it is passed differently from different views Integer userID = null; if (view == GBGridView.MON_USER) { userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); } else if (view == GBGridView.LRN_ACTIVITY) { - UserDTO userDTO = getUser(); if (userDTO != null) { userID = userDTO.getUserID(); } } - + Lesson lesson = getLessonService().getLesson(lessonID); + List gradebookActivityDTOs = new ArrayList(); - if (lesson != null) { - - List gradebookActivityDTOs = new ArrayList(); - - // Get the user gradebook list from the db - // A slightly different list is needed for userview or activity view - if (view == GBGridView.MON_USER || view == GBGridView.LRN_ACTIVITY) { - //Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); - User learner = (User) getUserService().findById(User.class, userID); - if (learner != null) { - gradebookActivityDTOs = getGradebookService().getGBActivityRowsForLearner(lesson, learner); - } else { - // return null and the grid will report the error - logger.error("No learner found for: " + userID); - return null; - } - } else if (view == GBGridView.MON_ACTIVITY) { - gradebookActivityDTOs = getGradebookService().getGBActivityRowsForLesson(lesson); + // Get the user gradebook list from the db + // A slightly different list is needed for userview or activity view + if ((view == GBGridView.MON_USER) || (view == GBGridView.LRN_ACTIVITY)) { + // Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); + User learner = (User) getUserService().findById(User.class, userID); + if (learner != null) { + gradebookActivityDTOs = getGradebookService().getGBActivityRowsForLearner(lesson, learner); + } else { + // return null and the grid will report the error + GradebookAction.logger.error("No learner found for: " + userID); + return null; } + } else if (view == GBGridView.MON_ACTIVITY) { + gradebookActivityDTOs = getGradebookService().getGBActivityRowsForLesson(lesson); + } - if (sortBy == null || sortBy.equals("")) { - sortBy = GradebookConstants.PARAM_START_DATE; - } - - String ret = GradebookUtil.toGridXML(gradebookActivityDTOs, view, sortBy, isSearch, searchField, - searchOper, searchString, sortOrder, rowLimit, page); - - writeResponse(response, CONTENT_TYPE_TEXT_XML, ENCODING_UTF8, ret); - } else { - logger.error("No lesson could be found for: " + lessonID); + if ((sortBy == null) || sortBy.equals("")) { + sortBy = GradebookConstants.PARAM_START_DATE; } + String ret = GradebookUtil.toGridXML(gradebookActivityDTOs, view, sortBy, isSearch, searchField, searchOper, + searchString, sortOrder, rowLimit, page); + + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_XML, LamsDispatchAction.ENCODING_UTF8, ret); return null; } @@ -190,7 +184,6 @@ * @return * @throws Exception */ - @SuppressWarnings("unchecked") public ActionForward getUserGridData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { @@ -213,81 +206,64 @@ // if leesonID is specified show results based on lesson if (lessonID != null) { - Lesson lesson = getLessonService().getLesson(lessonID); - if (lesson == null) { - logger.error("No lesson could be found for: " + lessonID); + if (!getSecurityService().isLessonMonitor(lessonID, user.getUserID(), "get gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); return null; } - - try { - getSecurityService().checkIsLessonMonitor(lessonID, user.getUserID()); - } catch (SecurityException e) { - log.error("Cannot get gradebook", e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given lesson"); - return null; - } - - if (view == GBGridView.MON_USER || view == GBGridView.MON_COURSE) { + + Lesson lesson = getLessonService().getLesson(lessonID); + if ((view == GBGridView.MON_USER) || (view == GBGridView.MON_COURSE)) { gradebookUserDTOs = getGradebookService().getGBUserRowsForLesson(lesson); } else if (view == GBGridView.MON_ACTIVITY) { String rowID = WebUtil.readStrParam(request, AttributeNames.PARAM_ACTIVITY_ID); - + Long activityID = null; - + // Splitting the rowID param to get the activity/group id pair String[] split = rowID.split("_"); if (split.length == 2) { activityID = Long.parseLong(split[0]); } else { activityID = Long.parseLong(rowID); } - + // Getting the group id if it is there Long groupId = WebUtil.readLongParam(request, GradebookConstants.PARAM_GROUP_ID, true); - + Activity activity = getGradebookService().getActivityById(activityID); - if (activity != null && activity instanceof ToolActivity) { - gradebookUserDTOs = getGradebookService().getGBUserRowsForActivity(lesson, (ToolActivity)activity, groupId); + if ((activity != null) && (activity instanceof ToolActivity)) { + gradebookUserDTOs = getGradebookService().getGBUserRowsForActivity(lesson, (ToolActivity) activity, + groupId); } else { // return null and the grid will report an error - logger.error("No activity found for: " + activityID); + GradebookAction.logger.error("No activity found for: " + activityID); return null; } } - - //if organisationID is specified (but not lessonID) then show results for organisation + + // if organisationID is specified (but not lessonID) then show results for organisation } else if (organisationID != null) { - - Organisation org = (Organisation) getUserService().findById(Organisation.class, organisationID); - if (org == null) { - logger.error("No organisation could be found for: " + organisationID); + if (!getSecurityService().isGroupMonitor(organisationID, user.getUserID(), "get gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); return null; } - - try { - getSecurityService().hasOrgRole(organisationID, user.getUserID(), Role.MONITOR); - } catch (SecurityException e) { - log.error(e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given organisation"); - return null; - } + Organisation org = (Organisation) getUserService().findById(Organisation.class, organisationID); gradebookUserDTOs = getGradebookService().getGBUserRowsForOrganisation(org); - } else { - logger.error("Missing parameters: either lessonID or organisationID should be specified."); - return null; + LamsDispatchAction.log.error("Missing parameters: either lessonID or organisationID should be specified."); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters"); + return null; } String ret = GradebookUtil.toGridXML(gradebookUserDTOs, view, sortBy, isSearch, searchField, searchOper, searchString, sortOrder, rowLimit, page); - writeResponse(response, CONTENT_TYPE_TEXT_XML, ENCODING_UTF8, ret); + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_XML, LamsDispatchAction.ENCODING_UTF8, ret); return null; } /** - * Returns an xml representation of the lesson grid for a course for - * gradebook + * Returns an xml representation of the lesson grid for a course for gradebook * * This has two modes, learnerView and monitorView * @@ -317,34 +293,50 @@ GBGridView view = GradebookUtil.readGBGridViewParam(request, GradebookConstants.PARAM_VIEW, false); Integer courseID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); Organisation organisation = (Organisation) getUserService().findById(Organisation.class, courseID); - - // in case of toolbar searching (which uses different parameters than a single field searching) get those parameters + + // in case of toolbar searching (which uses different parameters than a single field searching) get those + // parameters if (isSearch && (searchField == null)) { searchField = GradebookConstants.PARAM_ROW_NAME; searchOper = GradebookConstants.SEARCH_CONTAINS; searchString = WebUtil.readStrParam(request, GradebookConstants.PARAM_ROW_NAME, true); } - - Set lessons = (Set) organisation.getLessons(); + + Set lessons = organisation.getLessons(); if (lessons == null) { return null; } - + User user; + User viewer = getRealUser(); if (view == GBGridView.MON_USER) { + if (!getSecurityService().isGroupMonitor(courseID, viewer.getUserId(), "get course gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); + return null; + } + Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); user = (User) getUserService().findById(User.class, userID); } else { + if (!getSecurityService().isGroupMonitor(courseID, viewer.getUserId(), "get course gradebook for learner", + false) + && !getSecurityService().hasOrgRole(courseID, viewer.getUserId(), new String[] { Role.LEARNER }, + "get course gradebook for learner", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a participant in the organisation"); + return null; + } + user = getRealUser(); } - User viewer = getRealUser(); - - if (organisation == null || user == null || viewer == null) { + + if ((organisation == null) || (user == null) || (viewer == null)) { // Grid will handle error, just log and return null - logger.error("Error: request for course gradebook data with null course or user. CourseID: " + courseID); + GradebookAction.logger + .error("Error: request for course gradebook data with null course or user. CourseID: " + courseID); return null; } - List gradebookLessonDTOs = getGradebookService().getGBLessonRows(organisation, user, viewer, view); + List gradebookLessonDTOs = getGradebookService().getGBLessonRows(organisation, user, + viewer, view); if (sortBy == null) { sortBy = GradebookConstants.PARAM_ID; @@ -354,13 +346,12 @@ String ret = GradebookUtil.toGridXML(gradebookLessonDTOs, view, sortBy, isSearch, searchField, searchOper, searchString, sortOrder, rowLimit, page); - writeResponse(response, CONTENT_TYPE_TEXT_XML, ENCODING_UTF8, ret); + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_XML, LamsDispatchAction.ENCODING_UTF8, ret); return null; } - + /** - * Gets the total mark for a user's lesson and writes the result in the - * response + * Gets the total mark for a user's lesson and writes the result in the response * * @param mapping * @param form @@ -369,29 +360,41 @@ * @return * @throws Exception */ - @SuppressWarnings("unchecked") public ActionForward getLessonMarkAggregate(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); + HttpServletResponse response) throws Exception { + Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); - Lesson lesson = getLessonService().getLesson(lessonID); - User learner = (User) getUserService().findById(User.class, userID); + if (getUser().getUserID().equals(userID)) { + if (!getSecurityService().isLessonParticipant(lessonID, userID, "get lesson mark aggregate", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a participant in the lesson"); + return null; + } + } else { + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), "get lesson mark aggregate", + false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + } + Lesson lesson = getLessonService().getLesson(lessonID); + User learner = (User) getUserService().findById(User.class, userID); - if (lesson != null && learner != null) { - GradebookUserLesson lessonMark = getGradebookService().getGradebookUserLesson(lessonID, userID); - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, GradebookUtil.niceFormatting(lessonMark.getMark())); - } else { - // Grid will handle error, just log and return null - logger.error("Error: request for course gradebook data with null user or lesson. lessonID: " + lessonID); - } - return null; + if ((lesson != null) && (learner != null)) { + GradebookUserLesson lessonMark = getGradebookService().getGradebookUserLesson(lessonID, userID); + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, + GradebookUtil.niceFormatting(lessonMark.getMark())); + } else { + // Grid will handle error, just log and return null + GradebookAction.logger + .error("Error: request for course gradebook data with null user or lesson. lessonID: " + lessonID); + } + return null; } - + /** - * Gets the average mark for an activity and writes the result in the - * response + * Gets the average mark for an activity and writes the result in the response * * @param mapping * @param form @@ -402,12 +405,12 @@ */ @SuppressWarnings("unchecked") public ActionForward getActivityMarkAverage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + HttpServletResponse response) throws Exception { String rowID = WebUtil.readStrParam(request, AttributeNames.PARAM_ACTIVITY_ID); - + Long activityID = null; Long groupID = null; - + // Splitting the rowID param to get the activity/group id pair String[] split = rowID.split("_"); if (split.length == 2) { @@ -416,24 +419,34 @@ } else { activityID = Long.parseLong(rowID); } - - Activity activity = getGradebookService().getActivityById(activityID); - - if (activity != null) { - Double averageMark = getGradebookService().getAverageMarkForActivity(activityID, groupID); - - if (averageMark != null) { - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, GradebookUtil.niceFormatting(averageMark)); - } else { - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, GradebookConstants.CELL_EMPTY); - } - } else { - // Grid will handle error, just log and return null - logger.error("Error: request for course gradebook data with null activity. actvity: " + activityID); - } - return null; + + Activity activity = getGradebookService().getActivityById(activityID); + if (activity == null) { + LamsDispatchAction.log.error("Activity with ID: " + activityID + + " could not be found when getting activity mark average"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters"); + return null; + } + Integer userID = getUser().getUserID(); + for (Lesson lesson : (Set) activity.getLearningDesign().getLessons()) { + if (!getSecurityService().isLessonMonitor(lesson.getLessonId(), userID, "get activity mark average", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + } + + Double averageMark = getGradebookService().getAverageMarkForActivity(activityID, groupID); + if (averageMark != null) { + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, + GradebookUtil.niceFormatting(averageMark)); + } else { + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, + GradebookConstants.CELL_EMPTY); + } + + return null; } - + /** * Gets the average mark for lesson and writes the result in the response * @@ -444,29 +457,27 @@ * @return * @throws Exception */ - @SuppressWarnings("unchecked") public ActionForward getLessonMarkAverage(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - Lesson lesson = getLessonService().getLesson(lessonID); - - if (lesson != null) { - Double averageMark = getGradebookService().getAverageMarkForLesson(lessonID); - - if (averageMark != null) { - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, GradebookUtil.niceFormatting(averageMark)); - } else { - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, GradebookConstants.CELL_EMPTY); - } - } else { - // Grid will handle error, just log and return null - logger.error("Error: request for course gradebook data with null lesson. lesson: " + lessonID); - } - return null; - } - + HttpServletResponse response) throws Exception { + Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), "get lesson mark average", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + Lesson lesson = getLessonService().getLesson(lessonID); + Double averageMark = getGradebookService().getAverageMarkForLesson(lessonID); + if (averageMark != null) { + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, + GradebookUtil.niceFormatting(averageMark)); + } else { + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, + GradebookConstants.CELL_EMPTY); + } + return null; + } + private UserDTO getUser() { HttpSession ss = SessionManager.getSession(); return (UserDTO) ss.getAttribute(AttributeNames.USER); @@ -482,30 +493,30 @@ } private IUserManagementService getUserService() { - if (userService == null) { + if (GradebookAction.userService == null) { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() .getServletContext()); - userService = (IUserManagementService) ctx.getBean("userManagementService"); + GradebookAction.userService = (IUserManagementService) ctx.getBean("userManagementService"); } - return userService; + return GradebookAction.userService; } private ILessonService getLessonService() { - if (lessonService == null) { + if (GradebookAction.lessonService == null) { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() .getServletContext()); - lessonService = (ILessonService) ctx.getBean("lessonService"); + GradebookAction.lessonService = (ILessonService) ctx.getBean("lessonService"); } - return lessonService; + return GradebookAction.lessonService; } private IGradebookService getGradebookService() { - if (gradebookService == null) { + if (GradebookAction.gradebookService == null) { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() .getServletContext()); - gradebookService = (IGradebookService) ctx.getBean("gradebookService"); + GradebookAction.gradebookService = (IGradebookService) ctx.getBean("gradebookService"); } - return gradebookService; + return GradebookAction.gradebookService; } private ISecurityService getSecurityService() { @@ -517,4 +528,4 @@ return GradebookAction.securityService; } -} +} \ No newline at end of file Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookLearningAction.java =================================================================== diff -u -rcd5cef591859ae82025af74f79cf6bf6f9151568 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookLearningAction.java (.../GradebookLearningAction.java) (revision cd5cef591859ae82025af74f79cf6bf6f9151568) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookLearningAction.java (.../GradebookLearningAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -18,11 +18,11 @@ * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** - */ - -/* $Id$ */ -package org.lamsfoundation.lams.gradebook.web.action; + */ +/* $Id$ */ +package org.lamsfoundation.lams.gradebook.web.action; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -31,8 +31,7 @@ import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; -import org.lamsfoundation.lams.gradebook.service.IGradebookService; -import org.lamsfoundation.lams.lesson.service.ILessonService; +import org.lamsfoundation.lams.security.ISecurityService; import org.lamsfoundation.lams.usermanagement.Organisation; import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; @@ -47,115 +46,83 @@ /** * @author lfoxton * - * Handles the learner interfaces for gradebook + * Handles the learner interfaces for gradebook * - * This is where marking for an activity/lesson takes place + * This is where marking for an activity/lesson takes place * * - * @struts.action path="/gradebookLearning" parameter="dispatch" - * scope="request" validate="false" + * @struts.action path="/gradebookLearning" parameter="dispatch" scope="request" validate="false" * - * @struts:action-forward name="learnercoursegradebook" - * path="/gradebookCourseLearner.jsp" + * @struts:action-forward name="learnercoursegradebook" path="/gradebookCourseLearner.jsp" * @struts:action-forward name="error" path=".error" * @struts:action-forward name="message" path=".message" */ -public class GradebookLearningAction extends LamsDispatchAction{ - +public class GradebookLearningAction extends LamsDispatchAction { + private static Logger logger = Logger.getLogger(GradebookLearningAction.class); - - private static IGradebookService gradebookService; + private static IUserManagementService userService; - private static ILessonService lessonService; + private static ISecurityService securityService; + @Override public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return null; } - - @SuppressWarnings("unchecked") + public ActionForward courseLearner(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { - initServices(); Integer oranisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); - - logger.debug("request learnerGradebook for organisation: " + oranisationID.toString()); UserDTO user = getUser(); if (user == null) { - logger.error("User missing from session. "); + GradebookLearningAction.logger.error("User missing from session. "); return mapping.findForward("error"); - } else { - - Organisation organisation = (Organisation)userService.findById(Organisation.class, oranisationID); - if (organisation == null) { - logger.error("Organisation " + oranisationID + " does not exist. Unable to load gradebook"); - return mapping.findForward("error"); - } - - // Validate whether this user is a monitor for this organisation - if (!userService.isUserInRole(user.getUserID(), oranisationID, Role.LEARNER)) { - logger.error("User " + user.getLogin() - + " is not a learner in the requested course. Cannot access the course for gradebook."); - return displayMessage(mapping, request, "error.authorisation"); - } - - request.setAttribute("organisationID", oranisationID); - request.setAttribute("organisationName", organisation.getName()); - request.setAttribute("fullName",user.getFirstName() + " " + user.getLastName()); - - - return mapping.findForward("learnercoursegradebook"); } + if (!getSecurityService().isGroupMonitor(oranisationID, user.getUserID(), "get learner course gradebook", + false) + && !getSecurityService().hasOrgRole(oranisationID, user.getUserID(), new String[] { Role.LEARNER }, + "get course gradebook for learner", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a participant in the organisation"); + return null; + } + if (LamsDispatchAction.log.isDebugEnabled()) { + GradebookLearningAction.logger.debug("Getting learner gradebook for organisation: " + oranisationID); + } + + Organisation organisation = (Organisation) getUserService().findById(Organisation.class, oranisationID); + request.setAttribute("organisationID", oranisationID); + request.setAttribute("organisationName", organisation.getName()); + request.setAttribute("fullName", user.getFirstName() + " " + user.getLastName()); + + return mapping.findForward("learnercoursegradebook"); } catch (Exception e) { - logger.error("Failed to load gradebook monitor", e); + GradebookLearningAction.logger.error("Failed to load learner gradebook", e); return mapping.findForward("error"); } } - + private UserDTO getUser() { HttpSession ss = SessionManager.getSession(); return (UserDTO) ss.getAttribute(AttributeNames.USER); } - - private ActionForward displayMessage(ActionMapping mapping, HttpServletRequest req, String messageKey) { - req.setAttribute("messageKey", messageKey); - return mapping.findForward("message"); - } - private void initServices() { - getUserService(); - getLessonService(); - getGradebookService(); - } - private IUserManagementService getUserService() { - if (userService == null) { + if (GradebookLearningAction.userService == null) { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() .getServletContext()); - userService = (IUserManagementService) ctx.getBean("userManagementService"); + GradebookLearningAction.userService = (IUserManagementService) ctx.getBean("userManagementService"); } - return userService; + return GradebookLearningAction.userService; } - private ILessonService getLessonService() { - if (lessonService == null) { + private ISecurityService getSecurityService() { + if (GradebookLearningAction.securityService == null) { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() .getServletContext()); - lessonService = (ILessonService) ctx.getBean("lessonService"); + GradebookLearningAction.securityService = (ISecurityService) ctx.getBean("securityService"); } - return lessonService; + return GradebookLearningAction.securityService; } - - private IGradebookService getGradebookService() { - if (gradebookService == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() - .getServletContext()); - gradebookService = (IGradebookService) ctx.getBean("gradebookService"); - } - return gradebookService; - } - -} - +} \ No newline at end of file Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java =================================================================== diff -u -r3e36623a35a8f471dcf3a6b0de9eca8006a881e1 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java (.../GradebookMonitoringAction.java) (revision 3e36623a35a8f471dcf3a6b0de9eca8006a881e1) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java (.../GradebookMonitoringAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -23,6 +23,7 @@ /* $Id$ */ package org.lamsfoundation.lams.gradebook.web.action; +import java.util.Arrays; import java.util.LinkedHashMap; import javax.servlet.ServletOutputStream; @@ -43,8 +44,8 @@ import org.lamsfoundation.lams.lesson.Lesson; import org.lamsfoundation.lams.lesson.dto.LessonDetailsDTO; import org.lamsfoundation.lams.lesson.service.ILessonService; +import org.lamsfoundation.lams.security.ISecurityService; import org.lamsfoundation.lams.usermanagement.Organisation; -import org.lamsfoundation.lams.usermanagement.Role; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; @@ -55,7 +56,6 @@ import org.lamsfoundation.lams.web.action.LamsDispatchAction; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; -import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; @@ -67,8 +67,8 @@ * This is where marking for an activity/lesson takes place * * - * @struts.action path="/gradebookMonitoring" parameter="dispatch" scope="request" - * name="monitoringForm" validate="false" + * @struts.action path="/gradebookMonitoring" parameter="dispatch" scope="request" name="monitoringForm" + * validate="false" * * @struts:action-forward name="monitorgradebook" path="/gradebookMonitor.jsp" * @struts:action-forward name="monitorcoursegradebook" path="/gradebookCourseMonitor.jsp" @@ -77,194 +77,187 @@ */ public class GradebookMonitoringAction extends LamsDispatchAction { - private static Logger logger = Logger.getLogger(GradebookMonitoringAction.class); + private static Logger log = Logger.getLogger(GradebookMonitoringAction.class); - private static IGradebookService gradebookService; - private static IUserManagementService userService; - private static ILessonService lessonService; + private static IGradebookService gradebookService; + private static IUserManagementService userService; + private static ILessonService lessonService; + private static ISecurityService securityService; - @SuppressWarnings("unchecked") - public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + @Override + public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { + try { + Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + if (GradebookMonitoringAction.log.isDebugEnabled()) { + GradebookMonitoringAction.log.debug("Getting gradebook for lesson " + lessonId); + } + UserDTO user = getUser(); + if (user == null) { + GradebookMonitoringAction.log.error("User missing from session. "); + return mapping.findForward("error"); + } + if (!getSecurityService().isLessonMonitor(lessonId, user.getUserID(), "get lesson gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } - try { - initServices(); - Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - logger.debug("request monitorGradebook for lesson: " + lessonId.toString()); - UserDTO user = getUser(); - if (user == null) { - logger.error("User missing from session. "); - return mapping.findForward("error"); - } else { - Lesson lesson = lessonId != null ? lessonService.getLesson(lessonId) : null; - if (lesson == null) { - logger.error("Lesson " + lessonId + " does not exist. Unable to monitor lesson"); - return mapping.findForward("error"); - } + Lesson lesson = getLessonService().getLesson(lessonId); + boolean marksReleased = (lesson.getMarksReleased() != null) && lesson.getMarksReleased(); + LessonDetailsDTO lessonDetatilsDTO = lesson.getLessonDetails(); + request.setAttribute("lessonDetails", lessonDetatilsDTO); + request.setAttribute("marksReleased", marksReleased); - if (lesson.getLessonClass() == null || !lesson.getLessonClass().isStaffMember(getRealUser(user))) { - logger.error("User " + user.getLogin() - + " is not a monitor in the requested lesson. Cannot access the lesson for monitor."); - return displayMessage(mapping, request, "error.authorisation"); - } - - logger.debug("user is staff"); - - boolean marksReleased = lesson.getMarksReleased() != null && lesson.getMarksReleased(); - - LessonDetailsDTO lessonDetatilsDTO = lesson.getLessonDetails(); - request.setAttribute("lessonDetails", lessonDetatilsDTO); - request.setAttribute("marksReleased", marksReleased); - - return mapping.findForward("monitorgradebook"); - } - } catch (Exception e) { - logger.error("Failed to load gradebook monitor", e); - return mapping.findForward("error"); - } + return mapping.findForward("monitorgradebook"); + } catch (Exception e) { + GradebookMonitoringAction.log.error("Failed to load lesson gradebook", e); + return mapping.findForward("error"); } + } - @SuppressWarnings("unchecked") - public ActionForward courseMonitor(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws Exception { + public ActionForward courseMonitor(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws Exception { - try { - initServices(); - Integer oranisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); + try { + Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); + if (GradebookMonitoringAction.log.isDebugEnabled()) { + GradebookMonitoringAction.log.debug("Getting gradebook for organisation " + organisationID); + } - logger.debug("request monitorGradebook for organisation: " + oranisationID.toString()); - UserDTO user = getUser(); - if (user == null) { - logger.error("User missing from session. "); - return mapping.findForward("error"); - } else { + UserDTO user = getUser(); + if (user == null) { + GradebookMonitoringAction.log.error("User missing from session. "); + return mapping.findForward("error"); + } + if (!getSecurityService().isGroupMonitor(organisationID, user.getUserID(), "get course monitor", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); + return null; + } - Organisation organisation = (Organisation) userService.findById(Organisation.class, oranisationID); - if (organisation == null) { - logger.error("Organisation " + oranisationID + " does not exist. Unable to load gradebook"); - return mapping.findForward("error"); - } + Organisation organisation = (Organisation) getUserService().findById(Organisation.class, organisationID); + request.setAttribute("organisationID", organisationID); + request.setAttribute("organisationName", organisation.getName()); - // Validate whether this user is a monitor for this organisation - if (!userService.isUserInRole(user.getUserID(), oranisationID, Role.MONITOR)) { - logger.error("User " + user.getLogin() - + " is not a monitor in the requested course. Cannot access the course for gradebook."); - return displayMessage(mapping, request, "error.authorisation"); - } + return mapping.findForward("monitorcoursegradebook"); + } catch (Exception e) { + GradebookMonitoringAction.log.error("Failed to load course gradebook", e); + return mapping.findForward("error"); + } + } - logger.debug("user is staff"); + /** + * Updates a user's mark or feedback for an entire lesson + * + * @param mapping + * @param form + * @param request + * @param response + * @return + * @throws Exception + */ + public ActionForward updateUserLessonGradebookData(ActionMapping mapping, ActionForm form, + HttpServletRequest request, HttpServletResponse response) throws Exception { + Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), "update lesson gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } - request.setAttribute("organisationID", oranisationID); - request.setAttribute("organisationName", organisation.getName()); + Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_ID); + User learner = (User) getUserService().findById(User.class, userID); + if (learner == null) { + GradebookMonitoringAction.log.error("User with ID " + userID + + " could not be found to update his lesson gradebook"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "User could not be found"); + return null; + } - return mapping.findForward("monitorcoursegradebook"); - } - } catch (Exception e) { - logger.error("Failed to load gradebook monitor", e); - return mapping.findForward("error"); - } + String markStr = WebUtil.readStrParam(request, GradebookConstants.PARAM_MARK, true); + String feedback = WebUtil.readStrParam(request, GradebookConstants.PARAM_FEEDBACK, true); + Lesson lesson = getLessonService().getLesson(lessonID); + if ((markStr != null) && !markStr.equals("")) { + Double mark = Double.parseDouble(markStr); + getGradebookService().updateUserLessonGradebookMark(lesson, learner, mark); } + if (feedback != null) { + getGradebookService().updateUserLessonGradebookFeedback(lesson, learner, feedback); + } - /** - * Updates a user's mark or feedback for an entire lesson - * - * @param mapping - * @param form - * @param request - * @param response - * @return - * @throws Exception - */ - public ActionForward updateUserLessonGradebookData(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) throws Exception { - initServices(); - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - Integer userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_ID); - String markStr = WebUtil.readStrParam(request, GradebookConstants.PARAM_MARK, true); - String feedback = WebUtil.readStrParam(request, GradebookConstants.PARAM_FEEDBACK, true); - Lesson lesson = lessonService.getLesson(lessonID); - User learner = (User) userService.findById(User.class, userID); + return null; + } - if (lesson != null || learner != null) { - - if (markStr != null && !markStr.equals("")) { - Double mark = Double.parseDouble(markStr); - gradebookService.updateUserLessonGradebookMark(lesson, learner, mark); - } - - if (feedback != null) { - gradebookService.updateUserLessonGradebookFeedback(lesson, learner, feedback); - } - - } else { - logger.error("No lesson could be found for: " + lessonID); - } - return null; + /** + * Updates a user's mark or feedback for an activity, then aggregates their total lesson mark + * + * @param mapping + * @param form + * @param request + * @param response + * @return + * @throws Exception + */ + public ActionForward updateUserActivityGradebookData(ActionMapping mapping, ActionForm form, + HttpServletRequest request, HttpServletResponse response) throws Exception { + Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), "update activity gradebook", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; } - /** - * Updates a user's mark or feedback for an activity, then aggregates their total lesson mark - * - * @param mapping - * @param form - * @param request - * @param response - * @return - * @throws Exception - */ - public ActionForward updateUserActivityGradebookData(ActionMapping mapping, ActionForm form, - HttpServletRequest request, HttpServletResponse response) throws Exception { - initServices(); - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + GBGridView view = GradebookUtil.readGBGridViewParam(request, GradebookConstants.PARAM_VIEW, false); - GBGridView view = GradebookUtil.readGBGridViewParam(request, GradebookConstants.PARAM_VIEW, false); + Long activityID = null; + Integer userID = null; - Long activityID = null; - Integer userID = null; + // Fetch the id based on which grid it came from + if (view == GBGridView.MON_ACTIVITY) { + String rowID = WebUtil.readStrParam(request, AttributeNames.PARAM_ACTIVITY_ID); - // Fetch the id based on which grid it came from - if (view == GBGridView.MON_ACTIVITY) { - String rowID = WebUtil.readStrParam(request, AttributeNames.PARAM_ACTIVITY_ID); + // Splitting the rowID param to get the activity/group id pair + String[] split = rowID.split("_"); + if (split.length == 2) { + activityID = Long.parseLong(split[0]); + } else { + activityID = Long.parseLong(rowID); + } - // Splitting the rowID param to get the activity/group id pair - String[] split = rowID.split("_"); - if (split.length == 2) { - activityID = Long.parseLong(split[0]); - } else { - activityID = Long.parseLong(rowID); - } + userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_ID); + } else if (view == GBGridView.MON_USER) { + activityID = WebUtil.readLongParam(request, GradebookConstants.PARAM_ID); + userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); + } - userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_ID); + Activity activity = (Activity) getUserService().findById(Activity.class, activityID); + if ((activity == null) || !activity.isToolActivity()) { + GradebookMonitoringAction.log.error("Activity with ID " + activityID + + " could not be found or it is not a Tool Activity"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong activity"); + return null; + } - } else if (view == GBGridView.MON_USER) { - activityID = WebUtil.readLongParam(request, GradebookConstants.PARAM_ID); - userID = WebUtil.readIntParam(request, GradebookConstants.PARAM_USERID); - } + User learner = (User) getUserService().findById(User.class, userID); + if (learner == null) { + GradebookMonitoringAction.log.error("User with ID " + userID + + " could not be found to update his activity gradebook"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "User could not be found"); + return null; + } - String markStr = WebUtil.readStrParam(request, GradebookConstants.PARAM_MARK, true); - String feedback = WebUtil.readStrParam(request, GradebookConstants.PARAM_FEEDBACK, true); + String markStr = WebUtil.readStrParam(request, GradebookConstants.PARAM_MARK, true); + String feedback = WebUtil.readStrParam(request, GradebookConstants.PARAM_FEEDBACK, true); + Lesson lesson = getLessonService().getLesson(lessonID); + if ((markStr != null) && !markStr.equals("")) { + Double mark = Double.parseDouble(markStr); + getGradebookService().updateUserActivityGradebookMark(lesson, learner, activity, mark, true, true); + } - Activity activity = (Activity) userService.findById(Activity.class, activityID); - User learner = (User) userService.findById(User.class, userID); - Lesson lesson = lessonService.getLesson(lessonID); - - if (lesson != null && activity != null && learner != null && activity.isToolActivity()) { - - if (markStr != null && !markStr.equals("")) { - Double mark = Double.parseDouble(markStr); - gradebookService.updateUserActivityGradebookMark(lesson, learner, activity, mark, true, true); - } - - if (feedback != null) { - gradebookService.updateUserActivityGradebookFeedback(activity, learner, feedback); - } - - } else { - logger.error("Lesson or activity missing for lesson: " + lessonID + "and activity: " + activityID); - } - return null; + if (feedback != null) { + getGradebookService().updateUserActivityGradebookFeedback(activity, learner, feedback); } + return null; + } + /** * Toggles the release mark flag for a lesson * @@ -277,12 +270,14 @@ */ public ActionForward toggleReleaseMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { - initServices(); Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - - gradebookService.toggleMarksReleased(lessonID); + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), "toggle release marks", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } - writeResponse(response, CONTENT_TYPE_TEXT_PLAIN, ENCODING_UTF8, "success"); + getGradebookService().toggleMarksReleased(lessonID); + writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_PLAIN, LamsDispatchAction.ENCODING_UTF8, "success"); return null; } @@ -291,168 +286,161 @@ */ public ActionForward exportExcelLessonGradebook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { - - initServices(); - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - Lesson lesson = lessonService.getLesson(lessonID); + if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), + "export lesson gradebook spreadsheet", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } - if (lesson == null) { - String errorMsg = "Attempt to retrieve gradebook data for null lesson"; - logger.error(errorMsg); - throw new Exception(errorMsg); + if (GradebookMonitoringAction.log.isDebugEnabled()) { + GradebookMonitoringAction.log.debug("Exporting to a spreadsheet lesson: " + lessonID); } - + Lesson lesson = getLessonService().getLesson(lessonID); String fileName = lesson.getLessonName().replaceAll(" ", "_") + ".xlsx"; fileName = FileUtil.encodeFilenameForDownload(request, fileName); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); - logger.debug("Exporting to a spreadsheet gradebook lesson: " + lessonID); + GradebookMonitoringAction.log.debug("Exporting to a spreadsheet gradebook lesson: " + lessonID); ServletOutputStream out = response.getOutputStream(); - LinkedHashMap dataToExport = gradebookService.exportLessonGradebook(lesson); + LinkedHashMap dataToExport = getGradebookService().exportLessonGradebook(lesson); // set cookie that will tell JS script that export has been finished String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue"); Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue); fileDownloadTokenCookie.setPath("/"); response.addCookie(fileDownloadTokenCookie); - ExcelUtil.createExcel(out, dataToExport, gradebookService.getMessage("gradebook.export.dateheader"), true); + ExcelUtil.createExcel(out, dataToExport, getGradebookService().getMessage("gradebook.export.dateheader"), true); return null; } - + /** * Exports Course Gradebook into excel. */ public ActionForward exportExcelCourseGradebook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); + UserDTO user = getUser(); + if (!getSecurityService().isGroupMonitor(organisationID, user.getUserID(), + "export course gradebook spreadsheet", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); + return null; + } - initServices(); - Integer oranisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); - User user = getRealUser(getUser()); - - Organisation organisation = (Organisation) userService.findById(Organisation.class, oranisationID); - if (organisation == null || user == null) { - String errorMsg = "Organisation " + oranisationID + " does not exist or user is null. Unable to load gradebook"; - logger.error(errorMsg); - throw new Exception(errorMsg); + Organisation organisation = (Organisation) getUserService().findById(Organisation.class, organisationID); + if (GradebookMonitoringAction.log.isDebugEnabled()) { + GradebookMonitoringAction.log.debug("Exporting to a spreadsheet course: " + organisationID); } - - Integer organisationId = organisation.getOrganisationId(); - logger.debug("Exporting to a spreadsheet course: " + organisationId); + LinkedHashMap dataToExport = getGradebookService().exportCourseGradebook( + user.getUserID(), organisationID); - LinkedHashMap dataToExport = gradebookService.exportCourseGradebook(user.getUserId(), organisationId); - String fileName = organisation.getName().replaceAll(" ", "_") + ".xlsx"; - fileName = FileUtil.encodeFilenameForDownload(request, fileName); - + fileName = FileUtil.encodeFilenameForDownload(request, fileName); + response.setContentType("application/x-download"); - response.setHeader("Content-Disposition", "attachment;filename=" + fileName); - - //set cookie that will tell JS script that export has been finished + response.setHeader("Content-Disposition", "attachment;filename=" + fileName); + + // set cookie that will tell JS script that export has been finished String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue"); Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue); fileDownloadTokenCookie.setPath("/"); - response.addCookie(fileDownloadTokenCookie); - - //Code to generate file and write file contents to response + response.addCookie(fileDownloadTokenCookie); + + // Code to generate file and write file contents to response ServletOutputStream out = response.getOutputStream(); - ExcelUtil.createExcel(out, dataToExport, gradebookService.getMessage("gradebook.export.dateheader"), true); + ExcelUtil.createExcel(out, dataToExport, getGradebookService().getMessage("gradebook.export.dateheader"), true); return null; } - + /** * Exports selected lessons Gradebook into excel. */ public ActionForward exportExcelSelectedLessons(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { - - initServices(); - Integer oranisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); - User user = getRealUser(getUser()); - - Organisation organisation = (Organisation) userService.findById(Organisation.class, oranisationID); - if (organisation == null || user == null) { - String errorMsg = "Organisation " + oranisationID + " does not exist or user is null. Unable to load gradebook"; - logger.error(errorMsg); - throw new Exception(errorMsg); + Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); + UserDTO user = getUser(); + if (!getSecurityService().isGroupMonitor(organisationID, user.getUserID(), + "export selected lessons gradebook spreadsheet", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); + return null; } - - Integer organisationId = organisation.getOrganisationId(); - logger.debug("Exporting to a spreadsheet course: " + organisationId); + Organisation organisation = (Organisation) getUserService().findById(Organisation.class, organisationID); String[] lessonIds = request.getParameterValues(AttributeNames.PARAM_LESSON_ID); - Assert.notNull(lessonIds); + if (GradebookMonitoringAction.log.isDebugEnabled()) { + GradebookMonitoringAction.log.debug("Exporting to a spreadsheet lessons " + Arrays.toString(lessonIds) + + " from course: " + organisationID); + } + LinkedHashMap dataToExport = getGradebookService().exportSelectedLessonsGradebook( + user.getUserID(), organisationID, lessonIds); - LinkedHashMap dataToExport = gradebookService.exportSelectedLessonsGradebook(user.getUserId(), organisationId, lessonIds); - String fileName = organisation.getName().replaceAll(" ", "_") + ".xlsx"; - fileName = FileUtil.encodeFilenameForDownload(request, fileName); - + fileName = FileUtil.encodeFilenameForDownload(request, fileName); + response.setContentType("application/x-download"); - response.setHeader("Content-Disposition", "attachment;filename=" + fileName); - - //set cookie that will tell JS script that export has been finished + response.setHeader("Content-Disposition", "attachment;filename=" + fileName); + + // set cookie that will tell JS script that export has been finished String downloadTokenValue = WebUtil.readStrParam(request, "downloadTokenValue"); Cookie fileDownloadTokenCookie = new Cookie("fileDownloadToken", downloadTokenValue); fileDownloadTokenCookie.setPath("/"); - response.addCookie(fileDownloadTokenCookie); - - //Code to generate file and write file contents to response + response.addCookie(fileDownloadTokenCookie); + + // Code to generate file and write file contents to response ServletOutputStream out = response.getOutputStream(); ExcelUtil.createExcel(out, dataToExport, null, false); return null; } - private UserDTO getUser() { - HttpSession ss = SessionManager.getSession(); - return (UserDTO) ss.getAttribute(AttributeNames.USER); - } + private UserDTO getUser() { + HttpSession ss = SessionManager.getSession(); + return (UserDTO) ss.getAttribute(AttributeNames.USER); + } - private User getRealUser(UserDTO dto) { - return getUserService().getUserByLogin(dto.getLogin()); - } + private ActionForward displayMessage(ActionMapping mapping, HttpServletRequest req, String messageKey) { + req.setAttribute("messageKey", messageKey); + return mapping.findForward("message"); + } - private ActionForward displayMessage(ActionMapping mapping, HttpServletRequest req, String messageKey) { - req.setAttribute("messageKey", messageKey); - return mapping.findForward("message"); + private IUserManagementService getUserService() { + if (GradebookMonitoringAction.userService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + GradebookMonitoringAction.userService = (IUserManagementService) ctx.getBean("userManagementService"); } + return GradebookMonitoringAction.userService; + } - private void initServices() { - getUserService(); - getLessonService(); - getGradebookService(); + private ILessonService getLessonService() { + if (GradebookMonitoringAction.lessonService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + GradebookMonitoringAction.lessonService = (ILessonService) ctx.getBean("lessonService"); } + return GradebookMonitoringAction.lessonService; + } - private IUserManagementService getUserService() { - if (userService == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() - .getServletContext()); - userService = (IUserManagementService) ctx.getBean("userManagementService"); - } - return userService; + private IGradebookService getGradebookService() { + if (GradebookMonitoringAction.gradebookService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + GradebookMonitoringAction.gradebookService = (IGradebookService) ctx.getBean("gradebookService"); } + return GradebookMonitoringAction.gradebookService; + } - private ILessonService getLessonService() { - if (lessonService == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() - .getServletContext()); - lessonService = (ILessonService) ctx.getBean("lessonService"); - } - return lessonService; + private ISecurityService getSecurityService() { + if (GradebookMonitoringAction.securityService == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() + .getServletContext()); + GradebookMonitoringAction.securityService = (ISecurityService) ctx.getBean("securityService"); } - - private IGradebookService getGradebookService() { - if (gradebookService == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet() - .getServletContext()); - gradebookService = (IGradebookService) ctx.getBean("gradebookService"); - } - return gradebookService; - } -} + return GradebookMonitoringAction.securityService; + } +} \ No newline at end of file Index: lams_learning/src/java/org/lamsfoundation/lams/learning/export/web/action/MainExportServlet.java =================================================================== diff -u -r38b5da8f9b986f835a4dde123bd09954a4b6e171 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_learning/src/java/org/lamsfoundation/lams/learning/export/web/action/MainExportServlet.java (.../MainExportServlet.java) (revision 38b5da8f9b986f835a4dde123bd09954a4b6e171) +++ lams_learning/src/java/org/lamsfoundation/lams/learning/export/web/action/MainExportServlet.java (.../MainExportServlet.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -36,7 +36,6 @@ import java.net.URLEncoder; import java.util.Collection; import java.util.Iterator; -import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -59,7 +58,6 @@ import org.lamsfoundation.lams.lesson.service.ILessonService; import org.lamsfoundation.lams.security.ISecurityService; import org.lamsfoundation.lams.tool.ToolAccessMode; -import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.WebUtil; @@ -124,22 +122,26 @@ } ToolAccessMode accessMode = ToolAccessMode.TEACHER.toString().equals(role) ? ToolAccessMode.TEACHER : null; - try { - if (accessMode == null) { - securityService.checkIsLessonLearner(lesson.getLessonId(), currentUserId); - LearnerProgress learnerProgress = lessonService.getUserProgressForLesson(currentUserId, - lesson.getLessonId()); - if (learnerProgress == null || !learnerProgress.isComplete()) { - throw new ExportPortfolioException("Learner with ID: " + currentUserId - + " has not finished lesson with ID: " + lesson.getLessonId()); - } - } else { - securityService.checkIsLessonMonitor(lesson.getLessonId(), currentUserId); + if (accessMode == null) { + if (!securityService.isLessonLearner(lesson.getLessonId(), currentUserId, "export portfolio", + false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a learner in the lesson"); + return; } - } catch (SecurityException e) { - log.error("Cannot export portfolion", e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson"); - return; + LearnerProgress learnerProgress = lessonService.getUserProgressForLesson(currentUserId, + lesson.getLessonId()); + if (learnerProgress == null || !learnerProgress.isComplete()) { + log.error("Learner with ID: " + currentUserId + " has not finished lesson with ID: " + + lesson.getLessonId()); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "The learner has not finished the lesson"); + return; + } + } else { + if (!securityService.isLessonMonitor(lesson.getLessonId(), currentUserId, "export portfolio", + false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a learner in the lesson"); + return; + } } portfolios = exportService.exportPortfolioForStudent(userIdParam == null ? currentUserId : userIdParam, @@ -149,10 +151,7 @@ exportFilename = ExportPortfolioConstants.EXPORT_LEARNER_PREFIX + " " + portfolios.getLessonName() + " " + learnerLogin + ".zip"; } else if (mode.equals(ToolAccessMode.TEACHER.toString())) { - try { - securityService.checkIsLessonMonitor(lesson.getLessonId(), currentUserId); - } catch (SecurityException e) { - log.error("Cannot export portfolion", e); + if (!securityService.isLessonMonitor(lesson.getLessonId(), currentUserId, "export portfolio", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson"); return; } @@ -218,10 +217,10 @@ File tempDir = new File(exportTmpDir); // finds all the html extension files - Collection jspFiles = FileUtils.listFiles(tempDir, new String[] { "html" }, true); + Collection jspFiles = FileUtils.listFiles(tempDir, new String[] { "html" }, true); // iterates thru the collection and sends this - for (Iterator it = jspFiles.iterator(); it.hasNext();) { + for (Iterator it = jspFiles.iterator(); it.hasNext();) { Object element = it.next(); MainExportServlet.log.debug("Correcting links in file " + element.toString()); replaceImageFolderLinks(element.toString(), contentFolderID, learnerContentFolder); Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java =================================================================== diff -u -rd927914e80c12ea4cf2612788663209520c008c1 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java (.../IMonitoringService.java) (revision d927914e80c12ea4cf2612788663209520c008c1) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/IMonitoringService.java (.../IMonitoringService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -53,19 +53,6 @@ * @author Manpreet Minhas */ public interface IMonitoringService { - - /** - * Checks whether the user is a staff member for the lesson, the creator of the lesson or simply a group manager. If - * not, throws a UserAccessDeniedException exception - */ - void checkOwnerOrStaffMember(Integer userId, Long lessonId, String actionDescription); - - /** - * Checks whether the user is a staff member for the lesson, the creator of the lesson or simply a group manager. If - * not, throws a UserAccessDeniedException exception - */ - void checkOwnerOrStaffMember(Integer userId, Lesson lesson, String actionDescription); - /** Get the message service, which gives access to the I18N text */ MessageService getMessageService(); @@ -383,19 +370,6 @@ GateActivity closeGate(Long gateId); /** - * This method returns the details for the given Lesson in WDDX format. Object inside the packet is a - * LessonDetailsDTO. - * - * @param lessonID - * The lesson_id of the Lesson for which the details have to be fetched - * @param userID - * The user who is fetching the Lesson details - * @return String The requested details in wddx format - * @throws IOException - */ - String getLessonDetails(Long lessonID, Integer userID) throws IOException; - - /** * Returns a list of learners participating in the given Lesson * * @param lessonID @@ -502,20 +476,6 @@ String moveLesson(Long lessonID, Integer targetWorkspaceFolderID, Integer userID) throws IOException; /** - * This method changes the name of an existing Lesson to the one specified. - * - * @param lessonID - * The lesson_id of the Lesson whose name has to be changed - * @param newName - * The new name of the Lesson - * @param userID - * The user_id of the User who has requested this operation - * @return String The acknowledgement message/error in WDDX format - * @throws IOException - */ - String renameLesson(Long lessonID, String newName, Integer userID) throws IOException; - - /** * Return an activity object based on the requested id. * * @param activityId @@ -584,26 +544,6 @@ */ abstract Lesson createPreviewClassForLesson(int userID, long lessonID) throws UserAccessDeniedException; - /** - * Remove all the details for a particular preview lessons. The transaction handling for this method should be - * REQUIRES_NEW, which allows each lesson to be deleted separately. - * - * @param lessonID - * ID of the lesson which is the preview session. Mandatory. - */ - abstract void deletePreviewLesson(long lessonID); - - /** - * Remove all the "old" preview lessons. Removes all preview lessons older than the number of days specified in the - * configuration file. - *

- * Calls deletePreviewLesson(long lessonID) to do the actual deletion, so if one lesson throws a database exception - * when deleting, the other lessons should delete okay (as deletePreviewLesson uses a REQUIRES_NEW transaction) - * - * @return number of lessons deleted. - */ - abstract int deleteAllOldPreviewLessons(); - /* Supports the Chosen Groupings and Branching */ /** * Get all the active learners in the lesson who are not in a group or in a branch. @@ -743,29 +683,10 @@ */ void setGroupName(Long groupID, String name); - /** Open Time Chart */ - Boolean openTimeChart(long lessonId, Integer userId) throws UserAccessDeniedException; - /** Get Organisation by organisationId */ Organisation getOrganisation(Integer organisationId); /** - * If the activity is not grouped and not in a branch, then it create lams tool session for all the learners in the - * lesson. After the creation of lams tool session, it delegates to the tool instances to create tool's own tool - * session. Can't create it for a grouped activity or an activity in a branch as it may not be applicable to all - * users. - *

- * - * @param activity - * the tool activity that all tool session reference to. - * @param lesson - * the target lesson that these tool sessions belongs to. - * @throws LamsToolServiceException - * the exception when lams is talking to tool. - */ - void initToolSessionIfSuitable(ToolActivity activity, Lesson lesson); - - /** * Used in admin to clone lessons using the given lesson Ids (from another group) into the given group. Given staff * and learner ids should already be members of the group. * Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/service/MonitoringService.java (.../MonitoringService.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -47,6 +47,7 @@ import java.util.TreeSet; import java.util.Vector; +import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.collections.CollectionUtils; @@ -89,6 +90,7 @@ import org.lamsfoundation.lams.monitoring.MonitoringConstants; import org.lamsfoundation.lams.monitoring.dto.ContributeActivityDTO; import org.lamsfoundation.lams.security.ISecurityService; +import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.tool.ToolSession; import org.lamsfoundation.lams.tool.exception.LamsToolServiceException; import org.lamsfoundation.lams.tool.exception.ToolException; @@ -181,7 +183,7 @@ private ILamsCoreToolService lamsCoreToolService; private IUserManagementService userManagementService; - + private ISecurityService securityService; private Scheduler scheduler; @@ -231,7 +233,7 @@ public void setUserManagementService(IUserManagementService userManagementService) { this.userManagementService = userManagementService; } - + public void setSecurityService(ISecurityService securityService) { this.securityService = securityService; } @@ -362,40 +364,13 @@ // --------------------------------------------------------------------- @Override - public void checkOwnerOrStaffMember(Integer userId, Long lessonId, String actionDescription) { - checkOwnerOrStaffMember(userId, lessonDAO.getLesson(lessonId), actionDescription); - } - - @Override - public void checkOwnerOrStaffMember(Integer userId, Lesson lesson, String actionDescription) { - User user = (User) baseDAO.find(User.class, userId); - - if ((lesson.getUser() != null) && lesson.getUser().getUserId().equals(userId)) { - return; - } - - Organisation course = lesson.getOrganisation(); - if (OrganisationType.CLASS_TYPE.equals(course.getOrganisationType().getOrganisationTypeId())) { - course = course.getParentOrganisation(); - } - boolean isUserGroupManager = userManagementService.isUserInRole(userId, course.getOrganisationId(), - Role.GROUP_MANAGER); - - if ((lesson == null) || (lesson.getLessonClass() == null) - || (!lesson.getLessonClass().isStaffMember(user) && !isUserGroupManager)) { - throw new UserAccessDeniedException("User " + userId + " may not " + actionDescription + " for lesson " - + lesson.getLessonId()); - } - } - - @Override public Lesson initializeLesson(String lessonName, String lessonDescription, long learningDesignId, Integer organisationId, Integer userID, String customCSV, Boolean enableLessonIntro, Boolean displayDesignImage, Boolean learnerExportAvailable, Boolean learnerPresenceAvailable, Boolean learnerImAvailable, Boolean liveEditEnabled, Boolean enableLessonNotifications, Boolean learnerRestart, Integer scheduledNumberDaysToLessonFinish, Long precedingLessonId) { - securityService.hasOrgRole(organisationId, userID, Role.MONITOR); + securityService.isGroupMonitor(organisationId, userID, "intializeLesson", true); LearningDesign originalLearningDesign = authoringService.getLearningDesign(new Long(learningDesignId)); if (originalLearningDesign == null) { @@ -450,7 +425,7 @@ + " is missing. Unable to initialize lesson."); } User user = userID != null ? (User) baseDAO.find(User.class, userID) : null; - + return initializeLesson(lessonName, lessonDescription, originalLearningDesign, user, null, LearningDesign.COPY_TYPE_PREVIEW, customCSV, false, false, false, learnerPresenceAvailable, learnerImAvailable, liveEditEnabled, true, false, null, null); @@ -565,25 +540,22 @@ public Lesson createLessonClassForLesson(long lessonId, Organisation organisation, String learnerGroupName, List organizationUsers, String staffGroupName, List staffs, Integer userId) { Lesson newLesson = lessonDAO.getLesson(new Long(lessonId)); - if (newLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to create class for lesson."); - } - checkOwnerOrStaffMember(userId, newLesson, "create lesson class"); - // if lesson isn't started recreate the lesson class if (newLesson.isLessonStarted()) { + securityService.isLessonMonitor(lessonId, userId, "create class for lesson", true); lessonService.setLearners(newLesson, organizationUsers); lessonService.setStaffMembers(newLesson, staffs); - } else { + newLesson.setOrganisation(organisation); + // security check needs organisation to be set + securityService.isLessonMonitor(lessonId, userId, "create class for lesson", true); + LessonClass oldLessonClass = newLesson.getLessonClass(); LessonClass newLessonClass = this.createLessonClass(organisation, learnerGroupName, organizationUsers, staffGroupName, staffs, newLesson); newLessonClass.setLesson(newLesson); newLesson.setLessonClass(newLessonClass); - newLesson.setOrganisation(organisation); lessonDAO.updateLesson(newLesson); @@ -597,14 +569,10 @@ @Override public void startLessonOnSchedule(long lessonId, Date startDate, Integer userId) { - + securityService.isLessonMonitor(lessonId, userId, "start lesson on schedule", true); + // we get the lesson just created Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to start lesson."); - } - checkOwnerOrStaffMember(userId, requestedLesson, "start lesson on schedule"); - if (requestedLesson.isLessonStarted()) { // can't schedule it as it is already started. If the UI is correct, // this should never happen. @@ -654,13 +622,10 @@ @Override public void finishLessonOnSchedule(long lessonId, int scheduledNumberDaysToLessonFinish, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "finish lesson on schedule", true); + // we get the lesson want to finish Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to start lesson."); - } - checkOwnerOrStaffMember(userId, requestedLesson, "finish lesson on schedule"); - String triggerName = "finishLessonOnScheduleTrigger:" + lessonId; boolean alreadyScheduled = false; try { @@ -739,32 +704,21 @@ @Override public void startLesson(long lessonId, Integer userId) { - // System.out.println(messageService.getMessage("NO.SUCH.LESSON",new - // Object[]{new Long(lessonId)})); - // System.out.println(messageService.getMessage("INVALID.ACTIVITYID.TYPE", - // new Object[]{ "activityID"})); - // System.out.println(messageService.getMessage("INVALID.ACTIVITYID.LESSONID",new - // Object[]{ "activityID","lessonID"})); if (MonitoringService.log.isDebugEnabled()) { MonitoringService.log.debug("=============Starting Lesson " + lessonId + "=============="); } + securityService.isLessonMonitor(lessonId, userId, "start lesson", true); // we get the lesson just created Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to start lesson."); - } - if (requestedLesson.isLessonStarted()) { MonitoringService.log - .warn("Lesson for id=" + .warn("Lesson " + lessonId + " has been started. No need to start the lesson. The lesson was probably scheduled, and then the staff used \"Start now\". This message would have then been created by the schedule start"); return; } - checkOwnerOrStaffMember(userId, requestedLesson, "create lesson class"); - Date lessonStartTime = new Date(); // initialize tool sessions if necessary LearningDesign design = requestedLesson.getLearningDesign(); @@ -881,23 +835,15 @@ @Override public void finishLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "finish lesson", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set lesson to finished"); - } - checkOwnerOrStaffMember(userId, requestedLesson, "finish lesson"); setLessonState(requestedLesson, Lesson.FINISHED_STATE); } @Override public void archiveLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "archive lesson", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set lesson to archived"); - } - checkOwnerOrStaffMember(userId, requestedLesson, "archive lesson"); if (!Lesson.ARCHIVED_STATE.equals(requestedLesson.getLessonStateId()) && !Lesson.REMOVED_STATE.equals(requestedLesson.getLessonStateId())) { setLessonState(requestedLesson, Lesson.ARCHIVED_STATE); @@ -906,23 +852,15 @@ @Override public void unarchiveLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "unarchive lesson", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set lesson to archived"); - } - checkOwnerOrStaffMember(userId, requestedLesson, "unarchive lesson"); revertLessonState(requestedLesson); - } @Override public void suspendLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "suspend lesson", true); Lesson lesson = lessonDAO.getLesson(new Long(lessonId)); - checkOwnerOrStaffMember(userId, lesson, "suspend lesson"); - if (lesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to suspend lesson."); - } if (!Lesson.SUSPENDED_STATE.equals(lesson.getLessonStateId()) && !Lesson.REMOVED_STATE.equals(lesson.getLessonStateId())) { setLessonState(lesson, Lesson.SUSPENDED_STATE); @@ -931,16 +869,13 @@ @Override public void unsuspendLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "unsuspend lesson", true); Lesson lesson = lessonDAO.getLesson(new Long(lessonId)); - checkOwnerOrStaffMember(userId, lesson, "unsuspend lesson"); Integer state = lesson.getLessonStateId(); // only suspend started lesson if (!Lesson.SUSPENDED_STATE.equals(state)) { throw new MonitoringServiceException("Lesson is not suspended lesson. It can not be unsuspended."); } - if (lesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to suspend lesson."); - } revertLessonState(lesson); } @@ -951,7 +886,6 @@ * @param status */ private void setLessonState(Lesson requestedLesson, Integer status) { - requestedLesson.setPreviousLessonStateId(requestedLesson.getLessonStateId()); requestedLesson.setLessonStateId(status); lessonDAO.updateLesson(requestedLesson); @@ -966,7 +900,6 @@ * @param status */ private void revertLessonState(Lesson requestedLesson) { - Integer currentStatus = requestedLesson.getLessonStateId(); if (requestedLesson.getPreviousLessonStateId() != null) { if (requestedLesson.getPreviousLessonStateId().equals(Lesson.NOT_STARTED_STATE) @@ -1001,72 +934,49 @@ @Override public void removeLesson(long lessonId, Integer userId) { + securityService.isLessonMonitor(lessonId, userId, "remove lesson", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to remove lesson."); - } - checkOwnerOrStaffMember(userId, requestedLesson, "remove lesson"); - - // TODO give sysadmin rights to do this too! - setLessonState(requestedLesson, Lesson.REMOVED_STATE); } @Override public Boolean setLearnerPortfolioAvailable(long lessonId, Integer userId, Boolean isLearnerExportAvailable) { + securityService.isLessonMonitor(lessonId, userId, "set learner portfolio available", true); + isLearnerExportAvailable = (isLearnerExportAvailable != null) ? isLearnerExportAvailable : Boolean.FALSE; - Lesson lesson = lessonDAO.getLesson(new Long(lessonId)); - if (lesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set learner portfolio available to " + isLearnerExportAvailable); - } - checkOwnerOrStaffMember(userId, lesson, "set learner portfolio available"); - lesson.setLearnerExportAvailable(isLearnerExportAvailable); lessonDAO.updateLesson(lesson); - //audit log enabling/disabling export portfolio - writeAuditLog(MonitoringService.AUDIT_LEARNER_PORTFOLIO_SET, new Object[] { lesson.getLessonName(), - lesson.getLearnerExportAvailable() }); - + // audit log enabling/disabling export portfolio + writeAuditLog(MonitoringService.AUDIT_LEARNER_PORTFOLIO_SET, + new Object[] { lesson.getLessonName(), lesson.getLearnerExportAvailable() }); + return lesson.getLearnerExportAvailable(); } @Override public Boolean setPresenceAvailable(long lessonId, Integer userId, Boolean presenceAvailable) { + securityService.isLessonMonitor(lessonId, userId, "set presence available", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set learner presence available to " + presenceAvailable); - } - checkOwnerOrStaffMember(userId, requestedLesson, "set presence available"); requestedLesson.setLearnerPresenceAvailable(presenceAvailable != null ? presenceAvailable : Boolean.FALSE); lessonDAO.updateLesson(requestedLesson); return requestedLesson.getLearnerPresenceAvailable(); } @Override public Boolean setPresenceImAvailable(long lessonId, Integer userId, Boolean presenceImAvailable) { + securityService.isLessonMonitor(lessonId, userId, "set presence instant messaging available", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set learner im to " + presenceImAvailable); - } - checkOwnerOrStaffMember(userId, requestedLesson, "set presence available"); requestedLesson.setLearnerImAvailable(presenceImAvailable != null ? presenceImAvailable : Boolean.FALSE); lessonDAO.updateLesson(requestedLesson); return requestedLesson.getLearnerImAvailable(); } @Override public Boolean setLiveEditEnabled(long lessonId, Integer userId, Boolean liveEditEnabled) { + securityService.isLessonMonitor(lessonId, userId, "set live edit available", true); Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId - + " is missing. Unable to set live edit enabled to " + liveEditEnabled); - } - checkOwnerOrStaffMember(userId, requestedLesson, "set live edit available"); requestedLesson.setLiveEditEnabled(liveEditEnabled != null ? liveEditEnabled : Boolean.FALSE); lessonDAO.updateLesson(requestedLesson); return requestedLesson.getLiveEditEnabled(); @@ -1100,18 +1010,6 @@ } @Override - public Boolean openTimeChart(long lessonId, Integer userId) { - Lesson requestedLesson = lessonDAO.getLesson(new Long(lessonId)); - if (requestedLesson == null) { - throw new MonitoringServiceException("Lesson for id=" + lessonId + " is missing. Unable to open."); - } - - checkOwnerOrStaffMember(userId, requestedLesson, "open the time chart"); - - return true; - } - - @Override public GateActivity openGateForSingleUser(Long gateId, Integer userId) { GateActivity gate = (GateActivity) activityDAO.getActivityByActivityId(gateId); if ((gate != null) && (userId != null) && (userId >= 0)) { @@ -1133,9 +1031,8 @@ @Override public String forceCompleteActivitiesByUser(Integer learnerId, Integer requesterId, long lessonId, Long activityId, boolean removeLearnerContent) { + securityService.isLessonMonitor(lessonId, requesterId, "force complete", true); Lesson lesson = lessonDAO.getLesson(new Long(lessonId)); - checkOwnerOrStaffMember(requesterId, lesson, "force complete"); - User learner = (User) baseDAO.find(User.class, learnerId); LearnerProgress learnerProgress = learnerService.getProgress(learnerId, lessonId); @@ -1166,7 +1063,7 @@ .getCompletedActivities().containsKey(parentActivity) || ((parentActivity .getParentActivity() != null) && learnerProgress.getCompletedActivities().containsKey( parentActivity.getParentActivity())))))) { - + return forceUncompleteActivity(learnerProgress, stopActivity, removeLearnerContent); } } @@ -1346,7 +1243,7 @@ stopReason = messageService.getMessage( MonitoringService.FORCE_COMPLETE_STOP_MESSAGE_COMPLETED_TO_ACTIVITY, new Object[] { activity.getTitle() }); - + // without this, there are errors when target is in branching learnerService.createToolSessionsIfNecessary(stopActivity, learnerProgress); } else { @@ -1571,51 +1468,9 @@ } @Override - public String getLessonDetails(Long lessonID, Integer userID) throws IOException { - Lesson lesson = lessonDAO.getLesson(new Long(lessonID)); - checkOwnerOrStaffMember(userID, lesson, "get lesson deatils"); - - User user = (User) baseDAO.find(User.class, userID); - LessonDetailsDTO dto = lessonService.getLessonDetails(lessonID); - - Locale userLocale = new Locale(user.getLocale().getLanguageIsoCode(), user.getLocale().getCountryIsoCode()); - TimeZone tz = TimeZone.getTimeZone(user.getTimeZone()); - - /* Date Format for Chat room append */ - DateFormat sfm = new SimpleDateFormat("yyyyMMdd_HHmmss"); - if ((dto.getCreateDateTime() != WDDXTAGS.DATE_NULL_VALUE) && (dto.getCreateDateTime() != null)) { - dto.setCreateDateTimeStr(sfm.format(dto.getCreateDateTime())); - } - - DateFormat indfm = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", userLocale); - if ((dto.getStartDateTime() != WDDXTAGS.DATE_NULL_VALUE) && (dto.getStartDateTime() != null)) { - Date tzStartDate = DateUtil.convertToTimeZoneFromDefault(tz, dto.getStartDateTime()); - dto.setStartDateTimeStr(indfm.format(tzStartDate) + " " + tz.getDisplayName(userLocale)); - } - - if ((dto.getScheduleStartDate() != WDDXTAGS.DATE_NULL_VALUE) && (dto.getScheduleStartDate() != null)) { - Date tzScheduleDate = DateUtil.convertToTimeZoneFromDefault(tz, dto.getScheduleStartDate()); - dto.setScheduleStartDateStr(indfm.format(tzScheduleDate) + " " + tz.getDisplayName(userLocale)); - } - - MonitoringService.log.debug(dto.toString()); - MonitoringService.log.debug(dto.getLiveEditEnabled()); - - FlashMessage flashMessage; - if (dto != null) { - flashMessage = new FlashMessage("getLessonDetails", dto); - } else { - flashMessage = new FlashMessage("getLessonDetails", messageService.getMessage("NO.SUCH.LESSON", - new Object[] { lessonID }), FlashMessage.ERROR); - } - - return flashMessage.serializeMessage(); - } - - @Override public String getLessonLearners(Long lessonID, Integer userID) throws IOException { + securityService.isLessonMonitor(lessonID, userID, "get lesson learners", true); Lesson lesson = lessonDAO.getLesson(lessonID); - checkOwnerOrStaffMember(userID, lesson, "get lesson learners"); Vector lessonLearners = new Vector(); FlashMessage flashMessage; @@ -1635,8 +1490,8 @@ @Override public String getLessonStaff(Long lessonID, Integer userID) throws IOException { + securityService.isLessonMonitor(lessonID, userID, "get lesson staff", true); Lesson lesson = lessonDAO.getLesson(lessonID); - checkOwnerOrStaffMember(userID, lesson, "get lesson staff"); Vector lessonStaff = new Vector(); FlashMessage flashMessage; @@ -1844,8 +1699,8 @@ @Override public String getLearnerActivityURL(Long lessonID, Long activityID, Integer learnerUserID, Integer requestingUserId) throws IOException, LamsToolServiceException { + securityService.isLessonMonitor(lessonID, requestingUserId, "get learner activity URL", true); Lesson lesson = lessonDAO.getLesson(lessonID); - checkOwnerOrStaffMember(requestingUserId, lesson, "get monitoring learner progress url"); Activity activity = activityDAO.getActivityByActivityId(activityID); User learner = (User) baseDAO.find(User.class, learnerUserID); @@ -1870,8 +1725,8 @@ @Override public String getActivityMonitorURL(Long lessonID, Long activityID, String contentFolderID, Integer userID) throws IOException, LamsToolServiceException { + securityService.isLessonMonitor(lessonID, userID, "get activity monitor URL", true); Lesson lesson = lessonDAO.getLesson(lessonID); - checkOwnerOrStaffMember(userID, lesson, "get activity define later url"); Activity activity = activityDAO.getActivityByActivityId(activityID); @@ -1914,25 +1769,6 @@ } @Override - public String renameLesson(Long lessonID, String newName, Integer userID) throws IOException { - Lesson lesson = lessonDAO.getLesson(lessonID); - FlashMessage flashMessage; - if (lesson != null) { - if (lesson.getUser().getUserId().equals(userID)) { - lesson.setLessonName(newName); - lessonDAO.updateLesson(lesson); - flashMessage = new FlashMessage("renameLesson", newName); - } else { - flashMessage = FlashMessage.getUserNotAuthorized("renameLesson", userID); - } - } else { - flashMessage = new FlashMessage("renameLesson", messageService.getMessage("NO.SUCH.LESSON", - new Object[] { lessonID }), FlashMessage.ERROR); - } - return flashMessage.serializeMessage(); - } - - @Override public String releaseGate(Long activityID) throws IOException { GateActivity gate = (GateActivity) activityDAO.getActivityByActivityId(activityID); FlashMessage flashMessage; @@ -2091,41 +1927,6 @@ } // --------------------------------------------------------------------- - // Helper Methods - start lesson - // --------------------------------------------------------------------- - - @Override - public void initToolSessionIfSuitable(ToolActivity activity, Lesson lesson) { - if (activity.getApplyGrouping().equals(Boolean.FALSE) && (activity.getParentBranch() == null)) { - activity.setToolSessions(new HashSet()); - try { - - Set newToolSessions = lamsCoreToolService.createToolSessions(lesson.getAllLearners(), activity, lesson); - Iterator iter = newToolSessions.iterator(); - while (iter.hasNext()) { - // core has set up a new tool session, we need to ask tool - // to create their own - // tool sessions using the given id and attach the session - // to the activity. - ToolSession toolSession = (ToolSession) iter.next(); - lamsCoreToolService.notifyToolsToCreateSession(toolSession, activity); - activity.getToolSessions().add(toolSession); - } - } catch (LamsToolServiceException e) { - String error = "Unable to initialise tool session. Fail to call tool services. Error was " - + e.getMessage(); - MonitoringService.log.error(error, e); - throw new MonitoringServiceException(error, e); - } catch (ToolException e) { - String error = "Unable to initialise tool session. Tool encountered an error. Error was " - + e.getMessage(); - MonitoringService.log.error(error, e); - throw new MonitoringServiceException(error, e); - } - } - } - - // --------------------------------------------------------------------- // Helper Methods - scheduling // --------------------------------------------------------------------- @@ -2162,7 +1963,7 @@ // --------------------------------------------------------------------- // Preview related methods // --------------------------------------------------------------------- - + @Override public Lesson createPreviewClassForLesson(int userID, long lessonID) throws UserAccessDeniedException { @@ -2179,96 +1980,12 @@ staffs.add(user); return createLessonClassForLesson(lessonID, null, "Learner Group", learners, "Staff Group", staffs, userID); - } - /** - * {@inheritDoc}

- * - * Delete a preview lesson and all its contents. Warning: can only delete preview lessons. Can't guarentee data - * integrity if it is done to any other type of lesson. See removeLesson() for hiding lessons from a teacher's view - * without removing them from the database. TODO remove the related tool data. - */ - @Override - public void deletePreviewLesson(long lessonID) { - Lesson lesson = lessonDAO.getLesson(new Long(lessonID)); - deletePreviewLesson(lesson); - } - - private void deletePreviewLesson(Lesson lesson) { - if (lesson != null) { - if (lesson.isPreviewLesson()) { - - // get all the tool sessions for this lesson and remove all the - // tool session data - List toolSessions = lamsCoreToolService.getToolSessionsByLesson(lesson); - if ((toolSessions != null) && (toolSessions.size() > 0)) { - Iterator iter = toolSessions.iterator(); - while (iter.hasNext()) { - ToolSession toolSession = (ToolSession) iter.next(); - lamsCoreToolService.deleteToolSession(toolSession); - } - } else { - MonitoringService.log.debug("deletePreviewLesson: Removing tool sessions - none exist"); - } - - // lesson has learning design as a foriegn key, so need to - // remove lesson before learning design - LearningDesign ld = lesson.getLearningDesign(); - lessonDAO.deleteLesson(lesson); - authoringService.deleteLearningDesign(ld); - - } else { - MonitoringService.log - .warn("Unable to delete lesson as lesson is not a preview lesson. Learning design copy type was " - + lesson.getLearningDesign().getCopyTypeID()); - } - } - } - - @Override - public int deleteAllOldPreviewLessons() { - - int numDays = Configuration.getAsInt(ConfigurationKeys.PREVIEW_CLEANUP_NUM_DAYS); - - // Contract checking - if (numDays <= 0) { - MonitoringService.log.error("deleteAllOldPreviewSessions: number of days invalid (" + numDays - + "). See configuration file (option " + ConfigurationKeys.PREVIEW_CLEANUP_NUM_DAYS - + " Unable to delete any preview lessons"); - return 0; - } - - int numDeleted = 0; - - // calculate comparison date - long newestDateToKeep = System.currentTimeMillis() - (numDays * MonitoringService.numMilliSecondsInADay); - Date date = new Date(newestDateToKeep); - // convert data to UTC - MonitoringService.log.info("Deleting all preview lessons before " + date.toString() + " (server time) (" - + newestDateToKeep + ")"); - - // get all the preview sessions older than a particular date. - List sessions = lessonDAO.getPreviewLessonsBeforeDate(date); - Iterator iter = sessions.iterator(); - while (iter.hasNext()) { - Lesson lesson = (Lesson) iter.next(); - try { - deletePreviewLesson(lesson); - numDeleted++; - } catch (Exception e) { - MonitoringService.log - .error("Unable to delete lesson " + lesson.getLessonId() + " due to exception.", e); - } - } - - return numDeleted; - } - /* Grouping and branching related calls */ @Override - //TODO Optimise the database query. Do a single query rather then large collection access + // TODO Optimise the database query. Do a single query rather then large collection access public SortedSet getClassMembersNotGrouped(Long lessonID, Long activityID, boolean useCreateGrouping) { Activity activity = getActivityById(activityID); Grouping grouping = getGroupingForActivity(activity, useCreateGrouping, "getClassMembersNotGrouped"); Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/ComplexLearnerProgressAction.java =================================================================== diff -u -r1af4378c901cea902392d4ef17f9d990f25e16f3 -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/ComplexLearnerProgressAction.java (.../ComplexLearnerProgressAction.java) (revision 1af4378c901cea902392d4ef17f9d990f25e16f3) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/ComplexLearnerProgressAction.java (.../ComplexLearnerProgressAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -18,18 +18,17 @@ * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** - */ - -/* $Id$ */ -package org.lamsfoundation.lams.monitoring.web; + */ +/* $Id$ */ +package org.lamsfoundation.lams.monitoring.web; + import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; -import java.util.TreeSet; import java.util.Vector; import javax.servlet.ServletException; @@ -42,185 +41,194 @@ import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; -import org.lamsfoundation.lams.learning.service.ICoreLearnerService; -import org.lamsfoundation.lams.learning.service.LearnerServiceProxy; import org.lamsfoundation.lams.learningdesign.Activity; -import org.lamsfoundation.lams.learningdesign.ActivityOrderComparator; import org.lamsfoundation.lams.learningdesign.ComplexActivity; import org.lamsfoundation.lams.learningdesign.ParallelActivity; import org.lamsfoundation.lams.learningdesign.SequenceActivity; import org.lamsfoundation.lams.lesson.LearnerProgress; import org.lamsfoundation.lams.monitoring.dto.ContributeActivityDTO; import org.lamsfoundation.lams.monitoring.service.IMonitoringService; import org.lamsfoundation.lams.monitoring.service.MonitoringServiceProxy; -import org.lamsfoundation.lams.usermanagement.User; +import org.lamsfoundation.lams.security.SecurityException; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; -import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; -import org.springframework.web.context.support.WebApplicationContextUtils; - + /** * @author jliew * - * @struts:action path="/complexProgress" - * validate="false" + * @struts:action path="/complexProgress" validate="false" * @struts.action-forward name = "complexProgress" path = ".complexProgress" * @struts.action-forward name = "parallelProgress" path = "/parallelProgress.jsp" */ public class ComplexLearnerProgressAction extends Action { - private static Logger log = Logger.getLogger(ComplexLearnerProgressAction.class); + private static Logger log = Logger.getLogger(ComplexLearnerProgressAction.class); - public ActionForward execute(ActionMapping mapping, - ActionForm form, - HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { - - Long activityID = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID, false); - Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, false); - Integer userID = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false); - - IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet().getServletContext()); - Activity activity = monitoringService.getActivityById(activityID); - - HttpSession ss = SessionManager.getSession(); - UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); - - if (activity.isParallelActivity()) { + @Override + public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { - ArrayList urls = new ArrayList(); - ParallelActivity parallelActivity = (ParallelActivity)activity; - Set parallels = parallelActivity.getActivities(); - Iterator i = parallels.iterator(); - while (i.hasNext()) { - Activity a = (Activity)i.next(); - // get learner progress url for this parallel activity - urls.add(monitoringService.getLearnerActivityURL(lessonID, a.getActivityId(), userID, user.getUserID())); - } - request.setAttribute("parallelUrls", urls); - return mapping.findForward("parallelProgress"); - } + Long activityID = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID, false); + Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, false); + Integer userID = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, false); - else { - - HashMap statusMap = new HashMap(); - HashMap urlMap = new HashMap(); - LearnerProgress learnerProgress = monitoringService.getLearnerProgress(userID, lessonID); - request.setAttribute("hasSequenceActivity", false); - List subActivities = new ArrayList(); - - if (activity.isOptionsActivity() || activity.isBranchingActivity()) { - - ComplexActivity complexActivity = (ComplexActivity)activity; - - Iterator i = complexActivity.getActivities().iterator(); - - // iterate through each optional or branching activity - while (i.hasNext()) { - Activity aNext = (Activity)i.next(); - - // make sure have castable object, not a CGLIB class - Activity a = monitoringService.getActivityById(aNext.getActivityId()); - ContributeActivityDTO dto = new ContributeActivityDTO(a); - subActivities.add(dto); + IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() + .getServletContext()); + Activity activity = monitoringService.getActivityById(activityID); - Byte status = learnerProgress.getProgressState(a); - statusMap.put(a.getActivityId(), status); - - if (a.isSequenceActivity()) { - request.setAttribute("hasSequenceActivity", true); - // map learner progress urls of each activity in the sequence - SequenceActivity sequenceActivity = (SequenceActivity) a; - dto.setChildActivities(new Vector ()); - processSequenceChildren(lessonID, userID, - monitoringService, user, statusMap, urlMap, - learnerProgress, sequenceActivity, dto, null); - } else { - if (status.equals(LearnerProgress.ACTIVITY_ATTEMPTED) || status.equals(LearnerProgress.ACTIVITY_COMPLETED)) { - urlMap.put(a.getActivityId(), monitoringService.getLearnerActivityURL(lessonID, a.getActivityId(), userID, user.getUserID())); - } - } - } - - } else if ( activity.isSequenceActivity() ) { + HttpSession ss = SessionManager.getSession(); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); - SequenceActivity sequenceActivity = (SequenceActivity) activity; - processSequenceChildren(lessonID, userID, - monitoringService, user, statusMap, urlMap, - learnerProgress, sequenceActivity, null, subActivities); - - } else { - log.error("ComplexLearnerProgress trying to deal with a activity type it doesn't expect. Activity is "+activity); - return null; - } + if (activity.isParallelActivity()) { - // learner progress urls for children of the sequence activities - request.setAttribute("urlMap", urlMap); - // boolean flags for whether an activity is started - request.setAttribute("statusMap", statusMap); - // set of child activities - request.setAttribute("subActivities", subActivities); - // main activity title - request.setAttribute("activityTitle", activity.getTitle()); - - return mapping.findForward("complexProgress"); + ArrayList urls = new ArrayList(); + ParallelActivity parallelActivity = (ParallelActivity) activity; + Set parallels = parallelActivity.getActivities(); + Iterator i = parallels.iterator(); + try { + while (i.hasNext()) { + Activity a = (Activity) i.next(); + // get learner progress url for this parallel activity + urls.add(monitoringService.getLearnerActivityURL(lessonID, a.getActivityId(), userID, + user.getUserID())); } - + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + + request.setAttribute("parallelUrls", urls); + return mapping.findForward("parallelProgress"); } - /** - * Process the children of the sequence. Best done by traversing the transitions, with the first - * activity being the default activity for the sequence. - * - * If the page is for a SequenceActivity the subActivities list should be included as a parameter and - * parentContributeActivityDTO will be null. - * - * If the page is for a Branching or Optional Sequence activity then subActivities will be null - * (as the sequence activities go in the subactivities list) but parentContributeActivityDTO should not - * be null. - * - * @param lessonID - * @param userID - * @param monitoringService - * @param user - * @param statusMap - * @param urlMap - * @param learnerProgress - * @param sequenceActivity - * @param subActivities - * @param parentContributeActivityDTO - * @throws IOException - */ - private void processSequenceChildren(Long lessonID, Integer userID, - IMonitoringService monitoringService, UserDTO user, - HashMap statusMap, HashMap urlMap, - LearnerProgress learnerProgress, SequenceActivity sequenceActivity, - ContributeActivityDTO parentContributeActivityDTO, List subActivities) - throws IOException { - Activity child = sequenceActivity.getDefaultActivity(); - while ( child != null ) { - Byte status = learnerProgress.getProgressState(child); - statusMap.put(child.getActivityId(),status); - if (status.equals(LearnerProgress.ACTIVITY_ATTEMPTED) || status.equals(LearnerProgress.ACTIVITY_COMPLETED)) { - // learner progress url - urlMap.put(child.getActivityId(), - monitoringService.getLearnerActivityURL(lessonID, child.getActivityId(), userID, user.getUserID())); + else { + + HashMap statusMap = new HashMap(); + HashMap urlMap = new HashMap(); + LearnerProgress learnerProgress = monitoringService.getLearnerProgress(userID, lessonID); + request.setAttribute("hasSequenceActivity", false); + List subActivities = new ArrayList(); + + if (activity.isOptionsActivity() || activity.isBranchingActivity()) { + + ComplexActivity complexActivity = (ComplexActivity) activity; + + Iterator i = complexActivity.getActivities().iterator(); + + // iterate through each optional or branching activity + while (i.hasNext()) { + Activity aNext = (Activity) i.next(); + + // make sure have castable object, not a CGLIB class + Activity a = monitoringService.getActivityById(aNext.getActivityId()); + ContributeActivityDTO dto = new ContributeActivityDTO(a); + subActivities.add(dto); + + Byte status = learnerProgress.getProgressState(a); + statusMap.put(a.getActivityId(), status); + + if (a.isSequenceActivity()) { + request.setAttribute("hasSequenceActivity", true); + // map learner progress urls of each activity in the sequence + SequenceActivity sequenceActivity = (SequenceActivity) a; + dto.setChildActivities(new Vector()); + processSequenceChildren(lessonID, userID, monitoringService, user, statusMap, urlMap, + learnerProgress, sequenceActivity, dto, null); + } else { + if (status.equals(LearnerProgress.ACTIVITY_ATTEMPTED) + || status.equals(LearnerProgress.ACTIVITY_COMPLETED)) { + urlMap.put( + a.getActivityId(), + monitoringService.getLearnerActivityURL(lessonID, a.getActivityId(), userID, + user.getUserID())); } - - ContributeActivityDTO dto = new ContributeActivityDTO(child); - if ( subActivities != null ) - subActivities.add(dto); - if ( parentContributeActivityDTO != null ) - parentContributeActivityDTO.getChildActivities().add(dto); - - if ( child.getTransitionFrom() != null ) { - child = child.getTransitionFrom().getToActivity(); - } else { - child = null; - } + } } + + } else if (activity.isSequenceActivity()) { + SequenceActivity sequenceActivity = (SequenceActivity) activity; + try { + processSequenceChildren(lessonID, userID, monitoringService, user, statusMap, urlMap, + learnerProgress, sequenceActivity, null, subActivities); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + + } else { + ComplexLearnerProgressAction.log + .error("ComplexLearnerProgress trying to deal with a activity type it doesn't expect. Activity is " + + activity); + return null; + } + + // learner progress urls for children of the sequence activities + request.setAttribute("urlMap", urlMap); + // boolean flags for whether an activity is started + request.setAttribute("statusMap", statusMap); + // set of child activities + request.setAttribute("subActivities", subActivities); + // main activity title + request.setAttribute("activityTitle", activity.getTitle()); + + return mapping.findForward("complexProgress"); } + + } + + /** + * Process the children of the sequence. Best done by traversing the transitions, with the first activity being the + * default activity for the sequence. + * + * If the page is for a SequenceActivity the subActivities list should be included as a parameter and + * parentContributeActivityDTO will be null. + * + * If the page is for a Branching or Optional Sequence activity then subActivities will be null (as the sequence + * activities go in the subactivities list) but parentContributeActivityDTO should not be null. + * + * @param lessonID + * @param userID + * @param monitoringService + * @param user + * @param statusMap + * @param urlMap + * @param learnerProgress + * @param sequenceActivity + * @param subActivities + * @param parentContributeActivityDTO + * @throws IOException + */ + private void processSequenceChildren(Long lessonID, Integer userID, IMonitoringService monitoringService, + UserDTO user, HashMap statusMap, HashMap urlMap, LearnerProgress learnerProgress, + SequenceActivity sequenceActivity, ContributeActivityDTO parentContributeActivityDTO, + List subActivities) throws IOException { + Activity child = sequenceActivity.getDefaultActivity(); + while (child != null) { + Byte status = learnerProgress.getProgressState(child); + statusMap.put(child.getActivityId(), status); + if (status.equals(LearnerProgress.ACTIVITY_ATTEMPTED) || status.equals(LearnerProgress.ACTIVITY_COMPLETED)) { + // learner progress url + urlMap.put( + child.getActivityId(), + monitoringService.getLearnerActivityURL(lessonID, child.getActivityId(), userID, + user.getUserID())); + } + + ContributeActivityDTO dto = new ContributeActivityDTO(child); + if (subActivities != null) { + subActivities.add(dto); + } + if (parentContributeActivityDTO != null) { + parentContributeActivityDTO.getChildActivities().add(dto); + } + + if (child.getTransitionFrom() != null) { + child = child.getTransitionFrom().getToActivity(); + } else { + child = null; + } + } + } } - \ No newline at end of file Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java =================================================================== diff -u -r9234cb75efd86c137c56366bc5b0e2f93aad05ea -r27f1c5a7f08417a5d6f5e4c7faff092f520078a6 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 9234cb75efd86c137c56366bc5b0e2f93aad05ea) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 27f1c5a7f08417a5d6f5e4c7faff092f520078a6) @@ -224,9 +224,14 @@ newLesson = monitoringService.initializeLessonForPreview(title, desc, ldId, getUserId(), customCSV, learnerPresenceAvailable, learnerImAvailable, liveEditEnabled); } else { - newLesson = monitoringService.initializeLesson(title, desc, ldId, organisationId, getUserId(), customCSV, - false, false, learnerExportAvailable, learnerPresenceAvailable, learnerImAvailable, - liveEditEnabled, false, learnerRestart, null, null); + try { + newLesson = monitoringService.initializeLesson(title, desc, ldId, organisationId, getUserId(), + customCSV, false, false, learnerExportAvailable, learnerPresenceAvailable, learnerImAvailable, + liveEditEnabled, false, learnerRestart, null, null); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); + return null; + } } PrintWriter writer = response.getWriter(); @@ -258,9 +263,13 @@ HttpServletResponse response) throws IOException, ServletException { IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); - long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.startLesson(lessonId, getUserId()); + try { + monitoringService.startLesson(lessonId, getUserId()); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } response.setContentType("text/plain;charset=utf-8"); response.getWriter().write("true"); @@ -285,8 +294,13 @@ List learners = parseUserList(request, "learners", allUsers); List staff = parseUserList(request, "monitors", allUsers); - monitoringService.createLessonClassForLesson(lessonId, organisation, learnerGroupName, learners, - staffGroupName, staff, userID); + try { + monitoringService.createLessonClassForLesson(lessonId, organisation, learnerGroupName, learners, + staffGroupName, staff, userID); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson"); + return null; + } return null; } @@ -376,26 +390,30 @@ lesson = monitoringService.initializeLesson(lessonInstanceName, introDescription, ldId, organisationId, userId, null, introEnable, introImage, portfolioEnable, presenceEnable, imEnable, enableLiveEdit, notificationsEnable, learnerRestart, timeLimitIndividual, precedingLessonId); + + monitoringService.createLessonClassForLesson(lesson.getLessonId(), organisation, + learnerGroupInstanceName, lessonInstanceLearners, staffGroupInstanceName, staff, userId); } catch (SecurityException e) { - log.error("Cannot add a lesson for LD: " + ldId, e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given lesson"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation or lesson"); return null; } - monitoringService.createLessonClassForLesson(lesson.getLessonId(), organisation, learnerGroupInstanceName, - lessonInstanceLearners, staffGroupInstanceName, staff, userId); - if (!startMonitor) { - if (schedulingDatetime == null) { - monitoringService.startLesson(lesson.getLessonId(), userId); - } else { - // if lesson should start in few days, set it here - monitoringService.startLessonOnSchedule(lesson.getLessonId(), schedulingDatetime, userId); - } + try { + if (schedulingDatetime == null) { + monitoringService.startLesson(lesson.getLessonId(), userId); + } else { + // if lesson should start in few days, set it here + monitoringService.startLessonOnSchedule(lesson.getLessonId(), schedulingDatetime, userId); + } - // if lesson should finish in few days, set it here - if (timeLimitLesson != null) { - monitoringService.finishLessonOnSchedule(lesson.getLessonId(), timeLimitLesson, userId); + // if lesson should finish in few days, set it here + if (timeLimitLesson != null) { + monitoringService.finishLessonOnSchedule(lesson.getLessonId(), timeLimitLesson, userId); + } + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; } } } @@ -404,13 +422,18 @@ } public ActionForward startOnScheduleLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws ParseException { + HttpServletResponse response) throws ParseException, IOException { IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); String dateStr = WebUtil.readStrParam(request, MonitoringConstants.PARAM_LESSON_START_DATE); Date startDate = MonitoringAction.LESSON_SCHEDULING_DATETIME_FORMAT.parse(dateStr); - monitoringService.startLessonOnSchedule(lessonId, startDate, getUserId()); + try { + monitoringService.startLessonOnSchedule(lessonId, startDate, getUserId()); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } + return null; } @@ -438,7 +461,11 @@ IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.archiveLesson(lessonId, getUserId()); + try { + monitoringService.unsuspendLesson(lessonId, getUserId()); + } catch (SecurityException e) { + monitoringService.archiveLesson(lessonId, getUserId()); + } return null; } @@ -466,7 +493,11 @@ IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.unarchiveLesson(lessonId, getUserId()); + try { + monitoringService.unarchiveLesson(lessonId, getUserId()); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } return null; } @@ -488,7 +519,11 @@ IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.suspendLesson(lessonId, getUserId()); + try { + monitoringService.suspendLesson(lessonId, getUserId()); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } return null; } @@ -509,7 +544,11 @@ IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.unsuspendLesson(lessonId, getUserId()); + try { + monitoringService.unsuspendLesson(lessonId, getUserId()); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } return null; } @@ -535,21 +574,14 @@ */ public ActionForward removeLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException, ServletException { - JSONObject jsonObject = new JSONObject(); - Object removeLessonResult = Boolean.TRUE.toString(); IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); + long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + // if this method throws an Exception, there will be no removeLesson=true in the JSON reply + monitoringService.removeLesson(lessonId, getUserId()); - try { - long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); - monitoringService.removeLesson(lessonId, getUserId()); - - } catch (Exception e) { - FlashMessage flashMessage = handleException(e, "removeLesson", monitoringService); - removeLessonResult = flashMessage.getMessageValue(); - } - - jsonObject.put("removeLesson", removeLessonResult); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("removeLesson", true); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(jsonObject); return null; @@ -593,8 +625,14 @@ boolean removeLearnerContent = WebUtil.readBooleanParam(request, MonitoringConstants.PARAM_REMOVE_LEARNER_CONTENT, false); - String message = monitoringService.forceCompleteActivitiesByUser(learnerId, requesterId, lessonId, activityId, - removeLearnerContent); + String message = null; + try { + message = monitoringService.forceCompleteActivitiesByUser(learnerId, requesterId, lessonId, activityId, + removeLearnerContent); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } if (LamsDispatchAction.log.isDebugEnabled()) { LamsDispatchAction.log.debug("Force complete for learner " + learnerId + " lesson " + lessonId + ". " @@ -731,6 +769,7 @@ .getServletContext()); try { Long lessonID = new Long(WebUtil.readLongParam(request, "lessonID")); + getSecurityService().isLessonMonitor(lessonID, getUserId(), "get learning design details", true); wddxPacket = monitoringService.getLearningDesignDetails(lessonID); } catch (Exception e) { wddxPacket = handleException(e, "getLearningDesignDetails", monitoringService).serializeMessage(); @@ -804,9 +843,13 @@ Integer learnerUserID = new Integer(WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID)); Long activityID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID)); Long lessonID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID)); - - String url = monitoringService.getLearnerActivityURL(lessonID, activityID, learnerUserID, getUserId()); - return redirectToURL(mapping, response, url); + try { + String url = monitoringService.getLearnerActivityURL(lessonID, activityID, learnerUserID, getUserId()); + return redirectToURL(mapping, response, url); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } } /** Calls the server to bring up the activity's monitoring page. Assumes destination is a new window */ @@ -817,9 +860,13 @@ Long activityID = new Long(WebUtil.readLongParam(request, "activityID")); Long lessonID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID)); String contentFolderID = WebUtil.readStrParam(request, "contentFolderID"); - String url = monitoringService.getActivityMonitorURL(lessonID, activityID, contentFolderID, getUserId()); - - return redirectToURL(mapping, response, url); + try { + String url = monitoringService.getActivityMonitorURL(lessonID, activityID, contentFolderID, getUserId()); + return redirectToURL(mapping, response, url); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } } public ActionForward moveLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, @@ -855,12 +902,9 @@ DateFormat sfm = new SimpleDateFormat("yyyyMMdd_HHmmss"); lessonDTO.setCreateDateTimeStr(sfm.format(lessonDTO.getCreateDateTime())); } - - try { - getSecurityService().checkIsLessonMonitor(lessonId, user.getUserID()); - } catch (SecurityException e) { - log.error("Cannot monitor lesson", e); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the given lesson"); + + if (!getSecurityService().isLessonMonitor(lessonId, user.getUserID(), "monitor lesson", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); return null; } @@ -954,14 +998,20 @@ public ActionForward getLessonDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + HttpSession ss = SessionManager.getSession(); + UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + if (!getSecurityService().isLessonMonitor(lessonId, user.getUserID(), "get lesson details", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } + JSONObject responseJSON = new JSONObject(); Lesson lesson = getLessonService().getLesson(lessonId); LessonDetailsDTO lessonDetails = lesson.getLessonDetails(); String contentFolderId = lessonDetails.getContentFolderID(); - HttpSession ss = SessionManager.getSession(); - UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); + Locale userLocale = new Locale(user.getLocaleLanguage(), user.getLocaleCountry()); responseJSON.put(AttributeNames.PARAM_LEARNINGDESIGN_ID, lessonDetails.getLearningDesignID()); @@ -995,12 +1045,16 @@ public ActionForward getLessonProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); + Integer monitorUserId = getUserId(); + if (!getSecurityService().isLessonMonitor(lessonId, monitorUserId, "get lesson progress", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } Long branchingActivityId = WebUtil.readLongParam(request, "branchingActivityID", true); Lesson lesson = getLessonService().getLesson(lessonId); IMonitoringService monitoringService = MonitoringServiceProxy.getMonitoringService(getServlet() .getServletContext()); - Integer monitorUserId = getUserId(); LessonDetailsDTO lessonDetails = lesson.getLessonDetails(); String contentFolderId = lessonDetails.getContentFolderID(); @@ -1149,15 +1203,15 @@ * Preview. */ - if (new Long(lessonID) != null) { - + try { monitoringService.createPreviewClassForLesson(userID, lessonID); monitoringService.startLesson(lessonID, getUserId()); - - flashMessage = new FlashMessage("startPreviewSession", new Long(lessonID)); - + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson"); + return null; } - + + flashMessage = new FlashMessage("startPreviewSession", new Long(lessonID)); } catch (Exception e) { flashMessage = handleException(e, "startPreviewSession", monitoringService); } @@ -1241,7 +1295,11 @@ Long lessonID = new Long(WebUtil.readLongParam(request, "lessonID")); Integer userID = getUserId(); Boolean learnerExportPortfolioAvailable = WebUtil.readBooleanParam(request, "learnerExportPortfolio", false); - monitoringService.setLearnerPortfolioAvailable(lessonID, userID, learnerExportPortfolioAvailable); + try { + monitoringService.setLearnerPortfolioAvailable(lessonID, userID, learnerExportPortfolioAvailable); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } return null; } @@ -1258,12 +1316,15 @@ Integer userID = getUserId(); Boolean presenceAvailable = WebUtil.readBooleanParam(request, "presenceAvailable", false); - monitoringService.setPresenceAvailable(lessonID, userID, presenceAvailable); + try { + monitoringService.setPresenceAvailable(lessonID, userID, presenceAvailable); - if (!presenceAvailable) { - monitoringService.setPresenceImAvailable(lessonID, userID, false); + if (!presenceAvailable) { + monitoringService.setPresenceImAvailable(lessonID, userID, false); + } + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); } - return null; } @@ -1278,7 +1339,12 @@ Long lessonID = new Long(WebUtil.readLongParam(request, "lessonID")); Integer userID = getUserId(); Boolean presenceImAvailable = WebUtil.readBooleanParam(request, "presenceImAvailable", false); - monitoringService.setPresenceImAvailable(lessonID, userID, presenceImAvailable); + + try { + monitoringService.setPresenceImAvailable(lessonID, userID, presenceImAvailable); + } catch (SecurityException e) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + } return null; } @@ -1294,7 +1360,10 @@ long lessonID = WebUtil.readLongParam(request, "lessonID"); // check monitor privledges - monitoringService.openTimeChart(lessonID, getUserId()); + if (!getSecurityService().isLessonMonitor(lessonID, getUserId(), "open time chart", false)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); + return null; + } request.setAttribute("lessonID", lessonID); request.setAttribute("learnerID", WebUtil.readLongParam(request, "learnerID", true));