Search in sources :

Example 1 with UserType

use of teammates.common.datatransfer.UserType 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 2 with UserType

use of teammates.common.datatransfer.UserType in project teammates by TEAMMATES.

the class LoginServlet method doPost.

@Override
public final void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    GateKeeper gateKeeper = new GateKeeper();
    UserType user = gateKeeper.getCurrentUser();
    boolean isInstructor = req.getParameter(Const.ParamsNames.LOGIN_INSTRUCTOR) != null;
    boolean isStudent = req.getParameter(Const.ParamsNames.LOGIN_STUDENT) != null;
    boolean isAdmin = req.getParameter(Const.ParamsNames.LOGIN_ADMIN) != null;
    if (isInstructor) {
        if (isMasqueradeMode(user)) {
            resp.sendRedirect(Const.ActionURIs.INSTRUCTOR_HOME_PAGE);
        } else {
            resp.sendRedirect(gateKeeper.getLoginUrl(Const.ActionURIs.INSTRUCTOR_HOME_PAGE));
        }
    } else if (isStudent) {
        if (isMasqueradeMode(user)) {
            resp.sendRedirect(Const.ActionURIs.STUDENT_HOME_PAGE);
        } else {
            resp.sendRedirect(gateKeeper.getLoginUrl(Const.ActionURIs.STUDENT_HOME_PAGE));
        }
    } else if (isAdmin) {
        // TODO: do we need this branch?
        if (isMasqueradeMode(user)) {
            resp.sendRedirect(Const.ActionURIs.ADMIN_HOME_PAGE);
        } else {
            resp.sendRedirect(gateKeeper.getLoginUrl(Const.ActionURIs.ADMIN_HOME_PAGE));
        }
    } else {
        resp.sendRedirect(Const.ViewURIs.ERROR_PAGE);
    }
}
Also used : GateKeeper(teammates.logic.api.GateKeeper) UserType(teammates.common.datatransfer.UserType)

Example 3 with UserType

use of teammates.common.datatransfer.UserType in project teammates by TEAMMATES.

the class GateKeeper method getCurrentUser.

public UserType getCurrentUser() {
    User user = getCurrentGoogleUser();
    if (user == null) {
        return null;
    }
    UserType userType = new UserType(user);
    if (isAdministrator()) {
        userType.isAdmin = true;
    }
    if (isInstructor()) {
        userType.isInstructor = true;
    }
    if (isStudent()) {
        userType.isStudent = true;
    }
    return userType;
}
Also used : User(com.google.appengine.api.users.User) UserType(teammates.common.datatransfer.UserType)

Example 4 with UserType

use of teammates.common.datatransfer.UserType 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 5 with UserType

use of teammates.common.datatransfer.UserType in project teammates by TEAMMATES.

the class Action method authenticateUser.

// These methods are used for user authentication
protected void authenticateUser() {
    UserType currentUser = gateKeeper.getCurrentUser();
    loggedInUser = authenticateAndGetActualUser(currentUser);
    if (isValidUser()) {
        account = authenticateAndGetNominalUser(currentUser);
    }
}
Also used : UserType(teammates.common.datatransfer.UserType)

Aggregations

UserType (teammates.common.datatransfer.UserType)8 Test (org.testng.annotations.Test)3 GateKeeper (teammates.logic.api.GateKeeper)3 HashMap (java.util.HashMap)2 StudentAttributes (teammates.common.datatransfer.attributes.StudentAttributes)2 PageNotFoundException (teammates.common.exception.PageNotFoundException)2 UnauthorizedAccessException (teammates.common.exception.UnauthorizedAccessException)2 LogMessageGenerator (teammates.common.util.LogMessageGenerator)2 BlobKey (com.google.appengine.api.blobstore.BlobKey)1 BlobstoreService (com.google.appengine.api.blobstore.BlobstoreService)1 DatastoreTimeoutException (com.google.appengine.api.datastore.DatastoreTimeoutException)1 User (com.google.appengine.api.users.User)1 DeadlineExceededException (com.google.apphosting.api.DeadlineExceededException)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1 AccountAttributes (teammates.common.datatransfer.attributes.AccountAttributes)1 CourseAttributes (teammates.common.datatransfer.attributes.CourseAttributes)1 InstructorAttributes (teammates.common.datatransfer.attributes.InstructorAttributes)1