
se.wfh.libs.common.web.util.ApplicationHelper Maven / Gradle / Ivy
package se.wfh.libs.common.web.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class ApplicationHelper {
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationHelper.class);
public static final String USER_ID_KEY = "wfh_userId";
public static final String ADMIN_KEY = "wfh_isAdmin";
public static final String EXCEPTION_KEY = "wfh_exception";
private ApplicationHelper() {
throw new AssertionError("No instances for you!");
}
public static HttpSession getSession(final HttpServletRequest request) {
return request.getSession(true);
}
public static String getIp(final HttpServletRequest req) {
String ip = req.getRemoteAddr();
if (req.getHeader("x-forwarded-for") != null && isLocalhost(ip)) {
ip = req.getHeader("x-forwarded-for");
}
return ip;
}
private static boolean isLocalhost(final String remoteAddr) {
try {
return NetworkInterface.getByInetAddress(InetAddress
.getByName(remoteAddr)) != null;
} catch (SocketException | UnknownHostException sex) {
LOGGER.warn("Error fetching inetinterface");
LOGGER.debug(sex.getLocalizedMessage(), sex);
return false;
}
}
public static Integer getUserId(final HttpSession session) {
return (Integer) session.getAttribute(USER_ID_KEY);
}
public static Throwable getException(final HttpSession session) {
Throwable thr = (Throwable) session.getAttribute(EXCEPTION_KEY);
session.removeAttribute(EXCEPTION_KEY);
return thr;
}
public static Boolean isAdmin(final HttpSession session) {
return Boolean.TRUE.equals(session.getAttribute(ADMIN_KEY));
}
public static Boolean isLoggedIn(final HttpSession session) {
return getUserId(session) != null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy