Search in sources :

Example 11 with UnauthorizedAccessException

use of teammates.common.exception.UnauthorizedAccessException in project teammates by TEAMMATES.

the class InstructorCourseEditPageActionTest method testExecuteAndPostProcess.

@Override
@Test
public void testExecuteAndPostProcess() {
    InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1");
    String instructorId = instructor1OfCourse1.googleId;
    String courseId = instructor1OfCourse1.courseId;
    gaeSimulation.loginAsInstructor(instructorId);
    ______TS("Not enough parameters");
    verifyAssumptionFailure();
    ______TS("Typical case: open the course edit page");
    String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseId };
    InstructorCourseEditPageAction editAction = getAction(submissionParams);
    ShowPageResult pageResult = getShowPageResult(editAction);
    assertEquals(getPageResultDestination(Const.ViewURIs.INSTRUCTOR_COURSE_EDIT, false, "idOfInstructor1OfCourse1"), pageResult.getDestinationWithParams());
    assertFalse(pageResult.isError);
    assertEquals("", pageResult.getStatusMessage());
    InstructorCourseEditPageData data = (InstructorCourseEditPageData) pageResult.data;
    assertEquals(CoursesLogic.inst().getCourse(courseId).toString(), data.getCourse().toString());
    verifySameInstructorList(InstructorsLogic.inst().getInstructorsForCourse(courseId), data.getInstructorPanelList());
    String expectedLogSegment = "instructorCourseEdit Page Load<br>" + "Editing information for Course <span class=\"bold\">[" + courseId + "]</span>";
    AssertHelper.assertContains(expectedLogSegment, editAction.getLogMessage());
    ______TS("Typical case: open the course edit page with instructor's email");
    submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.INSTRUCTOR_EMAIL, "instr1@course1.tmt", Const.ParamsNames.COURSE_EDIT_MAIN_INDEX, "1" };
    editAction = getAction(submissionParams);
    pageResult = getShowPageResult(editAction);
    assertEquals(getPageResultDestination(Const.ViewURIs.INSTRUCTOR_COURSE_EDIT, false, "idOfInstructor1OfCourse1"), pageResult.getDestinationWithParams());
    assertFalse(pageResult.isError);
    assertEquals("", pageResult.getStatusMessage());
    data = (InstructorCourseEditPageData) pageResult.data;
    assertEquals(CoursesLogic.inst().getCourse(courseId).toString(), data.getCourse().toString());
    assertEquals(1, data.getInstructorPanelList().size());
    expectedLogSegment = "instructorCourseEdit Page Load<br>" + "Editing information for Course <span class=\"bold\">[" + courseId + "]</span>";
    AssertHelper.assertContains(expectedLogSegment, editAction.getLogMessage());
    ______TS("Masquerade mode");
    InstructorAttributes instructor = typicalBundle.instructors.get("instructor4");
    instructorId = instructor.googleId;
    courseId = instructor.courseId;
    gaeSimulation.loginAsAdmin("admin.user");
    submissionParams = new String[] { Const.ParamsNames.USER_ID, instructorId, Const.ParamsNames.COURSE_ID, courseId };
    editAction = getAction(submissionParams);
    pageResult = getShowPageResult(editAction);
    assertEquals(getPageResultDestination(Const.ViewURIs.INSTRUCTOR_COURSE_EDIT, false, "idOfInstructor4"), pageResult.getDestinationWithParams());
    assertFalse(pageResult.isError);
    assertEquals("", pageResult.getStatusMessage());
    data = (InstructorCourseEditPageData) pageResult.data;
    assertEquals(CoursesLogic.inst().getCourse(courseId).toString(), data.getCourse().toString());
    verifySameInstructorList(InstructorsLogic.inst().getInstructorsForCourse(courseId), data.getInstructorPanelList());
    expectedLogSegment = "instructorCourseEdit Page Load<br>" + "Editing information for Course <span class=\"bold\">[" + courseId + "]</span>";
    AssertHelper.assertContains(expectedLogSegment, editAction.getLogMessage());
    ______TS("Failure case: edit a non-existing course");
    CoursesLogic.inst().deleteCourseCascade(courseId);
    submissionParams = new String[] { Const.ParamsNames.USER_ID, instructorId, Const.ParamsNames.COURSE_ID, courseId };
    try {
        editAction = getAction(submissionParams);
        pageResult = getShowPageResult(editAction);
        signalFailureToDetectException();
    } catch (UnauthorizedAccessException e) {
        assertEquals("Trying to access system using a non-existent instructor entity", e.getMessage());
    }
}
Also used : InstructorCourseEditPageAction(teammates.ui.controller.InstructorCourseEditPageAction) ShowPageResult(teammates.ui.controller.ShowPageResult) UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) InstructorCourseEditPageData(teammates.ui.pagedata.InstructorCourseEditPageData) InstructorAttributes(teammates.common.datatransfer.attributes.InstructorAttributes) Test(org.testng.annotations.Test)

Example 12 with UnauthorizedAccessException

use of teammates.common.exception.UnauthorizedAccessException in project teammates by TEAMMATES.

the class ControllerServlet method doPost.

@Override
// used as fallback
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public final void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserType userType = new GateKeeper().getCurrentUser();
    String url = HttpRequestHelper.getRequestedUrl(req);
    Map<String, String[]> params = HttpRequestHelper.getParameterMap(req);
    try {
        /* We are using the Template Method Design Pattern here.
             * This method contains the high level logic of the request processing.
             * Concrete details of the processing steps are to be implemented by child
             * classes, based on request-specific needs.
             */
        long startTime = System.currentTimeMillis();
        log.info("Request received : [" + req.getMethod() + "] " + req.getRequestURL().toString() + ":" + HttpRequestHelper.printRequestParameters(req));
        log.info("User agent : " + req.getHeader("User-Agent"));
        Action c = new ActionFactory().getAction(req);
        if (c.isValidUser()) {
            ActionResult actionResult = c.executeAndPostProcess();
            actionResult.writeSessionTokenToCookieIfRequired(req, resp);
            actionResult.send(req, resp);
        } else {
            resp.sendRedirect(c.getAuthenticationRedirectUrl());
        }
        long timeTaken = System.currentTimeMillis() - startTime;
        // This is the log message that is used to generate the 'activity log' for the admin.
        log.info(c.getLogMessage() + "|||" + timeTaken);
    } catch (PageNotFoundException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ACTION_NOT_FOUND_PAGE, params, url));
    } catch (EntityNotFoundException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ENTITY_NOT_FOUND_PAGE, params, url));
    } catch (FeedbackSessionNotVisibleException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        req.getSession().setAttribute(Const.ParamsNames.FEEDBACK_SESSION_NOT_VISIBLE, e.getStartTimeString());
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.FEEDBACK_SESSION_NOT_VISIBLE, params, url));
    } catch (InvalidOriginException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.INVALID_ORIGIN, params, url));
    } catch (UnauthorizedAccessException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.UNAUTHORIZED, params, url));
    } catch (DeadlineExceededException | DatastoreTimeoutException e) {
        /*This exception may not be caught because GAE kills
              the request soon after throwing it. In that case, the error
              message in the log will be emailed to the admin by a separate
              cron job.*/
        cleanUpStatusMessageInSession(req);
        log.severe("Deadline exceeded exception caught by ControllerServlet : " + TeammatesException.toStringWithStackTrace(e));
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.DEADLINE_EXCEEDED_ERROR_PAGE, params, url));
    } catch (InvalidPostParametersException e) {
        String requestUrl = req.getRequestURL().toString();
        log.info(e.getMessage());
        cleanUpStatusMessageInSession(req);
        List<StatusMessage> statusMessagesToUser = new ArrayList<>();
        statusMessagesToUser.add(new StatusMessage(Const.StatusMessages.NULL_POST_PARAMETER_MESSAGE, StatusMessageColor.WARNING));
        req.getSession().setAttribute(Const.ParamsNames.STATUS_MESSAGES_LIST, statusMessagesToUser);
        if (requestUrl.contains("/instructor")) {
            resp.sendRedirect(Const.ActionURIs.INSTRUCTOR_HOME_PAGE);
        } else if (requestUrl.contains("/student")) {
            resp.sendRedirect(Const.ActionURIs.STUDENT_HOME_PAGE);
        } else if (requestUrl.contains("/admin")) {
            resp.sendRedirect(Const.ActionURIs.ADMIN_HOME_PAGE);
        } else {
            cleanUpStatusMessageInSession(req);
            resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ERROR_PAGE, params, url));
        }
    } catch (Throwable t) {
        /* Log only stack trace to prevent delay in termination of request
             * which can result in GAE shutting down the instance.
             * Note that severe logs are sent by email automatically in the cron job auto/compileLogs.
             */
        log.severe("Unexpected exception caught by ControllerServlet : " + TeammatesException.toStringWithStackTrace(t));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ERROR_PAGE, params, url));
    }
}
Also used : InvalidPostParametersException(teammates.common.exception.InvalidPostParametersException) LogMessageGenerator(teammates.common.util.LogMessageGenerator) DeadlineExceededException(com.google.apphosting.api.DeadlineExceededException) EntityNotFoundException(teammates.common.exception.EntityNotFoundException) DatastoreTimeoutException(com.google.appengine.api.datastore.DatastoreTimeoutException) StatusMessage(teammates.common.util.StatusMessage) PageNotFoundException(teammates.common.exception.PageNotFoundException) FeedbackSessionNotVisibleException(teammates.common.exception.FeedbackSessionNotVisibleException) InvalidOriginException(teammates.common.exception.InvalidOriginException) UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) GateKeeper(teammates.logic.api.GateKeeper) ArrayList(java.util.ArrayList) List(java.util.List) UserType(teammates.common.datatransfer.UserType)

Example 13 with UnauthorizedAccessException

use of teammates.common.exception.UnauthorizedAccessException in project teammates by TEAMMATES.

the class InstructorFeedbackSubmissionEditPageAction method verifyAccessibleForSpecificUser.

@Override
protected void verifyAccessibleForSpecificUser(FeedbackSessionAttributes session) {
    InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId);
    boolean isCreatorOnly = false;
    gateKeeper.verifyAccessible(instructor, session, isCreatorOnly);
    boolean shouldEnableSubmit = instructor.isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS);
    if (!shouldEnableSubmit && instructor.isAllowedForPrivilegeAnySection(session.getFeedbackSessionName(), Const.ParamsNames.INSTRUCTOR_PERMISSION_SUBMIT_SESSION_IN_SECTIONS)) {
        shouldEnableSubmit = true;
    }
    if (!shouldEnableSubmit) {
        throw new UnauthorizedAccessException("Feedback session [" + session.getFeedbackSessionName() + "] is not accessible to instructor [" + instructor.email + "] for this purpose");
    }
}
Also used : UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) InstructorAttributes(teammates.common.datatransfer.attributes.InstructorAttributes)

Example 14 with UnauthorizedAccessException

use of teammates.common.exception.UnauthorizedAccessException in project teammates by TEAMMATES.

the class LogMessageGeneratorTest method generateLogMessage_servletActionFailure.

@Test
public void generateLogMessage_servletActionFailure() {
    ______TS("With google login");
    UserType loginUser = new UserType("googleIdABC");
    String url = "/randomPage";
    Map<String, String[]> paramMap = new HashMap<>();
    Exception e = new PageNotFoundException("randomPage");
    String logMessagePrefix = "TEAMMATESLOG|||Error when getting ActionName for requestUrl : /randomPage" + "|||Servlet Action Failure|||true|||Unregistered|||Unknown|||googleIdABC|||Unknown|||";
    String generatedMessage = logCenter.generateActionFailureLogMessage(url, paramMap, e, loginUser);
    assertTrue(generatedMessage.startsWith(logMessagePrefix));
    AssertHelper.assertLogIdContainsUserId(generatedMessage, "googleIdABC");
    ______TS("Without google login (with key)");
    url = Const.ActionURIs.STUDENT_COURSE_JOIN;
    paramMap = generateRequestParamsWithRegKey();
    e = new UnauthorizedAccessException("Unknown Registration Key KeyABC");
    generatedMessage = logCenter.generateActionFailureLogMessage(url, paramMap, e, null);
    logMessagePrefix = "TEAMMATESLOG|||studentCourseJoin|||Servlet Action Failure|||true" + "|||Unknown|||Unknown|||Unknown|||Unknown|||";
    assertTrue(generatedMessage.startsWith(logMessagePrefix));
    AssertHelper.assertLogIdContainsUserId(generatedMessage, "student@email.com%CS2103");
}
Also used : PageNotFoundException(teammates.common.exception.PageNotFoundException) HashMap(java.util.HashMap) UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) UserType(teammates.common.datatransfer.UserType) UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) PageNotFoundException(teammates.common.exception.PageNotFoundException) Test(org.testng.annotations.Test)

Example 15 with UnauthorizedAccessException

use of teammates.common.exception.UnauthorizedAccessException in project teammates by TEAMMATES.

the class StudentFeedbackResultsPageAction method execute.

@Override
protected ActionResult execute() throws EntityDoesNotExistException {
    String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID);
    String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME);
    if (courseId == null || feedbackSessionName == null) {
        return createRedirectResult(Const.ActionURIs.STUDENT_HOME_PAGE);
    }
    if (!isJoinedCourse(courseId)) {
        return createPleaseJoinCourseResponse(courseId);
    }
    gateKeeper.verifyAccessible(getCurrentStudent(courseId), logic.getFeedbackSession(feedbackSessionName, courseId));
    StudentFeedbackResultsPageData data = new StudentFeedbackResultsPageData(account, student, sessionToken);
    data.student = getCurrentStudent(courseId);
    data.setBundle(logic.getFeedbackSessionResultsForStudent(feedbackSessionName, courseId, data.student.email));
    if (data.getBundle() == null) {
        // leave this here as a safety net on the off cases that GateKeeper fails to catch the Exception
        throw new EntityDoesNotExistException("Feedback session " + feedbackSessionName + " does not exist in " + courseId + ".");
    }
    if (!data.getBundle().feedbackSession.isPublished()) {
        throw new UnauthorizedAccessException("This feedback session is not yet visible.");
    }
    if (data.getBundle().isStudentHasSomethingNewToSee(data.student)) {
        statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_RESULTS_SOMETHINGNEW, StatusMessageColor.INFO));
    } else {
        statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_RESULTS_NOTHINGNEW, StatusMessageColor.WARNING));
    }
    statusToAdmin = "Show student feedback result page<br>" + "Session Name: " + feedbackSessionName + "<br>" + "Course ID: " + courseId;
    Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> questionsWithResponses = data.getBundle().getQuestionResponseMapSortedByRecipient();
    data.init(questionsWithResponses);
    return createShowPageResult(Const.ViewURIs.STUDENT_FEEDBACK_RESULTS, data);
}
Also used : UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) FeedbackQuestionAttributes(teammates.common.datatransfer.attributes.FeedbackQuestionAttributes) List(java.util.List) StudentFeedbackResultsPageData(teammates.ui.pagedata.StudentFeedbackResultsPageData) EntityDoesNotExistException(teammates.common.exception.EntityDoesNotExistException) StatusMessage(teammates.common.util.StatusMessage)

Aggregations

UnauthorizedAccessException (teammates.common.exception.UnauthorizedAccessException)32 InstructorAttributes (teammates.common.datatransfer.attributes.InstructorAttributes)18 Test (org.testng.annotations.Test)13 FeedbackSessionAttributes (teammates.common.datatransfer.attributes.FeedbackSessionAttributes)8 ShowPageResult (teammates.ui.controller.ShowPageResult)8 FeedbackQuestionAttributes (teammates.common.datatransfer.attributes.FeedbackQuestionAttributes)6 StudentAttributes (teammates.common.datatransfer.attributes.StudentAttributes)6 AccountAttributes (teammates.common.datatransfer.attributes.AccountAttributes)5 FeedbackResponseAttributes (teammates.common.datatransfer.attributes.FeedbackResponseAttributes)4 EntityNotFoundException (teammates.common.exception.EntityNotFoundException)4 FeedbackQuestionsDb (teammates.storage.api.FeedbackQuestionsDb)4 FeedbackResponsesDb (teammates.storage.api.FeedbackResponsesDb)4 RedirectResult (teammates.ui.controller.RedirectResult)4 CourseAttributes (teammates.common.datatransfer.attributes.CourseAttributes)3 StatusMessage (teammates.common.util.StatusMessage)3 Action (teammates.ui.controller.Action)3 DeadlineExceededException (com.google.apphosting.api.DeadlineExceededException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 UserType (teammates.common.datatransfer.UserType)2