Skip to content

Commit

Permalink
Fixed code smells
Browse files Browse the repository at this point in the history
  • Loading branch information
car031 committed Oct 17, 2024
1 parent 07cef63 commit bfa670a
Show file tree
Hide file tree
Showing 26 changed files with 558 additions and 158 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ private void forbidRuntimeUsage(String expression) throws ForbiddenCodeException
} else {
Pattern runtimePattern = Pattern.compile("\\.\\s*(getRuntime|runtime)", Pattern.DOTALL);
Matcher m = runtimePattern.matcher(expression);
while (m.find()) {
if (m.find()) {
String snippet = expression.substring(Math.max(0, m.start() - 50),
Math.min(expression.length() - 1, m.end() + 50));
log.error("Detected possible suspicious access to java.lang.Runtime: {}", snippet);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,29 +333,47 @@ public void send(EMail email) throws MessagingException {
/*
* If we have to images, the parts must be 'related' otherwise 'mixed'
*/
Multipart mpMessage = new MimeMultipart(email.getImages().isEmpty() ? "mixed" : "related");
Multipart multipartMessage = new MimeMultipart(email.getImages().isEmpty() ? "mixed" : "related");

if (StringUtils.isNotEmpty(email.getMessageText())) {
MimeBodyPart body = buildBodyPart(email);
mpMessage.addBodyPart(body);
multipartMessage.addBodyPart(body);
}

int i = 1;
for (String image : email.getImages()) {
MimeBodyPart imageBodyPart = new MimeBodyPart();
includeImages(email, multipartMessage);

try {
DataSource ds = new URLDataSource(UrlUtil.toURL(image));
imageBodyPart.setDataHandler(new DataHandler(ds));
} catch (MalformedURLException | URISyntaxException e) {
includeAttachments(email, multipartMessage);

message.setContent(multipartMessage);

MailDateFormat formatter = new MailDateFormat();
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // always use UTC
// for outgoing mail
Date now = new Date();
message.setHeader("Date", formatter.format(now));

if (!Context.get().getProperties().getBoolean("smtp.nosend", false)) {
try (Transport transport = buildTransport(session);) {
transport.sendMessage(message, message.getAllRecipients());
} catch (IOException e) {
throw new MessagingException(e.getMessage(), e);
}

imageBodyPart.setHeader("Content-ID", "<image_" + (i++) + ">");
imageBodyPart.setDisposition("inline");
mpMessage.addBodyPart(imageBodyPart);
log.info("Sent email with subject '{}' to recipients {}", email.getSubject(),
email.getAllRecipientsEmails());
} else {
log.info("Email with subject '{}' not sent because of the config parameter smtp.nosend",
email.getSubject());
}

/*
* If the case, we save the email as document in LogicalDOC's repository
*/
email.setSentDate(now);
historycizeOutgoingEmail(email, message, from);
}

private void includeAttachments(EMail email, Multipart multipartMessage) throws MessagingException {
for (Integer partId : email.getAttachments().keySet()) {
EMailAttachment att = email.getAttachment(partId);
String mime = detectMimeType(att);
Expand All @@ -370,48 +388,40 @@ public void send(EMail email) throws MessagingException {
throw new MessagingException(e.getMessage(), e);
}

if (StringUtils.isNotEmpty(att.getDisposition()))
if ("remove".equals(att.getDisposition()))
if (StringUtils.isNotEmpty(att.getDisposition())) {
if ("remove".equals(att.getDisposition())) {
part.removeHeader("Content-Disposition");
else
} else {
part.setDisposition(att.getDisposition());
}
}

if (StringUtils.isNotEmpty(att.getContentType()))
part.setHeader("Content-Type", att.getContentType());

if (StringUtils.isNotEmpty(att.getContentEncoding()))
part.setHeader("Content-Transfer-Encoding", att.getContentEncoding());

mpMessage.addBodyPart(part);
multipartMessage.addBodyPart(part);
}
}

message.setContent(mpMessage);

MailDateFormat formatter = new MailDateFormat();
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // always use UTC
// for outgoing mail
Date now = new Date();
message.setHeader("Date", formatter.format(now));
private void includeImages(EMail email, Multipart multipartMessage) throws MessagingException {
int i = 1;
for (String image : email.getImages()) {
MimeBodyPart imageBodyPart = new MimeBodyPart();

if (!Context.get().getProperties().getBoolean("smtp.nosend", false)) {
try (Transport transport = buildTransport(session);) {
transport.sendMessage(message, message.getAllRecipients());
} catch (IOException e) {
try {
DataSource ds = new URLDataSource(UrlUtil.toURL(image));
imageBodyPart.setDataHandler(new DataHandler(ds));
} catch (MalformedURLException | URISyntaxException e) {
throw new MessagingException(e.getMessage(), e);
}

log.info("Sent email with subject '{}' to recipients {}", email.getSubject(),
email.getAllRecipientsEmails());
} else {
log.info("Email with subject '{}' not sent because of the config parameter smtp.nosend",
email.getSubject());
imageBodyPart.setHeader("Content-ID", "<image_" + (i++) + ">");
imageBodyPart.setDisposition("inline");
multipartMessage.addBodyPart(imageBodyPart);
}

/*
* If the case, we save the email as document in LogicalDOC's repository
*/
email.setSentDate(now);
historycizeOutgoingEmail(email, message, from);
}

protected InternetAddress prepareFrom(EMail email) throws AddressException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public String getContent() {
String tmp = content.toString();
if (tmp != null && tmp.length() > 0) {
// Clean all the unwanted characters
tmp = tmp.replaceAll("[<>\"“�`]", "");
tmp = tmp.replaceAll("[<>\"]", "");
}
return tmp;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,22 @@
*/
public class HibernateSearchDAO extends HibernatePersistentObjectDAO<SavedSearch> implements SearchDAO {

private static final String USERID = "userId";

private HibernateSearchDAO() {
super(SavedSearch.class);
super.log = LoggerFactory.getLogger(HibernateSearchDAO.class);
}

@Override
public List<SavedSearch> findByUserId(long userId) throws PersistenceException {
return findByWhere(ENTITY + ".userId = :userId", Map.of("userId", userId), ENTITY + ".name asc", null);
return findByWhere(ENTITY + ".userId = :userId", Map.of(USERID, userId), ENTITY + ".name asc", null);
}

@Override
public SavedSearch findByUserIdAndName(long userId, String name) throws PersistenceException {
List<SavedSearch> searches = findByWhere(ENTITY + ".userId = :userId and " + ENTITY + ".name = :name",
Map.of("userId", userId, "name", name), null, null);
Map.of(USERID, userId, "name", name), null, null);
if (searches.isEmpty())
return null;
else
Expand Down Expand Up @@ -74,7 +76,7 @@ private void setUniqueName(SavedSearch search) {

// Execute the query to populate the sets
try {
SqlRowSet rs = queryForRowSet(query.toString(), Map.of("userId", search.getUserId(), "baseName",
SqlRowSet rs = queryForRowSet(query.toString(), Map.of(USERID, search.getUserId(), "baseName",
baseName.toLowerCase() + "%", "id", search.getId()), null);
if (rs != null)
while (rs.next()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ public Device() {
* @param request the current request
*/
public Device(HttpServletRequest request) {
UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));

setDeviceId(getDeviceId(request));

UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
setBrowser(agent.getBrowser().getName());

if (agent.getBrowserVersion() != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,7 @@ public boolean isTrustedDevice(String username, HttpServletRequest request) thro
return false;

List<Device> trustedDevices = findTrustedDevices(user.getId());
for (Device device : trustedDevices)
if (device.equals(requestDevice))
return true;

return false;
return trustedDevices.stream().anyMatch(d -> d.getDeviceId().equals(requestDevice.getDeviceId()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.logicaldoc.core.security;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
Expand Down Expand Up @@ -33,6 +34,7 @@
import com.logicaldoc.core.security.user.User;
import com.logicaldoc.core.security.user.UserDAO;
import com.logicaldoc.util.Context;
import com.logicaldoc.util.crypt.CryptUtil;
import com.logicaldoc.util.sql.SqlUtil;

/**
Expand Down Expand Up @@ -466,11 +468,36 @@ public String getSessionId(HttpServletRequest request) {
if (auth instanceof LDAuthenticationToken ldAuthenticationToken)
return ldAuthenticationToken.getSid();

if (request != null && Context.get().getProperties().getBoolean("security.useclientid", true)) {
Client client = buildClient(request);
Session session = getByClientId(client.getId());
if (session != null && isOpen(session.getSid()))
return session.getSid();
return getSessionIdFromClient(request);
}

private String getSessionIdFromClient(HttpServletRequest request) {
if (request == null || !Context.get().getProperties().getBoolean("security.useclientid", false))
return null;

Client client = buildClient(request);
Session session = getByClientId(client.getId());

/*
* In case of ClienID match, we must check the session provides Basic
* Authentication and refers to the same username
*/
if (session != null && isOpen(session.getSid()) && session.getUsername().equals(client.getUsername())) {
String[] credentials = getBasicCredentials(request);
if (credentials.length == 2) {
try {
/*
* In case the current user has defined a password, also
* check it matches with the basic authentication
*/
final String sessionUserPassword = session.getUser().getPassword();
if (StringUtils.isEmpty(sessionUserPassword)
|| CryptUtil.encryptSHA256(credentials[1]).equals(sessionUserPassword))
return session.getSid();
} catch (NoSuchAlgorithmException e) {
log.error("Unable to check credentials", e);
}
}
}

return null;
Expand All @@ -488,13 +515,13 @@ else if (StringUtils.isNotEmpty(request.getHeader(PARAM_SID)))
sid = request.getHeader(PARAM_SID);
else if (request.getAttribute(PARAM_SID) != null
&& StringUtils.isNotEmpty((String) request.getAttribute(PARAM_SID)))
sid = (String) request.getAttribute(PARAM_SID);
sid = (String) request.getAttribute(PARAM_SID);
else if (request.getSession(true).getAttribute(PARAM_SID) != null
&& StringUtils.isNotEmpty((String) request.getSession(true).getAttribute(PARAM_SID)))
sid = (String) request.getSession(true).getAttribute(PARAM_SID);
else
else
sid = getSessionIdFromCookie(request);

return sid;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
public class HibernateSequenceDAO extends HibernatePersistentObjectDAO<Sequence> implements SequenceDAO {

private static final String TENANTID = "tenantId";
private static final String AND = " and ";

private HibernateSequenceDAO() {
Expand Down Expand Up @@ -88,7 +89,7 @@ public List<Sequence> findByName(String name, long tenantId) {
String query = " " + ENTITY + ".tenantId = :tenantId " + AND + ENTITY + ".name like :name ";

try {
return findByWhere(query, Map.of("tenantId", tenantId, "name", name + "%"), null, null);
return findByWhere(query, Map.of(TENANTID, tenantId, "name", name + "%"), null, null);
} catch (PersistenceException e) {
log.error(e.getMessage(), e);
return new ArrayList<>();
Expand Down Expand Up @@ -126,7 +127,7 @@ private Sequence findSequence(String sequenceName, long objectId, long tenantId,
String query = "select ld_id from ld_sequence where ld_name = :name and ld_objectid = :objectId and ld_tenantid = :tenantId";
try {
long sequenceId = queryForLong(query,
Map.of("tenantId", tenantId, "objectId", objectId, "name", sequenceName));
Map.of(TENANTID, tenantId, "objectId", objectId, "name", sequenceName));
if (sequenceId != 0L)
sequence = findById(sequenceId);
} catch (Exception t) {
Expand All @@ -142,7 +143,7 @@ private List<Sequence> findSequences(String sequenceName, long objectId, long te
query += AND + ENTITY + ".objectId = :objectId ";
query += AND + ENTITY + ".name = :name ";

sequences = findByWhere(query, Map.of("tenantId", tenantId, "objectId", objectId, "name", sequenceName),
sequences = findByWhere(query, Map.of(TENANTID, tenantId, "objectId", objectId, "name", sequenceName),
null, null);
} catch (Exception t) {
// Nothing to do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public Scheduler getObject() {
return super.getObject();
else {
log.debug(ASPECT_DISABLED);
return null;
return new DummyScheduler();
}
}

Expand Down
Loading

0 comments on commit bfa670a

Please sign in to comment.