package server; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import models.Configuration; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.thrift.TException; import server.generated.Image; import server.generated.Lecture; import server.generated.Person; import server.generated.Server; import server.generated.User; import org.openslx.imagemaster.thrift.iface.ImageServer.Client; import org.openslx.imagemaster.thrift.iface.InvalidTokenException; import org.openslx.imagemaster.thrift.iface.UserInfo; import thrift.MasterThriftConnection; //import thrift.SessionData; import sql.SQL; //import util.XMLCreator; public class ServerHandler implements Server.Iface { private static Logger log = Logger.getLogger(ServerHandler.class); static SQL sql = new SQL(); private Map tokenManager = new HashMap<>(); //saves the current tokens and the mapped userdata, returning from the server public boolean authenticated(String token) throws TException { if(tokenManager.get(token) != null) { //user found in tokenManager, session was set to valid once before (cached session, no further action needed) return true; } else { MasterThriftConnection thrift = new MasterThriftConnection(); Client client = thrift.getMasterThriftConnection(); //user not in tokenManager, check authentication, then add user to tokenManager log.info("token is: "+token); UserInfo ui = null; if( (ui = client.getUserFromToken(token)) != null) //user authenticated by masterserver { //user was authenticated by the masterserver, cache the data tokenManager.put(token, ui); return true; } } return false; } private UserInfo getUserFromToken(String token) //local function, which gets userdata from the tokenmanager, not the masterserver { //implemented, as there is no need for userdata in each function, so return type of authenticated should stay boolean UserInfo ui = tokenManager.get(token); return ui; } public boolean setSessionInvalid(String token) { log.info("token disabling.. round one"); log.info(tokenManager.get(token)); tokenManager.remove(token); log.info("token disabling.. round two"); log.info(tokenManager.get(token)); if(tokenManager.get(token) == null) //check if deletion worked and token isn't stored anymore { return true; } return false; } @Override public User getFtpUser(String token) throws TException { if(authenticated(token)) { log.info("returning FTPUser..."); User user = new User(); user.setUserName(UUID.randomUUID().toString().substring(0, 8)); user.setPassword(getEncodedSha1Sum(UUID.randomUUID().toString() .substring(0, 8))); if (Configuration.config.getAbsolute_path().endsWith("/")) { user.setPath(Configuration.config.getAbsolute_path()); } else { user.setPath(Configuration.config.getAbsolute_path() + "/"); } // check if folder temp and folder prod exist if (folderTempExists() == true && folderProdExists() == true) { sql.writeFTPUser(user.getUserName(), user.getPassword()); return user; } else { log.info("Error: returning null user"); return null; } } return null; } public boolean folderTempExists() { // check if folder temp exists, otherwise create it Path path = null; if (Configuration.config.getAbsolute_path().endsWith("/")) { path = Paths.get(Configuration.config.getAbsolute_path() + "temp"); } else { path = Paths.get(Configuration.config.getAbsolute_path() + "/temp"); } if (Files.exists(path) == true) { log.info("folder '" + path + "' exists, no further action"); return true; } else { // create directory and set permissions boolean success = (new File(path + "")).mkdirs(); if (!success) { log.info("failed to create folder '" + path + "'"); return false; } else { // set permissions try { Runtime.getRuntime().exec("chmod 777 " + path); } catch (IOException e) { e.printStackTrace(); } log.info("folder '" + path + "' successfully created"); return true; } } }// end folderTempExists() public boolean folderProdExists() { // check if folder temp exists, otherwise create it Path path = null; if (Configuration.config.getAbsolute_path().endsWith("/")) { path = Paths.get(Configuration.config.getAbsolute_path() + "prod"); } else { path = Paths.get(Configuration.config.getAbsolute_path() + "/prod"); } if (Files.exists(path) == true) { log.info("folder '" + path + "' exists, no further action"); return true; } else { // create directory and set permissions boolean success = (new File(path + "")).mkdirs(); if (!success) { log.info("failed to create folder '" + path + "'"); return false; } else { // set permissions try { Runtime.getRuntime().exec("chmod 777 " + path); } catch (IOException e) { e.printStackTrace(); } log.info("folder '" + path + "' successfully created"); return true; } } }// end folderProdExists() public String getEncodedSha1Sum(String key) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(key.getBytes()); log.info("successfully returned EncodedSha1Sum"); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { // handle error case to taste } return null; } @Override public long DeleteFtpUser(String user, String token) throws TException { if(authenticated(token)) { return sql.DeleteUser(user); } return -1; } @Override public String getPathOfImage(String image_id, String version, String token) throws TException { if(authenticated(token)) { log.info("successfully returned PathOfImage: " + sql.getPathOfImage(image_id, version)); return sql.getPathOfImage(image_id, version); } return null; } @Override public String setInstitution(String university, String token) throws TException { if(authenticated(token)) { return sql.setInstitution(university); } return null; } @Override public boolean writeVLdata(String imagename, String desc, String Tel, String Fak, boolean license, boolean internet, long ram, long cpu, String imagePath, boolean isTemplate, long filesize, long shareMode, String os, String uid, String token, String userID) throws TException { if(authenticated(token)) { String mode = null; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } // String pk_institution = sql.setInstitution(university); // String pk_person = sql.setPerson(login, lastname, firstname, Mail, // new Date(), pk_institution); // OS impl Select and write // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden: 'Windows 7 // 32 bit" String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os .substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")) .replace(" ", "")); // sql.setImageData(pk_person, license, internet, cpu, ram, // imagename,desc, imagePath, filesize,mode,pk_os); sql.setImageData(userID, license, internet, cpu, ram, imagename, desc, imagePath, filesize, mode, pk_os, uid); log.info("userID in serverhandler was: "+userID); log.info("written VLdata"); return true; } return false; } @Override public List getImageListPermissionWrite(String userID, String token) throws TException { if(authenticated(token)) { return sql.getImageListPermissionWrite(userID); } return null; } @Override public List getImageListPermissionRead(String userID, String token) throws TException { if(authenticated(token)) { return sql.getImageListPermissionRead(userID); } return null; } @Override public List getImageListPermissionLink(String userID, String token) throws TException { if(authenticated(token)) { return sql.getImageListPermissionLink(userID); } return null; } @Override public List getImageListPermissionAdmin(String userID, String token) throws TException { if(authenticated(token)) { return sql.getImageListPermissionAdmin(userID); } return null; } @Override public List getImageListAllTemplates(String token) throws TException { if(authenticated(token)) { return sql.getImageListAllTemplates(); } return null; } @Override public List getAllOS(String token) throws TException { if(authenticated(token)) { return sql.getAllOS(); } return null; } //UserInfo does not return the institution, so in this case, the local method is prepared, but not yet executed, as the institution has to be added to UserInfo (or selected by institutionID) @Override public Map getPersonData(String Vorname, String Nachname, String token) throws TException { /* if(authenticated(token)) { return sql.getPersonData(Vorname, Nachname); } return null; */ Map map = new HashMap<>(); UserInfo ui = getUserFromToken(token); map.put("mail", ui.getEMail()); map.put("Nachname", ui.getLastName()); map.put("Vorname", ui.getFirstName()); //map.put("Hochschule", sql.getInstitutionByID(ui.getOrganizationId())); //does not deliver the correct id Map tempMap = new HashMap<>(); tempMap = sql.getPersonData(Vorname, Nachname); map.put("Hochschule", tempMap.get("Hochschule")); return map; } public void setPerson(String userID, String token, String institution) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); //String institution = sql.getInstitutionByID(ui.getOrganizationId()); sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), institution); } } @Override public boolean writeLecturedata(String name, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageID, String token, String Tel, String Fak, String lectureID, String university) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); //String pk_image = imageID; Map map = new HashMap(); int imageversion = 0; //String university = sql.getInstitutionByID(ui.getOrganizationId()); String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); map = sql.getImageIDandVersion(imageID); //pk_image = map.get("GUID"); imageversion = Integer.parseInt(map.get("version")); sql.setLectureData(pk_person, imageID, imageversion, name, desc, shortdesc, startDate, endDate, isActive, lectureID); } return false; } @Override public boolean startFileCopy(String filename, String token) throws TException { if(authenticated(token)) { // copy file from folder temp to folder prod String file = Configuration.config.getAbsolute_path() + "temp/" + filename; File tmpFile = new File(file); log.info("Trying to move file to '/srv/openslx/nfs/prod/" + tmpFile.getName() + "'"); try { FileUtils.moveFile(tmpFile, new File(Configuration.config.getAbsolute_path() + "prod/" + filename)); // int ret = sql.UpdateImagePath(filename); if (sql.UpdateImagePath(filename) == 0) { log.info("file moved and database updated."); } } catch (IOException e) { log.info("Failed to move file."); e.printStackTrace(); } } return true; } @Override public Map getImageData(String imageid, String imageversion, String token) throws TException { if(authenticated(token)) { //log.info("returning ImageData: "+ sql.getImageData(imageid, imageversion).size() + "items."); return sql.getImageData(imageid, imageversion); } return null; } @Override public boolean updateImageData(String name, String newName, String desc, String image_path, boolean license, boolean internet, long ram, long cpu, String id, String version, boolean isTemplate, long filesize, long shareMode, String os, String token) throws TException { if(authenticated(token)) { String mode = null; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os .substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")) .replace(" ", "")); sql.UpdateImageData(name, newName, desc, image_path, license, internet, cpu, ram, id, version, isTemplate, filesize, mode, pk_os); } return false; } @Override public List getLectureList(String token) throws TException { if(authenticated(token)) { //log.info("returning LectureList"); return sql.getLectureList(); } return null; } @Override public List getLectureListPermissionRead(String token) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); //log.info("returning LectureListRead"); return sql.getLectureListPermissionRead(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public List getLectureListPermissionWrite(String token) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); //log.info("returning LectureListWrite"); return sql.getLectureListPermissionWrite(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public List getLectureListPermissionAdmin(String token) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); //log.info("returning LectureListAdmin"); return sql.getLectureListPermissionAdmin(ui.getUserId()); } return null; }// end getLectureListPermissionRead @Override public boolean updateLecturedata(String name, String newName, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageid, String imageversion, String token, String Tel, String Fak, String id, String university) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); Map map = new HashMap(); map = sql.getDeleteXMLData(id); sql.updateLectureData(imageid, imageversion, ui.getLastName(), newName, desc, shortdesc, startDate, endDate, isActive, id); String path = Configuration.config.getAbsolute_path() + "prod/" + map.get("date").substring(0, map.get("date").length() - 2) + "_" + university + "_" + ui.getEMail() + "_" + map.get("name") + ".xml"; File tmpFile = new File(path); try { FileUtils.forceDelete(tmpFile); } catch (IOException e1) { e1.printStackTrace(); } } return false; } @Override public boolean deleteImageServer(String imageid, String imageversion, String token) throws TException { if(authenticated(token)) { String stringFile = sql.getFile(imageid, imageversion); log.info("File to Delete: " + stringFile); File tmpFile = new File(Configuration.config.getAbsolute_path() + stringFile); try { // File wird von Server gelöscht FileUtils.forceDelete(tmpFile); return true; } catch (IOException e) { log.info("Failed to execute deleteImageServer."); e.printStackTrace(); } } return false; } @Override public boolean deleteImageData(String id, String version, String token) throws TException { boolean success=false; if(authenticated(token)) { if(sql.deleteImage(id, version)==true) { success=true; log.info("Image '"+id+"' and permissions successfully deleted."); } } return success; } @Override public boolean connectedToLecture(String id, String version, String token) throws TException { if(authenticated(token)) { return sql.connectedToLecture(id, version); } return true; } public boolean deleteLecture(String id, String token, String university) throws TException { boolean success = false; UserInfo ui = getUserFromToken(token); String user = ui.getEMail(); if(authenticated(token)) { Map map = new HashMap(); map = sql.getDeleteXMLData(id); try { String path = Configuration.config.getAbsolute_path() + "prod/" + map.get("date") .substring(0, map.get("date").length() - 2) + "_" + university + "_" + user + "_" + map.get("name") + ".xml"; File xmlFile = new File(path); FileUtils.forceDelete(xmlFile); } catch (IOException e) { log.info("Failed to execute deleteLecture."); e.printStackTrace(); } if(sql.deleteLecture(id) == true){ success = true; log.info("Lecture '"+id+"' and permissions successfully deleted."); } } return success; } @Override public List getAllUniversities(String token) throws TException { if(authenticated(token)) { return sql.getAllUniversities(); } return null; } @Override public Map getLectureData(String lectureid, String token) throws TException { if(authenticated(token)) { //log.info("returning LectureData"); return sql.getLectureData(lectureid); } return null; } public static int nthIndexOf(final String string, final String searchToken,final int index) { int j = 0; for (int i = 0; i < index; i++) { j = string.indexOf(searchToken, j + 1); if (j == -1) break; } return j; } @Override public boolean checkUser(String username, String token) throws TException { if(authenticated(token)) { return sql.checkUser(username); } return false; } @Override public boolean createUser(String token, String university) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); return true; } return false; } @Override public boolean writeImageRights(String imageID, String token, String role, String university, String userID) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); String pk_image = null; Map map = new HashMap(); String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); map = sql.getImageIDandVersion(imageID); pk_image = map.get("GUID"); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int linkallowed = 1; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } else { int read = 1; int write = 0; // int changePermission=0; int admin = 0; int linkallowed = 0; int roleID = sql.getRoleID(role); sql.setImageRights(pk_person, pk_image, roleID, read, write, admin, linkallowed); } log.info("Written image rights"); return true; } return false; } @Override public boolean writeLectureRights(String lectureID, String role, String token, String university, String userID) throws TException { if(authenticated(token)) { //String pk_lecture = null; UserInfo ui = getUserFromToken(token); String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); //pk_lecture = sql.getLectureID(lectureID); if (role.equals("Dozent")) { int read = 1; int write = 1; // int changePermission=0; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } else if (role.equals("Admin")) { int read = 1; int write = 1; // int changePermission=1; int admin = 1; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } else { int read = 0; int write = 0; // int changePermission=0; int admin = 0; int roleID = sql.getRoleID(role); sql.setLectureRights(pk_person, lectureID, roleID, read, write, admin); } return true; } return false; } @Override public List getAllOtherSatelliteUsers(List userID, String token) throws TException { if(authenticated(token)) { return sql.getAllOtherSatelliteUsers(userID); // return null; } return null; } //set permissions for users which are !=userID public boolean writeAdditionalImageRights(String imageID, String userID, boolean isRead, boolean isWrite, boolean isLinkAllowed, boolean isAdmin, String token) throws TException { boolean success = false; if(authenticated(token)) { Map map = new HashMap(); map = sql.getImageIDandVersion(imageID); //String imageID = map.get("GUID"); sql.writeAdditionalImageRights(imageID, userID, isRead, isWrite, isLinkAllowed, isAdmin); log.info("Written additional image rights for " + userID); } return success; } public boolean writeAdditionalLectureRights(String lectureID, String userID, boolean isRead, boolean isWrite, boolean isAdmin, String token) throws TException { if(authenticated(token)) { Map map = new HashMap(); //String lectureID = sql.getLectureID(lectureID); sql.writeAdditionalLectureRights(lectureID, userID, isRead, isWrite, isAdmin); log.info("Written additional lecture rights for "+ userID); return true; } return false; } @Override public List getPermissionForUserAndImage(String token, String imageID, String userID) throws TException { if(authenticated(token)) { return sql.getPermissionForUserAndImage(userID, imageID); } return null; } public List getPermissionForUserAndLecture(String token,String lectureID, String userID) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); return sql.getPermissionForUserAndLecture(userID, lectureID); } return null; } @Override public void deleteAllAdditionalImagePermissions(String imageID, String token, String userID) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); sql.deleteAllAdditionalImagePermissions(imageID, userID); } return; } @Override public void deleteAllAdditionalLecturePermissions(String lectureID,String token, String userID) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); sql.deleteAllAdditionalLecturePermissions(lectureID, userID); } return; } @Override public List getImageList(String token) throws TException { UserInfo ui = getUserFromToken(token); if(authenticated(token)) { return sql.getImageList(ui.getEMail()); } return null; } @Override public List getAdditionalImageContacts(String imageID, String token) throws TException { if(authenticated(token)) { return sql.getAdditionalImageContacts(imageID); } return null; } @Override public String getOsNameForGuestOs(String guestOS, String token) throws TException { if(authenticated(token)) { return sql.getOsNameForGuestOs(guestOS); } return null; } @Override public String createRandomUUID(String token) throws TException { if(authenticated(token)) { return sql.createRandomUUID(); } return null; } public Map getItemOwner(String itemID, String token) throws TException { if(authenticated(token)) { return sql.getItemOwner(itemID); } return null; } @Override public boolean userIsImageAdmin(String imageID, String token, String userID) throws TException { if(authenticated(token)) { UserInfo ui = getUserFromToken(token); return sql.userIsImageAdmin(userID,imageID); } return false; } @Override public boolean userIsLectureAdmin(String userID, String lectureID, String token) throws TException { if(authenticated(token)) { return sql.userIsLectureAdmin(userID,lectureID); } return false; } @Override public String getInstitutionByID(String institutionID) throws TException { // TODO Auto-generated method stub return null; } }// end class