Search in sources :

Example 56 with UserSession

use of org.olat.core.util.UserSession in project openolat by klemens.

the class WebdavStatus method doLock.

/**
 * LOCK Method.
 */
public void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }
    final String path = getRelativePath(req);
    final WebResourceRoot resources = getResources(req);
    if (!resources.canWrite(path)) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }
    UserSession usess = webDAVManager.getUserSession(req);
    LockInfo lock = new LockInfo(usess.getIdentity().getKey(), true, false);
    // Parsing lock request
    // Parsing depth header
    String depthStr = req.getHeader("Depth");
    if (depthStr == null) {
        lock.setDepth(maxDepth);
    } else {
        if (depthStr.equals("0")) {
            lock.setDepth(0);
        } else {
            lock.setDepth(maxDepth);
        }
    }
    if (log.isDebug()) {
        log.debug("Lock the ressource: " + path + " with depth:" + lock.getDepth());
    }
    // Parsing timeout header
    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.setExpiresAt(System.currentTimeMillis() + (lockDuration * 1000));
    int lockRequestType = LOCK_CREATION;
    Node lockInfoNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder(req);
    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (IOException e) {
        lockRequestType = LOCK_REFRESH;
    } catch (SAXException e) {
        lockRequestType = LOCK_REFRESH;
    }
    if (lockInfoNode != null) {
        // Reading lock information
        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;
        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch(currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String nodeName = currentNode.getNodeName();
                    if (nodeName.endsWith("lockscope")) {
                        lockScopeNode = currentNode;
                    }
                    if (nodeName.endsWith("locktype")) {
                        lockTypeNode = currentNode;
                    }
                    if (nodeName.endsWith("owner")) {
                        lockOwnerNode = currentNode;
                    }
                    break;
            }
        }
        if (lockScopeNode != null) {
            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        String tempScope = currentNode.getNodeName();
                        if (tempScope.indexOf(':') != -1) {
                            lock.setScope(tempScope.substring(tempScope.indexOf(':') + 1));
                        } else {
                            lock.setScope(tempScope);
                        }
                        break;
                }
            }
            if (lock.getScope() == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }
        if (lockTypeNode != null) {
            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        break;
                    case Node.ELEMENT_NODE:
                        String tempType = currentNode.getNodeName();
                        if (tempType.indexOf(':') != -1) {
                            lock.setType(tempType.substring(tempType.indexOf(':') + 1));
                        } else {
                            lock.setType(tempType);
                        }
                        break;
                }
            }
            if (lock.getType() == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }
        if (lockOwnerNode != null) {
            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch(currentNode.getNodeType()) {
                    case Node.TEXT_NODE:
                        lock.setOwner(lock.getOwner() + currentNode.getNodeValue());
                        break;
                    case Node.ELEMENT_NODE:
                        strWriter = new StringWriter();
                        domWriter = new DOMWriter(strWriter, true);
                        domWriter.print(currentNode);
                        lock.setOwner(lock.getOwner() + strWriter.toString());
                        break;
                }
            }
            if (lock.getOwner() == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.setOwner("");
        }
    }
    final WebResource resource = resources.getResource(path);
    lock.setWebResource(resource);
    Iterator<LockInfo> locksList = null;
    if (lockRequestType == LOCK_CREATION) {
        // Generating lock id
        String lockToken = lockManager.generateLockToken(lock, usess.getIdentity().getKey());
        if (resource.isDirectory() && lock.getDepth() == maxDepth) {
            // Locking a collection (and all its member resources)
            // Checking if a child resource of this collection is
            // already locked
            Vector<String> lockPaths = new Vector<String>();
            locksList = lockManager.getCollectionLocks();
            while (locksList.hasNext()) {
                LockInfo currentLock = locksList.next();
                if (currentLock.hasExpired()) {
                    WebResource currentLockedResource = resources.getResource(currentLock.getWebPath());
                    lockManager.removeResourceLock(currentLockedResource);
                    continue;
                }
                if ((currentLock.getWebPath().startsWith(lock.getWebPath())) && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.getWebPath());
                }
            }
            locksList = lockManager.getResourceLocks();
            while (locksList.hasNext()) {
                LockInfo currentLock = locksList.next();
                if (currentLock.hasExpired()) {
                    WebResource currentLockedResource = resources.getResource(currentLock.getWebPath());
                    lockManager.removeResourceLock(currentLockedResource);
                    continue;
                }
                if ((currentLock.getWebPath().startsWith(lock.getWebPath())) && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.getWebPath());
                }
            }
            if (!lockPaths.isEmpty()) {
                // One of the child paths was locked
                // We generate a multistatus error report
                Enumeration<String> lockPathsList = lockPaths.elements();
                resp.setStatus(WebdavStatus.SC_CONFLICT);
                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();
                generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING);
                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement("D", "response", XMLWriter.OPENING);
                    generatedXML.writeElement("D", "href", XMLWriter.OPENING);
                    generatedXML.writeText(lockPathsList.nextElement());
                    generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement("D", "status", XMLWriter.CLOSING);
                    generatedXML.writeElement("D", "response", XMLWriter.CLOSING);
                }
                generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);
                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();
                return;
            }
            boolean addLock = true;
            // Checking if there is already a shared lock on this path
            locksList = lockManager.getCollectionLocks();
            while (locksList.hasNext()) {
                LockInfo currentLock = locksList.next();
                if (currentLock.getWebPath().equals(lock.getWebPath())) {
                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }
                    currentLock.addToken(lockToken);
                    lock = currentLock;
                    addLock = false;
                }
            }
            if (addLock) {
                lock.addToken(lockToken);
                lockManager.addCollectionLock(lock);
            }
        } else {
            // Locking a single resource
            // Retrieving an already existing lock on that resource
            WebResource lockedResource = resources.getResource(lock.getWebPath());
            LockInfo presentLock = lockManager.getResourceLock(lockedResource);
            if (presentLock != null) {
                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.setWebDAVLock(true);
                    presentLock.addToken(lockToken);
                    lock = presentLock;
                }
            } else {
                lock.addToken(lockToken);
                lockManager.putResourceLock(lockedResource, lock);
                // Checking if a resource exists at this path
                if (!resource.exists()) {
                    // "Creating" a lock-null resource
                    int slash = lock.getWebPath().lastIndexOf('/');
                    String parentPath = lock.getWebPath().substring(0, slash);
                    WebResource parentResource = resources.getResource(parentPath);
                    Vector<String> lockNulls = lockManager.getLockNullResource(parentResource);
                    if (lockNulls == null) {
                        lockNulls = new Vector<String>();
                        lockManager.putLockNullResource(parentPath, lockNulls);
                    }
                    lockNulls.addElement(lock.getWebPath());
                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }
        }
    }
    if (lockRequestType == LOCK_REFRESH) {
        String ifHeader = req.getHeader("If");
        if (ifHeader == null)
            ifHeader = "";
        // Checking resource locks
        LockInfo toRenew = lockManager.getResourceLock(resource);
        if (toRenew != null) {
            // At least one of the tokens of the locks must have been given
            Iterator<String> tokenList = toRenew.tokens();
            while (tokenList.hasNext()) {
                String token = tokenList.next();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.setExpiresAt(lock.getExpiresAt());
                    toRenew.setWebDAVLock(true);
                    lock = toRenew;
                }
            }
        }
        // Checking inheritable collection locks
        Iterator<LockInfo> collectionLocksList = lockManager.getCollectionLocks();
        while (collectionLocksList.hasNext()) {
            toRenew = collectionLocksList.next();
            if (path.equals(toRenew.getWebPath())) {
                Iterator<String> tokenList = toRenew.tokens();
                while (tokenList.hasNext()) {
                    String token = tokenList.next();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.setExpiresAt(lock.getExpiresAt());
                        lock = toRenew;
                    }
                }
            }
        }
    }
    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING);
    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING);
    lock.toXML(generatedXML);
    generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING);
    generatedXML.writeElement("D", "prop", XMLWriter.CLOSING);
    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();
}
Also used : InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) UserSession(org.olat.core.util.UserSession) Vector(java.util.Vector) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) LockInfo(org.olat.core.util.vfs.lock.LockInfo) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 57 with UserSession

use of org.olat.core.util.UserSession in project openolat by klemens.

the class WebdavStatus method deleteResource.

/**
 * Delete a resource.
 *
 * @param path Path of the resource which is to be deleted
 * @param req Servlet request
 * @param resp Servlet response
 * @param setStatus Should the response status be set on successful
 *                  completion
 */
private boolean deleteResource(final String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws IOException {
    String ifHeader = req.getHeader("If");
    if (ifHeader == null)
        ifHeader = "";
    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null)
        lockTokenHeader = "";
    final WebResourceRoot resources = getResources(req);
    final WebResource resource = resources.getResource(path);
    UserSession usess = webDAVManager.getUserSession(req);
    if (lockManager.isLocked(resource, ifHeader + lockTokenHeader, usess.getIdentity())) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return false;
    }
    if (!resource.exists()) {
        resp.sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }
    if (!resource.isDirectory()) {
        if (!resources.delete(resource)) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {
        Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
        deleteCollection(req, path, errorList);
        if (!resources.delete(resource)) {
            errorList.put(path, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        }
        if (!errorList.isEmpty()) {
            sendReport(req, resp, errorList);
            return false;
        }
    }
    if (setStatus) {
        resp.setStatus(WebdavStatus.SC_NO_CONTENT);
    }
    return true;
}
Also used : Hashtable(java.util.Hashtable) UserSession(org.olat.core.util.UserSession)

Example 58 with UserSession

use of org.olat.core.util.UserSession in project openolat by klemens.

the class BulkAssessmentTask method run.

/**
 * Used by to task executor, without any GUI
 */
@Override
public void run() {
    final List<BulkAssessmentFeedback> feedbacks = new ArrayList<>();
    try {
        log.audit("Start process bulk assessment");
        LoggingResourceable[] infos = new LoggingResourceable[2];
        if (task != null && task.getCreator() != null) {
            UserSession session = new UserSession();
            session.setIdentity(task.getCreator());
            session.setSessionInfo(new SessionInfo(task.getCreator().getKey(), task.getCreator().getName()));
            ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(session);
            infos[0] = LoggingResourceable.wrap(courseRes, OlatResourceableType.course);
            ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[0]);
            infos[1] = LoggingResourceable.wrap(getCourseNode());
            ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[1]);
        }
        doProcess(feedbacks);
        log.audit("End process bulk assessment");
        cleanup();
        ThreadLocalUserActivityLogger.log(AssessmentLoggingAction.ASSESSMENT_BULK, getClass(), infos);
    } catch (Exception e) {
        log.error("", e);
        feedbacks.add(new BulkAssessmentFeedback("", "bulk.assessment.error"));
        throw e;
    } finally {
        cleanupUnzip();
        sendFeedback(feedbacks);
    }
}
Also used : BulkAssessmentFeedback(org.olat.course.assessment.model.BulkAssessmentFeedback) UserSession(org.olat.core.util.UserSession) ArrayList(java.util.ArrayList) SessionInfo(org.olat.core.util.SessionInfo) LoggingResourceable(org.olat.util.logging.activity.LoggingResourceable) FileNotFoundException(java.io.FileNotFoundException)

Example 59 with UserSession

use of org.olat.core.util.UserSession in project openolat by klemens.

the class AuthenticatedDispatcher method execute.

/**
 * Main method called by OpenOLATServlet. This processess all requests for
 * authenticated users.
 *
 * @param request
 * @param response
 * @param uriPrefix
 */
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
    String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
    UserSession usess = CoreSpringFactory.getImpl(UserSessionManager.class).getUserSession(request);
    UserRequest ureq = null;
    try {
        // upon creation URL is checked for
        ureq = new UserRequestImpl(uriPrefix, request, response);
    } catch (NumberFormatException nfe) {
        // a 404 message must be shown -> e.g. robots correct their links.
        if (log.isDebug()) {
            log.debug("Bad Request " + request.getPathInfo());
        }
    }
    boolean auth = usess.isAuthenticated();
    if (!auth) {
        String guestAccess = ureq.getParameter(GUEST);
        if (guestAccess == null || !CoreSpringFactory.getImpl(LoginModule.class).isGuestLoginEnabled()) {
            String businessPath = extractBusinessPath(ureq, request, uriPrefix);
            if (businessPath != null) {
                usess.putEntryInNonClearedStore(AUTHDISPATCHER_BUSINESSPATH, businessPath);
            }
            redirectToDefaultDispatcher(request, response);
            return;
        } else if (guestAccess.equals(TRUE)) {
            // try to log in as anonymous
            // use the language from the lang parameter if available, otherwise use the system default locale
            String guestLang = ureq.getParameter("language");
            if (guestLang == null) {
                // support for legacy lang parameter
                guestLang = ureq.getParameter("lang");
            }
            Locale guestLoc;
            if (guestLang == null) {
                guestLoc = I18nModule.getDefaultLocale();
            } else {
                guestLoc = I18nManager.getInstance().getLocaleOrDefault(guestLang);
            }
            int loginStatus = AuthHelper.doAnonymousLogin(ureq, guestLoc);
            if (loginStatus != AuthHelper.LOGIN_OK) {
                if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
                    DispatcherModule.redirectToServiceNotAvailable(response);
                }
                // error, redirect to login screen
                redirectToDefaultDispatcher(request, response);
                return;
            }
        // else now logged in as anonymous user, continue
        }
    }
    // authenticated!
    try {
        // kill session if not secured via SSL
        if (forceSecureAccessOnly && !request.isSecure()) {
            SessionInfo sessionInfo = usess.getSessionInfo();
            if (sessionInfo != null) {
                HttpSession session = sessionInfo.getSession();
                if (session != null) {
                    try {
                        session.invalidate();
                    } catch (IllegalStateException ise) {
                    // thrown when session already invalidated. fine. ignore.
                    }
                }
            }
            redirectToDefaultDispatcher(request, response);
            return;
        }
        SessionInfo sessionInfo = usess.getSessionInfo();
        if (sessionInfo == null) {
            redirectToDefaultDispatcher(request, response);
            return;
        }
        if (userBasedLogLevelManager != null) {
            userBasedLogLevelManager.activateUsernameBasedLogLevel(sessionInfo.getLogin());
        }
        sessionInfo.setLastClickTime();
        String businessPath = (String) usess.removeEntryFromNonClearedStore(AUTHDISPATCHER_BUSINESSPATH);
        if (businessPath != null) {
            processBusinessPath(businessPath, ureq, usess);
        } else if (ureq.isValidDispatchURI()) {
            // valid uri for dispatching (has timestamp, componentid and windowid)
            processValidDispatchURI(ureq, usess, request, response);
        } else {
            businessPath = extractBusinessPath(ureq, request, uriPrefix);
            if (businessPath == null) {
                processBusinessPath("", ureq, usess);
            } else {
                processBusinessPath(businessPath, ureq, usess);
            }
        }
    } catch (InvalidRequestParameterException e) {
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            log.error("An exception occured while handling the invalid request parameter exception...", e1);
        }
    } catch (Throwable th) {
        // Do not log as Warn or Error here, log as ERROR in MsgFactory => ExceptionWindowController throws an OLATRuntimeException
        log.debug("handleError in AuthenticatedDispatcher throwable=" + th);
        DispatcherModule.handleError();
        ChiefController msgcc = MsgFactory.createMessageChiefController(ureq, th);
        // the controller's window must be failsafe also
        msgcc.getWindow().dispatchRequest(ureq, true);
    // do not dispatch (render only), since this is a new Window created as
    // a result of another window's click.
    } finally {
        if (userBasedLogLevelManager != null) {
            userBasedLogLevelManager.deactivateUsernameBasedLogLevel();
        }
    }
}
Also used : Locale(java.util.Locale) HttpSession(javax.servlet.http.HttpSession) SessionInfo(org.olat.core.util.SessionInfo) LoginModule(org.olat.login.LoginModule) IOException(java.io.IOException) ChiefController(org.olat.core.gui.control.ChiefController) UserSessionManager(org.olat.core.util.session.UserSessionManager) InvalidRequestParameterException(org.olat.core.gui.components.form.flexible.impl.InvalidRequestParameterException) UserSession(org.olat.core.util.UserSession) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 60 with UserSession

use of org.olat.core.util.UserSession in project openolat by klemens.

the class DMZDispatcher method execute.

/**
 * Main method called by OpenOLATServlet. This processess all requests for
 * users who are not authenticated.
 *
 * @param request
 * @param response
 * @param uriPrefix
 */
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
    if (rejectRequest(request, response)) {
        return;
    }
    UserRequest ureq = null;
    String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
    try {
        // upon creation URL is checked for
        ureq = new UserRequestImpl(uriPrefix, request, response);
    } catch (NumberFormatException nfe) {
        // a 404 message must be shown -> e.g. robots correct their links.
        if (log.isDebug()) {
            log.debug("Bad Request " + request.getPathInfo());
        }
        DispatcherModule.sendBadRequest(request.getPathInfo(), response);
        return;
    }
    try {
        // find out about which subdispatcher is meant
        // e.g. got here because of /dmz/...
        // maybe something like /dmz/registration/
        // 
        // add the context path to align with uriPrefix e.g. /olat/dmz/
        String pathInfo = request.getContextPath() + request.getPathInfo();
        ChiefControllerCreator subPathccc = null;
        // if /olat/dmz/
        boolean dmzOnly = pathInfo.equals(uriPrefix);
        if (!dmzOnly) {
            int sl = pathInfo.indexOf('/', uriPrefix.length());
            String sub;
            if (sl > 1) {
                // e.g. something like /registration/ or /pwchange/
                sub = pathInfo.substring(uriPrefix.length() - 1, sl + 1);
            } else {
                // e.g. something like /info.html from (/dmz/info.html)
                sub = pathInfo;
            }
            // chief controller creator for sub path, e.g.
            subPathccc = dmzServicesByPath.get(sub);
            if (subPathccc != null) {
                UserSession usess = ureq.getUserSession();
                Windows ws = Windows.getWindows(usess);
                synchronized (ws) {
                    // o_clusterOK by:fj per user session
                    ChiefController occ = subPathccc.createChiefController(ureq);
                    Window window = occ.getWindow();
                    window.setUriPrefix(uriPrefix);
                    ws.registerWindow(window);
                    window.dispatchRequest(ureq, true);
                    return;
                }
            }
        }
        // else a /olat/dmz/ request
        UserSession usess = ureq.getUserSession();
        Windows ws = Windows.getWindows(usess);
        // and make it useless under heavily load or 2 concurrent requests
        synchronized (usess) {
            // o_clusterOK by:fj per user session
            Window window;
            boolean windowHere = ws.isExisting(uriPrefix, ureq.getWindowID());
            boolean validDispatchUri = ureq.isValidDispatchURI();
            if (validDispatchUri && !windowHere) {
                // probably valid framework link from previous user && new Session(no window):
                // when a previous user logged off, and 30min later (when the httpsession is invalidated), the next user clicks e.g. on
                // the log-in link in the -same- browser window ->
                // -> there is no window -> create a new one
                window = null;
                CoreSpringFactory.getImpl(UserSessionManager.class).signOffAndClear(usess);
                usess.setLocale(LocaleNegotiator.getPreferedLocale(ureq));
                // update locale infos
                I18nManager.updateLocaleInfoToThread(usess);
                // request new windows since it is a new usersession, the old one was purged
                ws = Windows.getWindows(usess);
            } else if (validDispatchUri) {
                window = ws.getWindow(ureq);
            } else if (dmzOnly) {
                // e.g. /dmz/ -> start screen, clear previous session data
                window = null;
                CoreSpringFactory.getImpl(UserSessionManager.class).signOffAndClear(usess);
                usess.setLocale(LocaleNegotiator.getPreferedLocale(ureq));
                // update locale infos
                I18nManager.updateLocaleInfoToThread(usess);
                OAuthLoginModule oauthModule = CoreSpringFactory.getImpl(OAuthLoginModule.class);
                if (canRedirectConfigurableOAuth(request, response, oauthModule)) {
                    return;
                } else if (canRedirectOAuth(request, oauthModule)) {
                    OAuthSPI oauthSpi = oauthModule.getRootProvider();
                    HttpSession session = request.getSession();
                    OAuthResource.redirect(oauthSpi, response, session);
                    return;
                }
                // request new windows since it is a new usersession, the old one was purged
                ws = Windows.getWindows(usess);
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (window == null) {
                // no window found, -> start a new WorkFlow/Controller and obtain the window
                // main controller which also implements the windowcontroller for pagestatus and modal dialogs
                Object wSettings = usess.getEntry(WINDOW_SETTINGS);
                ChiefController occ = chiefControllerCreator.createChiefController(ureq);
                window = occ.getWindow();
                window.setUriPrefix(uriPrefix);
                ws.registerWindow(window);
                String businessPath = (String) usess.removeEntryFromNonClearedStore(DMZDISPATCHER_BUSINESSPATH);
                if (businessPath != null) {
                    List<ContextEntry> ces = BusinessControlFactory.getInstance().createCEListFromString(businessPath);
                    window.getDTabs().activate(ureq, null, ces);
                }
                // apply the settings forward
                usess.putEntryInNonClearedStore(WINDOW_SETTINGS, wSettings);
            }
            window.dispatchRequest(ureq);
        }
    } catch (InvalidRequestParameterException e) {
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            log.error("An exception occured while handling the invalid request parameter exception...", e1);
        }
    } catch (Throwable th) {
        try {
            ChiefController msgcc = MsgFactory.createMessageChiefController(ureq, th);
            // the controller's window must be failsafe also
            msgcc.getWindow().dispatchRequest(ureq, true);
        // do not dispatch (render only), since this is a new Window created as
        // a result of another window's click.
        } catch (Throwable t) {
            log.error("An exception occured while handling the exception...", t);
        }
    }
}
Also used : Window(org.olat.core.gui.components.Window) OAuthLoginModule(org.olat.login.oauth.OAuthLoginModule) HttpSession(javax.servlet.http.HttpSession) Windows(org.olat.core.gui.Windows) ChiefController(org.olat.core.gui.control.ChiefController) IOException(java.io.IOException) ContextEntry(org.olat.core.id.context.ContextEntry) UserSessionManager(org.olat.core.util.session.UserSessionManager) InvalidRequestParameterException(org.olat.core.gui.components.form.flexible.impl.InvalidRequestParameterException) ChiefControllerCreator(org.olat.core.gui.control.ChiefControllerCreator) UserSession(org.olat.core.util.UserSession) OAuthSPI(org.olat.login.oauth.OAuthSPI) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Aggregations

UserSession (org.olat.core.util.UserSession)146 UserSessionManager (org.olat.core.util.session.UserSessionManager)26 Identity (org.olat.core.id.Identity)22 Roles (org.olat.core.id.Roles)20 SessionInfo (org.olat.core.util.SessionInfo)20 HttpSession (javax.servlet.http.HttpSession)18 UserRequest (org.olat.core.gui.UserRequest)18 Test (org.junit.Test)16 MapperKey (org.olat.core.dispatcher.mapper.manager.MapperKey)16 UserRequestImpl (org.olat.core.gui.UserRequestImpl)16 ContextEntry (org.olat.core.id.context.ContextEntry)14 IOException (java.io.IOException)12 AssertException (org.olat.core.logging.AssertException)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 Window (org.olat.core.gui.components.Window)10 UnknownHostException (java.net.UnknownHostException)8 ArrayList (java.util.ArrayList)8 ChiefController (org.olat.core.gui.control.ChiefController)8 Preferences (org.olat.core.util.prefs.Preferences)8 InetAddress (java.net.InetAddress)6