Search in sources :

Example 91 with UserSession

use of org.olat.core.util.UserSession in project OpenOLAT by OpenOLAT.

the class WebDAVManagerImpl method getWebDAVRoot.

@Override
public WebResourceRoot getWebDAVRoot(HttpServletRequest req) {
    UserSession usess = getUserSession(req);
    if (usess == null || usess.getIdentity() == null) {
        return createEmptyRoot(usess);
    }
    usess.getSessionInfo().setLastClickTime();
    VFSResourceRoot fdc = (VFSResourceRoot) usess.getEntry("_DIRCTX");
    if (fdc != null) {
        return fdc;
    }
    IdentityEnvironment identityEnv = usess.getIdentityEnvironment();
    VFSContainer webdavContainer = getMountableRoot(identityEnv);
    // create the / folder
    VirtualContainer rootContainer = new VirtualContainer("");
    rootContainer.addItem(webdavContainer);
    rootContainer.setLocalSecurityCallback(new ReadOnlyCallback());
    fdc = new VFSResourceRoot(identityEnv.getIdentity(), rootContainer);
    usess.putEntry("_DIRCTX", fdc);
    return fdc;
}
Also used : ReadOnlyCallback(org.olat.core.util.vfs.callbacks.ReadOnlyCallback) UserSession(org.olat.core.util.UserSession) VFSContainer(org.olat.core.util.vfs.VFSContainer) IdentityEnvironment(org.olat.core.id.IdentityEnvironment) VirtualContainer(org.olat.core.util.vfs.VirtualContainer)

Example 92 with UserSession

use of org.olat.core.util.UserSession in project OpenOLAT by OpenOLAT.

the class WebDAVManagerImpl method afterAuthorization.

private UserSession afterAuthorization(Identity identity, HttpServletRequest request) {
    UserSession usess = sessionManager.getUserSession(request);
    synchronized (usess) {
        // double check to prevent severals concurrent login
        if (usess.isAuthenticated()) {
            return usess;
        }
        sessionManager.signOffAndClear(usess);
        usess.setIdentity(identity);
        UserDeletionManager.getInstance().setIdentityAsActiv(identity);
        // set the roles (admin, author, guest)
        Roles roles = BaseSecurityManager.getInstance().getRoles(identity);
        usess.setRoles(roles);
        // set session info
        SessionInfo sinfo = new SessionInfo(identity.getKey(), identity.getName(), request.getSession());
        User usr = identity.getUser();
        sinfo.setFirstname(usr.getProperty(UserConstants.FIRSTNAME, null));
        sinfo.setLastname(usr.getProperty(UserConstants.LASTNAME, null));
        String remoteAddr = request.getRemoteAddr();
        sinfo.setFromIP(remoteAddr);
        sinfo.setFromFQN(remoteAddr);
        try {
            InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr());
            if (iaddr.length > 0)
                sinfo.setFromFQN(iaddr[0].getHostName());
        } catch (UnknownHostException e) {
        // ok, already set IP as FQDN
        }
        sinfo.setAuthProvider(BaseSecurityModule.getDefaultAuthProviderIdentifier());
        sinfo.setUserAgent(request.getHeader("User-Agent"));
        sinfo.setSecure(request.isSecure());
        sinfo.setWebDAV(true);
        sinfo.setWebModeFromUreq(null);
        // set session info for this session
        usess.setSessionInfo(sinfo);
        // 
        sessionManager.signOn(usess);
        return usess;
    }
}
Also used : User(org.olat.core.id.User) UnknownHostException(java.net.UnknownHostException) UserSession(org.olat.core.util.UserSession) SessionInfo(org.olat.core.util.SessionInfo) Roles(org.olat.core.id.Roles) InetAddress(java.net.InetAddress)

Example 93 with UserSession

use of org.olat.core.util.UserSession in project OpenOLAT by OpenOLAT.

the class WebDAVManagerImpl method handleAuthentication.

/**
 * @see org.olat.core.commons.services.webdav.WebDAVManager#handleAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public boolean handleAuthentication(HttpServletRequest req, HttpServletResponse resp) {
    // manger not started
    if (timedSessionCache == null) {
        return false;
    }
    UserSession usess = sessionManager.getUserSession(req);
    if (usess != null && usess.isAuthenticated()) {
        req.setAttribute(REQUEST_USERSESSION_KEY, usess);
        return true;
    }
    usess = doAuthentication(req, resp);
    if (usess == null) {
        return false;
    }
    // register usersession in REQUEST, not session !!
    // see SecureWebDAVServlet.setAuthor() and checkQuota()
    req.setAttribute(REQUEST_USERSESSION_KEY, usess);
    return true;
}
Also used : UserSession(org.olat.core.util.UserSession)

Example 94 with UserSession

use of org.olat.core.util.UserSession in project OpenOLAT by OpenOLAT.

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 95 with UserSession

use of org.olat.core.util.UserSession in project OpenOLAT by OpenOLAT.

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)

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