Search in sources :

Example 6 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method deleteAllFiles.

/**
 * deletes all files inside a given derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param pathParamMcrObjID - the MyCoRe Object ID
 * @param pathParamMcrDerID - the MyCoRe Derivate ID
 * @return a Jersey Response Object
 * @throws MCRRestAPIException
 */
public static Response deleteAllFiles(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID) throws MCRRestAPIException {
    Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    SortedMap<String, String> parameter = new TreeMap<>();
    parameter.put("mcrObjectID", pathParamMcrObjID);
    parameter.put("mcrDerivateID", pathParamMcrDerID);
    String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
    if (base64Signature == null) {
    // ToDo error handling
    }
    if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
        try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
            // MCRSession session = MCRServlet.getSession(request);
            MCRSession session = MCRSessionMgr.getCurrentSession();
            MCRUserInformation currentUser = session.getUserInformation();
            MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
            session.setUserInformation(apiUser);
            MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
            MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
            // MCRAccessManager.checkPermission uses CACHE, which seems to be dirty from other calls
            MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
            if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
                MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
                final MCRPath rootPath = MCRPath.getPath(der.getId().toString(), "/");
                try {
                    Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
                    Files.createDirectory(rootPath);
                } catch (IOException e) {
                    LOGGER.error(e);
                }
            }
            session.setUserInformation(currentUser);
            response = Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
        }
    } else {
        throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "Delete failed.", "The submitted data could not be validated."));
    }
    return response;
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Response(javax.ws.rs.core.Response) MCRSession(org.mycore.common.MCRSession) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRUserInformation(org.mycore.common.MCRUserInformation)

Example 7 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRRestAPIUploadHelper method uploadFile.

/**
 * uploads a file into a given derivate
 * @param info - the Jersey UriInfo object
 * @param request - the HTTPServletRequest object
 * @param pathParamMcrObjID - a MyCoRe Object ID
 * @param pathParamMcrDerID - a MyCoRe Derivate ID
 * @param uploadedInputStream - the inputstream from HTTP Post request
 * @param fileDetails - the file information from HTTP Post request
 * @param formParamPath - the path of the file inside the derivate
 * @param formParamMaindoc - true, if this file should be marked as maindoc
 * @param formParamUnzip - true, if the upload is zip file that should be unzipped inside the derivate
 * @param formParamMD5 - the MD5 sum of the uploaded file
 * @param formParamSize - the size of the uploaded file
 * @return a Jersey Response object
 * @throws MCRRestAPIException
 */
public static Response uploadFile(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID, InputStream uploadedInputStream, FormDataContentDisposition fileDetails, String formParamPath, boolean formParamMaindoc, boolean formParamUnzip, String formParamMD5, Long formParamSize) throws MCRRestAPIException {
    SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
    SortedMap<String, String> parameter = new TreeMap<>();
    parameter.put("mcrObjectID", pathParamMcrObjID);
    parameter.put("mcrDerivateID", pathParamMcrDerID);
    parameter.put("path", formParamPath);
    parameter.put("maindoc", Boolean.toString(formParamMaindoc));
    parameter.put("unzip", Boolean.toString(formParamUnzip));
    parameter.put("md5", formParamMD5);
    parameter.put("size", Long.toString(formParamSize));
    String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
    if (base64Signature == null) {
        throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The submitted data could not be validated.", "Please provide a signature as HTTP header 'X-MyCoRe-RestAPI-Signature'."));
    }
    if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
        try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
            // MCRSession session = MCRServlet.getSession(request);
            MCRSession session = MCRSessionMgr.getCurrentSession();
            MCRUserInformation currentUser = session.getUserInformation();
            MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
            session.setUserInformation(apiUser);
            MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
            MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
            MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
            if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
                MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
                java.nio.file.Path derDir = null;
                String path = null;
                if (der.getOwnerID().equals(objID)) {
                    try {
                        derDir = UPLOAD_DIR.resolve(derID.toString());
                        if (Files.exists(derDir)) {
                            Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
                        }
                        path = formParamPath.replace("\\", "/").replace("../", "");
                        while (path.startsWith("/")) {
                            path = path.substring(1);
                        }
                        MCRDirectory difs = MCRDirectory.getRootDirectory(derID.toString());
                        if (difs == null) {
                            difs = new MCRDirectory(derID.toString());
                        }
                        der.getDerivate().getInternals().setIFSID(difs.getID());
                        der.getDerivate().getInternals().setSourcePath(derDir.toString());
                        if (formParamUnzip) {
                            String maindoc = null;
                            try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(uploadedInputStream))) {
                                ZipEntry entry;
                                while ((entry = zis.getNextEntry()) != null) {
                                    LOGGER.debug("Unzipping: {}", entry.getName());
                                    java.nio.file.Path target = derDir.resolve(entry.getName());
                                    Files.createDirectories(target.getParent());
                                    Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
                                    if (maindoc == null && !entry.isDirectory()) {
                                        maindoc = entry.getName();
                                    }
                                }
                            } catch (IOException e) {
                                LOGGER.error(e);
                            }
                            MCRFileImportExport.importFiles(derDir.toFile(), difs);
                            if (formParamMaindoc) {
                                der.getDerivate().getInternals().setMainDoc(maindoc);
                            }
                        } else {
                            java.nio.file.Path saveFile = derDir.resolve(path);
                            Files.createDirectories(saveFile.getParent());
                            Files.copy(uploadedInputStream, saveFile, StandardCopyOption.REPLACE_EXISTING);
                            // delete old file
                            MCRFileImportExport.importFiles(derDir.toFile(), difs);
                            if (formParamMaindoc) {
                                der.getDerivate().getInternals().setMainDoc(path);
                            }
                        }
                        MCRMetadataManager.update(der);
                        Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
                    } catch (IOException | MCRPersistenceException | MCRAccessException e) {
                        LOGGER.error(e);
                        throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal error", e.getMessage()));
                    }
                }
                session.setUserInformation(currentUser);
                return Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
            }
        }
    }
    throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "File upload failed.", "The submitted data could not be validated."));
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) ZipEntry(java.util.zip.ZipEntry) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) MCRAccessException(org.mycore.access.MCRAccessException) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ZipInputStream(java.util.zip.ZipInputStream) MCRSession(org.mycore.common.MCRSession) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) BufferedInputStream(java.io.BufferedInputStream) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRUserInformation(org.mycore.common.MCRUserInformation) MCRPersistenceException(org.mycore.common.MCRPersistenceException)

Example 8 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRAclEditorResource method transform.

protected InputStream transform(String xmlFile) throws Exception {
    InputStream guiXML = getClass().getResourceAsStream(xmlFile);
    if (guiXML == null) {
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build());
    }
    SAXBuilder saxBuilder = new SAXBuilder();
    Document webPage = saxBuilder.build(guiXML);
    XPathExpression<Object> xpath = XPathFactory.instance().compile("/MyCoReWebPage/section/div[@id='mycore-acl-editor2']");
    Object node = xpath.evaluateFirst(webPage);
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    String lang = mcrSession.getCurrentLanguage();
    if (node != null) {
        Element mainDiv = (Element) node;
        mainDiv.setAttribute("lang", lang);
        String bsPath = CONFIG.getString("MCR.bootstrap.path", "");
        if (!bsPath.equals("")) {
            bsPath = MCRFrontendUtil.getBaseURL() + bsPath;
            Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet").setAttribute("type", "text/css");
            mainDiv.addContent(0, item);
        }
    }
    MCRContent content = MCRJerseyUtil.transform(webPage, request);
    return content.getInputStream();
}
Also used : SAXBuilder(org.jdom2.input.SAXBuilder) MCRSession(org.mycore.common.MCRSession) WebApplicationException(javax.ws.rs.WebApplicationException) InputStream(java.io.InputStream) Element(org.jdom2.Element) JsonObject(com.google.gson.JsonObject) Document(org.jdom2.Document) MCRContent(org.mycore.common.content.MCRContent)

Example 9 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRAccessControlSystem method checkPermission.

@Override
public boolean checkPermission(Element rule) {
    MCRSession session = MCRSessionMgr.getCurrentSession();
    String ruleStr = getNormalizedRuleString(rule);
    MCRAccessRule accessRule = new MCRAccessRule(null, "System", new Date(), ruleStr, "");
    try {
        return accessRule.checkAccess(session.getUserInformation().getUserID(), new Date(), new MCRIPAddress(session.getCurrentIP()));
    } catch (MCRException | UnknownHostException e) {
        // only return true if access is allowed, we dont know this
        LOGGER.debug("Error while checking rule.", e);
        return false;
    }
}
Also used : MCRException(org.mycore.common.MCRException) MCRSession(org.mycore.common.MCRSession) UnknownHostException(java.net.UnknownHostException) Date(java.util.Date)

Example 10 with MCRSession

use of org.mycore.common.MCRSession in project mycore by MyCoRe-Org.

the class MCRAccessCacheManager method isPermitted.

public Boolean isPermitted(String id, String permission) {
    MCRPermissionHandle handle = new MCRPermissionHandle(id, permission);
    MCRCache<MCRPermissionHandle, Boolean> permissionCache = accessCache.get();
    MCRSession currentSession = MCRSessionMgr.getCurrentSession();
    return permissionCache.getIfUpToDate(handle, currentSession.getLoginTime());
}
Also used : MCRSession(org.mycore.common.MCRSession)

Aggregations

MCRSession (org.mycore.common.MCRSession)63 IOException (java.io.IOException)15 MCRUserInformation (org.mycore.common.MCRUserInformation)10 MCRObjectID (org.mycore.datamodel.metadata.MCRObjectID)10 MCRPath (org.mycore.datamodel.niofs.MCRPath)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 Date (java.util.Date)5 EntityManager (javax.persistence.EntityManager)5 Path (java.nio.file.Path)4 Response (javax.ws.rs.core.Response)4 Test (org.junit.Test)4 MCRRestAPIException (org.mycore.restapi.v1.errors.MCRRestAPIException)4 SAXException (org.xml.sax.SAXException)4 UnknownHostException (java.net.UnknownHostException)3 Document (org.jdom2.Document)3 MCRAccessException (org.mycore.access.MCRAccessException)3 MCRException (org.mycore.common.MCRException)3 MCRPersistenceException (org.mycore.common.MCRPersistenceException)3 MCRDerivate (org.mycore.datamodel.metadata.MCRDerivate)3 MCRRestAPIError (org.mycore.restapi.v1.errors.MCRRestAPIError)3