Ejemplo n.º 1
0
  private boolean checkAccess(BaseForum baseForum, String userId, String siteId) {

    if (baseForum instanceof OpenForum) {

      // If the supplied user is the super user or an instructor, return true.
      if (securityService.isSuperUser(userId)
          || forumManager.isInstructor(
              userId, Entity.SEPARATOR + SiteService.SITE_SUBTYPE + Entity.SEPARATOR + siteId)) {
        return true;
      }

      OpenForum of = (OpenForum) baseForum;

      // If this is not a draft and is available, return true.
      if (!of.getDraft() && of.getAvailability()) {
        return true;
      }

      // If this is a draft/unavailable forum AND was authored by the current user, return true.
      if ((of.getDraft() || !of.getAvailability()) && of.getCreatedBy().equals(userId)) {
        return true;
      }
    } else if (baseForum instanceof PrivateForum) {
      PrivateForum pf = (PrivateForum) baseForum;
      // If the current user is the creator, return true.
      if (pf.getCreatedBy().equals(userId)) {
        return true;
      }
    }

    return false;
  }
Ejemplo n.º 2
0
  /** @inheritDoc */
  public List getUnassignedMembersInRole(final String siteContext, final Role role) {
    List siteMembers = getSiteMembersInRole(siteContext, role);

    // Get all userUids of all users in sections
    List<String> sectionedUserUids = new ArrayList<String>();
    List sections = getSections(siteContext);
    for (Iterator sectionIter = sections.iterator(); sectionIter.hasNext(); ) {
      CourseSection section = (CourseSection) sectionIter.next();
      List sectionUsers = securityService.unlockUsers(getLock(role), section.getUuid());
      for (Iterator userIter = sectionUsers.iterator(); userIter.hasNext(); ) {
        org.sakaiproject.user.api.User user = (org.sakaiproject.user.api.User) userIter.next();
        sectionedUserUids.add(user.getId());
      }
    }

    // Now generate the list of unsectioned enrollments by subtracting the two collections
    // Since the APIs return different kinds of objects, we need to iterate
    List<ParticipationRecord> unsectionedMembers = new ArrayList<ParticipationRecord>();
    for (Iterator iter = siteMembers.iterator(); iter.hasNext(); ) {
      ParticipationRecord record = (ParticipationRecord) iter.next();
      if (!sectionedUserUids.contains(record.getUser().getUserUid())) {
        unsectionedMembers.add(record);
      }
    }
    return unsectionedMembers;
  }
Ejemplo n.º 3
0
  /** build the context */
  public String buildMainPanelContext(
      VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
    String template = null;

    // if not logged in as the super user, we won't do anything
    if (!securityService.isSuperUser()) {
      context.put("tlang", rb);
      return (String) getContext(rundata).get("template") + "_noaccess";
    }

    // check mode and dispatch
    String mode = (String) state.getAttribute(STATE_MODE);

    if (StringUtils.equals(mode, SINGLE_MODE)) {
      template = buildSingleModeContext(portlet, context, rundata, state);
    } else if (StringUtils.equals(mode, BATCH_MODE)) {
      template = buildBatchModeContext(portlet, context, rundata, state);
    } else if (StringUtils.equals(mode, BATCH_ARCHIVE_CONFIRM_MODE)) {
      template = buildBatchModeArchiveConfirmContext(portlet, context, rundata, state);
    } else if (StringUtils.equals(mode, DOWNLOAD_MODE)) {
      template = buildDownloadContext(portlet, context, rundata, state);
    }

    return (String) getContext(rundata).get("template") + template;
  } // buildMainPanelContext
Ejemplo n.º 4
0
 /** {@inheritDoc} */
 public boolean hasAdmin() {
   boolean superUser = securityService.isSuperUser();
   return (superUser)
       || ("true"
               .equals(
                   serverConfigurationService.getString("search.allow.maintain.admin", "false"))
           && siteService.allowUpdateSite(siteId));
 }
Ejemplo n.º 5
0
  /**
   * doImport called when "eventSubmit_doBatch_Archive_PreProcess" is in the request parameters to
   * do the prep work for archiving a bunch of sites that match the criteria
   */
  public void doBatch_Archive_PreProcess(RunData data, Context context) {

    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.batch.auth"));
      return;
    }

    // if we have a selected term then use that as the batch export param
    String selectedTerm = data.getParameters().getString("archive-term");

    log.debug("selectedTerm: " + selectedTerm);

    if (StringUtils.isBlank(selectedTerm)) {
      addAlert(state, rb.getString("archive.batch.term.text.missingterm"));
      state.setAttribute(STATE_MODE, BATCH_MODE);
      return;
    }

    // set the message
    state.setAttribute(
        "confirmString",
        rb.getFormattedMessage("archive.batch.term.text.confirm.1", new Object[] {selectedTerm}));

    // get the sites that match the criteria
    Map<String, String> propertyCriteria = new HashMap<String, String>();
    propertyCriteria.put("term_eid", selectedTerm);
    List<Site> sites =
        siteService.getSites(
            SelectionType.ANY, null, null, propertyCriteria, SortType.TITLE_ASC, null);

    if (sites.isEmpty()) {
      addAlert(
          state,
          rb.getFormattedMessage("archive.batch.term.text.nosites", new Object[] {selectedTerm}));
      state.setAttribute(STATE_MODE, BATCH_MODE);
      return;
    }

    // convert to new list so that we dont load entire sites into context
    List<SparseSite> ssites = new ArrayList<SparseSite>();
    for (Site s : sites) {
      ssites.add(new SparseSite(s.getId(), s.getTitle()));
    }

    state.setAttribute("sites", ssites);

    // put into state for next pass
    state.setAttribute("selectedTerm", selectedTerm);

    // set mode so we go to next template
    state.setAttribute(STATE_MODE, BATCH_ARCHIVE_CONFIRM_MODE);
  }
Ejemplo n.º 6
0
 /**
  * Checks whether a user is in a role in any learningContext (site or section)
  *
  * @param userUid
  * @param role
  * @param authzRef
  * @return
  */
 private boolean isUserInRole(String userUid, Role role, String authzRef) {
   org.sakaiproject.user.api.User user;
   try {
     user = userDirectoryService.getUser(userUid);
   } catch (UserNotDefinedException ide) {
     log.error("Could not find user with id " + userUid);
     return false;
   }
   if (role.isNone()) {
     // Make sure that the user is in fact NOT in any role with a role marker
     if (securityService.unlock(user, SectionAwareness.INSTRUCTOR_MARKER, authzRef)
         || securityService.unlock(user, SectionAwareness.STUDENT_MARKER, authzRef)
         || securityService.unlock(user, SectionAwareness.TA_MARKER, authzRef)) {
       return false;
     } else {
       return true;
     }
   }
   return securityService.unlock(user, getLock(role), authzRef);
 }
Ejemplo n.º 7
0
  /**
   * doImport called when "eventSubmit_doBatch_Import" is in the request parameters to run an
   * import.
   */
  public void doBatch_Import(RunData data, Context context) {
    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    Hashtable fTable = new Hashtable();

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.batch.auth"));
      return;
    }

    // String fileName = data.getParameters().getString("import-file");
    FileItem fi = data.getParameters().getFileItem("importFile");
    if (fi == null) {
      addAlert(state, rb.getString("archive.batch.missingname"));
    } else {
      // get content
      String content = fi.getString();

      String[] lines = content.split("\n");
      for (int i = 0; i < lines.length; i++) {
        String lineContent = (String) lines[i];
        String[] lineContents = lineContent.split("\t");
        if (lineContents.length == 2) {
          fTable.put(lineContents[0], lineContents[1]);
        } else {
          addAlert(state, rb.getString("archive.batch.wrongformat"));
        }
      }
    }

    if (!fTable.isEmpty()) {
      Enumeration importFileName = fTable.keys();
      int count = 1;
      while (importFileName.hasMoreElements()) {
        String path = StringUtils.trimToNull((String) importFileName.nextElement());
        String siteCreatorName = StringUtils.trimToNull((String) fTable.get(path));
        if (path != null && siteCreatorName != null) {
          String nSiteId = idManager.createUuid();

          try {
            Object[] params = new Object[] {count, path, nSiteId, siteCreatorName};
            addAlert(state, rb.getFormattedMessage("archive.import1", params));
            addAlert(state, archiveService.merge(path, nSiteId, siteCreatorName));

          } catch (Exception ignore) {
          }
        }

        count++;
      }
    }
  }
 /**
  * Establish a security advisor to allow the "embedded" azg work to occur with no need for
  * additional security permissions.
  */
 protected void enableSecurityAdvisorToGetAnnouncement() {
   // put in a security advisor so we can do our podcast work without need
   // of further permissions
   securityService.pushAdvisor(
       new SecurityAdvisor() {
         public SecurityAdvice isAllowed(String userId, String function, String reference) {
           if (function.equals(AnnouncementService.SECURE_ANNC_READ)
               || function.equals(ContentHostingService.AUTH_RESOURCE_READ)) // SAK-23300
           return SecurityAdvice.ALLOWED;
           else return SecurityAdvice.PASS;
         }
       });
 }
Ejemplo n.º 9
0
  /**
   * doArchive called when "eventSubmit_doArchive" is in the request parameters to run the archive.
   */
  public void doArchive(RunData data, Context context) {
    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.limited"));
      return;
    }

    String id = data.getParameters().getString("archive-id");
    if (StringUtils.isNotBlank(id)) {
      String msg = archiveService.archive(id.trim());
      addAlert(state, rb.getFormattedMessage("archive", new Object[] {id}) + " \n " + msg);
    } else {
      addAlert(state, rb.getString("archive.please"));
    }
  } // doArchive
Ejemplo n.º 10
0
  /** doImport called when "eventSubmit_doImport" is in the request parameters to run an import. */
  public void doImport(RunData data, Context context) {
    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.import"));
      return;
    }

    String id = data.getParameters().getString("import-id");
    String file = data.getParameters().getString("import-file");
    if ((id != null) && (id.trim().length() > 0) && (file != null) && (file.trim().length() > 0)) {
      String msg = archiveService.merge(file.trim(), id.trim(), null);
      addAlert(state, rb.getFormattedMessage("archive.import2", new Object[] {file, id}) + msg);
    } else {
      addAlert(state, rb.getString("archive.file"));
    }
  } // doImport
Ejemplo n.º 11
0
 private List getSiteInstructors(String siteContext) {
   Course course = getCourse(siteContext);
   if (course == null) {
     return new ArrayList();
   }
   List sakaiMembers =
       securityService.unlockUsers(SectionAwareness.INSTRUCTOR_MARKER, course.getUuid());
   List<InstructorRecordImpl> membersList = new ArrayList<InstructorRecordImpl>();
   for (Iterator iter = sakaiMembers.iterator(); iter.hasNext(); ) {
     org.sakaiproject.user.api.User sakaiUser = (org.sakaiproject.user.api.User) iter.next();
     User user = SakaiUtil.convertUser(sakaiUser);
     if (user != null) {
       InstructorRecordImpl record = new InstructorRecordImpl(course, user);
       membersList.add(record);
     }
   }
   return membersList;
 }
Ejemplo n.º 12
0
  private List getSiteTeachingAssistants(String siteContext) {
    Course course = getCourse(siteContext);
    if (course == null) {
      return new ArrayList();
    }
    List sakaiMembers = securityService.unlockUsers(SectionAwareness.TA_MARKER, course.getUuid());
    if (log.isDebugEnabled()) log.debug("Site TAs size = " + sakaiMembers.size());

    List<TeachingAssistantRecordImpl> membersList = new ArrayList<TeachingAssistantRecordImpl>();
    for (Iterator iter = sakaiMembers.iterator(); iter.hasNext(); ) {
      org.sakaiproject.user.api.User sakaiUser = (org.sakaiproject.user.api.User) iter.next();
      User user = SakaiUtil.convertUser(sakaiUser);
      if (user != null) {
        TeachingAssistantRecordImpl record = new TeachingAssistantRecordImpl(course, user);
        membersList.add(record);
      }
    }
    return membersList;
  }
Ejemplo n.º 13
0
 private List getSiteEnrollments(String siteContext) {
   Course course = getCourse(siteContext);
   if (course == null) {
     log.error("Could not find course site " + siteContext);
     return new ArrayList();
   }
   List sakaiMembers =
       securityService.unlockUsers(SectionAwareness.STUDENT_MARKER, course.getUuid());
   if (log.isDebugEnabled()) log.debug("Site students size = " + sakaiMembers.size());
   List<EnrollmentRecordImpl> membersList = new ArrayList<EnrollmentRecordImpl>();
   for (Iterator iter = sakaiMembers.iterator(); iter.hasNext(); ) {
     org.sakaiproject.user.api.User sakaiUser = (org.sakaiproject.user.api.User) iter.next();
     User user = SakaiUtil.convertUser(sakaiUser);
     if (user != null) {
       EnrollmentRecordImpl record = new EnrollmentRecordImpl(course, null, user);
       membersList.add(record);
     }
   }
   return membersList;
 }
Ejemplo n.º 14
0
  /** get file */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    if (!securityService.isSuperUser()) {
      log.error("Must be super user to download archives");
      response.sendError(
          HttpServletResponse.SC_FORBIDDEN, "Must be super user to download archives");
      return;
    }

    String archiveName = request.getParameter("archive");
    Path sakaiHome = Paths.get(serverConfigurationService.getSakaiHomePath());
    Path archives =
        sakaiHome.resolve(serverConfigurationService.getString("archive.storage.path", "archive"));

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment;filename=" + archiveName);

    Path archivePath = archives.resolve(archiveName).normalize();
    if (!archivePath.startsWith(archives)) {
      log.error(
          String.format(
              "The archive file (%s) is not inside the archives folder (%s)",
              archivePath.toString(), archives.toString()));
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "Archive param must be a valid site archive. Param was: " + archiveName);
      return;
    }
    OutputStream out = response.getOutputStream();

    try (InputStream in = FileUtils.openInputStream(archivePath.toFile())) {
      IOUtils.copyLarge(in, out);
      out.flush();
      out.close();
    }
  }
Ejemplo n.º 15
0
  /**
   * doImport called when "eventSubmit_doBatch_Archive" is in the request parameters to archive a
   * bunch of sites that match the criteria NOTE. This performs exactly as per a normal archive. Ie
   * if you archive a site twice, you get two copies of the resources. A change needs to be made to
   * the archive service to clean out the archives before each run.
   */
  public void doBatch_Archive(RunData data, Context context) {

    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.batch.auth"));
      return;
    }

    final String selectedTerm = (String) state.getAttribute("selectedTerm");
    final List<SparseSite> sites = (List<SparseSite>) state.getAttribute("sites");
    final Session currentSession =
        sessionManager.getCurrentSession(); // need to pass this into the new thread
    final User currentUser =
        userDirectoryService.getCurrentUser(); // need to pass this into the new thread

    // do the archive in a new thread
    Runnable backgroundRunner =
        new Runnable() {
          public void run() {
            try {
              archiveSites(sites, selectedTerm, currentSession, currentUser);
            } catch (IllegalStateException e) {
              throw e;
            } catch (Exception e) {
              log.error("Batch Archive background runner thread died: " + e, e);
            }
          }
        };
    Thread backgroundThread = new Thread(backgroundRunner);
    backgroundThread.setDaemon(true);
    backgroundThread.start();

    state.setAttribute(STATE_MODE, BATCH_MODE);
  }
 /** remove recent add SecurityAdvisor from stack */
 protected void disableSecurityAdvisor() {
   securityService.popAdvisor();
 }
Ejemplo n.º 17
0
 // ################################################################
 // Private methods
 // ################################################################
 private boolean isSuperUser() {
   return M_secs.isSuperUser();
 }
 public boolean updateScore(String submissionId) {
   boolean saved = false;
   SecurityAdvisor sa =
       new SecurityAdvisor() {
         public SecurityAdvice isAllowed(String userId, String function, String reference) {
           if (AssignmentService.SECURE_GRADE_ASSIGNMENT_SUBMISSION.equals(function)
               || AssignmentService.SECURE_UPDATE_ASSIGNMENT.equals(function)
               || AssignmentService.SECURE_ACCESS_ASSIGNMENT.equals(function)
               || AssignmentService.SECURE_ACCESS_ASSIGNMENT_SUBMISSION.equals(function)) {
             return SecurityAdvice.ALLOWED;
           } else {
             return SecurityAdvice.PASS;
           }
         }
       };
   try {
     securityService.pushAdvisor(sa);
     // first check that submission exists and that it can be graded/override score
     AssignmentSubmission submission = assignmentService.getSubmission(submissionId);
     // only override grades that have never been graded or was last graded by this service
     // this prevents this service from overriding instructor set grades, which take precedent.
     if (submission != null
         && (submission.getGraded() == false
             || submission.getGradedBy() == null
             || "".equals(submission.getGradedBy().trim())
             || AssignmentPeerAssessmentService.class
                 .getName()
                 .equals(submission.getGradedBy().trim()))) {
       List<PeerAssessmentItem> items =
           getPeerAssessmentItems(
               submissionId, submission.getAssignment().getContent().getFactor());
       if (items != null) {
         // scores are stored w/o decimal points, so a score of 3.4 is stored as 34 in the DB
         // add all the scores together and divide it by the number of scores added.  Then round.
         Integer totalScore = 0;
         int denominator = 0;
         for (PeerAssessmentItem item : items) {
           if (!item.isRemoved() && item.getScore() != null) {
             totalScore += item.getScore();
             denominator++;
           }
         }
         if (denominator > 0) {
           totalScore = Math.round(totalScore / denominator);
         } else {
           totalScore = null;
         }
         String totleScoreStr = null;
         if (totalScore != null) {
           totleScoreStr = totalScore.toString();
         }
         boolean changed = false;
         if ((totleScoreStr == null || "".equals(totleScoreStr))
             && (submission.getGrade() == null || "".equals(submission.getGrade()))) {
           // scores are both null, nothing changed
         } else if ((totleScoreStr != null && !"".equals(totleScoreStr))
             && (submission.getGrade() == null || "".equals(submission.getGrade()))) {
           // one score changed, update
           changed = true;
         } else if ((totleScoreStr == null || "".equals(totleScoreStr))
             && (submission.getGrade() != null && !"".equals(submission.getGrade()))) {
           // one score changed, update
           changed = true;
         } else if (!totleScoreStr.equals(submission.getGrade())) {
           changed = true;
         }
         if (changed) {
           AssignmentSubmissionEdit edit = assignmentService.editSubmission(submissionId);
           edit.setGrade(totleScoreStr);
           edit.setGraded(true);
           edit.setGradedBy(AssignmentPeerAssessmentService.class.getName());
           edit.setGradeReleased(false);
           assignmentService.commitEdit(edit);
           saved = true;
         }
       }
     }
   } catch (IdUnusedException e) {
     log.error(e.getMessage(), e);
   } catch (InUseException e) {
     log.error(e.getMessage(), e);
   } catch (PermissionException e) {
     log.error(e.getMessage(), e);
   } finally {
     // remove advisor
     if (sa != null) {
       securityService.popAdvisor(sa);
     }
   }
   return saved;
 }
Ejemplo n.º 19
0
 private boolean hasPermission(String reference, String permission) {
   return M_secs.unlock(permission, reference);
 }