Commit b36799be authored by ls1947's avatar ls1947
Browse files

start some refactoring classes

parent 19bb3b86
package edu.kit.scc.webreg.service.twofa;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.kit.scc.webreg.entity.UserEntity;
public class LinotpConnection {
private static final Logger logger = LoggerFactory.getLogger(LinotpConnection.class);
private Map<String, String> configMap;
private URI uri;
private HttpHost targetHost;
private AuthCache authCache;
private CredentialsProvider credsProvider;
private RequestConfig config;
private CloseableHttpClient httpClient;
private HttpClientContext context;
private String adminSession;
public LinotpConnection(Map<String, String> configMap) throws TwoFaException {
super();
this.configMap = configMap;
init();
}
public void close() {
try {
httpClient.close();
} catch (IOException e) {
}
}
protected void init() throws TwoFaException {
try {
uri = new URI(configMap.get("url"));
} catch (URISyntaxException e) {
throw new TwoFaException(e);
}
targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(configMap.get("username"), configMap.get("password"));
credsProvider.setCredentials(AuthScope.ANY, credentials);
context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
config = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.build();
httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
}
public LinotpTokenResultList getTokenList(UserEntity user) throws TwoFaException {
LinotpTokenResultList resultList = new LinotpTokenResultList();
try {
HttpPost httpPost = new HttpPost(configMap.get("url") + "/admin/show");
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
if (configMap.containsKey("userId"))
nvps.add(new BasicNameValuePair("user", configMap.get("userId")));
else
nvps.add(new BasicNameValuePair("user", user.getEppn()));
if (configMap.containsKey("realm"))
nvps.add(new BasicNameValuePair("realm", configMap.get("realm")));
nvps.add(new BasicNameValuePair("session", adminSession));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context);
try {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
logger.debug(responseString);
ObjectMapper om = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> map = om.readValue(responseString, Map.class);
if (map.get("result") instanceof Map<?, ?>) {
Map<?, ?> resultMap = (Map<?, ?>) map.get("result");
logger.debug("value: " + resultMap.get("value").getClass().toString());
if (resultMap.get("value") instanceof Map<?, ?>) {
Map<?, ?> valueMap = (Map<?, ?>) resultMap.get("value");
logger.debug("data: " + valueMap.get("data").getClass().toString());
List<?> dataList = getDataList(valueMap);
for (Object data : dataList) {
if (data instanceof Map<?, ?>) {
Map<?, ?> dataMap = (Map<?, ?>) data;
logger.debug("ID: " + dataMap.get("LinOtp.TokenId"));
LinotpToken lt = new LinotpToken();
lt.setSerial(dataMap.get("LinOtp.TokenSerialnumber").toString());
for (Object key : dataMap.keySet()) {
if (key instanceof String) {
Object value = dataMap.get(key);
lt.getValueMap().put((String) key, value);
}
else {
logger.warn("linotp key is not string type: {} ({})", key, key.getClass());
}
}
resultList.add(lt);
}
}
}
}
} finally {
response.close();
}
} catch (ParseException | IOException e) {
throw new TwoFaException(e);
}
return resultList;
}
public void requestAdminSession() throws TwoFaException {
HttpPost httpPost = new HttpPost(configMap.get("url") + "/admin/getsession");
adminSession = null;
try {
CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context);
try {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
logger.debug(responseString);
CookieStore cookieStore = context.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
logger.debug("Cookie {}: {}", cookie.getName(), cookie.getValue());
if (cookie.getName().equalsIgnoreCase("admin_session")) {
adminSession = cookie.getValue();
}
}
} finally {
response.close();
}
} catch (ParseException | IOException e) {
throw new TwoFaException(e);
}
if (adminSession == null) {
throw new TwoFaException("LinOTP issued no admin session. Cannot continue.");
}
}
protected List<?> getDataList(Map<?, ?> valueMap) {
logger.debug("data: " + valueMap.get("data").getClass().toString());
if (valueMap.get("data") instanceof List<?>) {
List<?> dataList = (List<?>) valueMap.get("data");
return dataList;
}
else {
return null;
}
}
}
package edu.kit.scc.webreg.service.twofa;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class LinotpToken implements Serializable {
private static final long serialVersionUID = 1L;
private String serial;
private Map<String, Object> valueMap;
private Boolean readOnly;
public LinotpToken() {
valueMap = new HashMap<String, Object>();
}
public String getSerial() {
return serial;
}
public Boolean getReadOnly() {
return readOnly;
}
public void setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
}
public void setSerial(String serial) {
this.serial = serial;
}
public Map<String, Object> getValueMap() {
return valueMap;
}
public void setValueMap(Map<String, Object> valueMap) {
this.valueMap = valueMap;
}
}
package edu.kit.scc.webreg.service.twofa;
import java.util.ArrayList;
public class LinotpTokenResultList extends ArrayList<LinotpToken> {
private static final long serialVersionUID = 1L;
private String status;
private String statusMessage;
private boolean readOnly;
private String managementUrl;
public LinotpTokenResultList() {
super();
}
public boolean getReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public String getManagementUrl() {
return managementUrl;
}
public void setManagementUrl(String managementUrl) {
this.managementUrl = managementUrl;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
}
package edu.kit.scc.webreg.service.twofa;
import java.util.List;
public interface TwoFaService {
List<?> findByUserId(Long userId) throws TwoFaException;
LinotpTokenResultList findByUserId(Long userId) throws TwoFaException;
}
package edu.kit.scc.webreg.service.twofa;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.inject.Inject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.kit.scc.webreg.dao.UserDao;
import edu.kit.scc.webreg.entity.UserEntity;
......@@ -51,119 +23,30 @@ public class TwoFaServiceImpl implements TwoFaService {
private UserDao userDao;
@Override
public List<?> findByUserId(Long userId) throws TwoFaException {
public LinotpTokenResultList findByUserId(Long userId) throws TwoFaException {
UserEntity user = userDao.findById(userId);
Map<String, String> configMap = configResolver.resolveConfig(user);
try {
URI uri = new URI(configMap.get("url"));
HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(configMap.get("username"), configMap.get("password"));
credsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
String adminSession = null;
try {
HttpPost httpPost = new HttpPost(configMap.get("url") + "/admin/getsession");
CloseableHttpResponse response = httpClient.execute(targetHost, httpPost, context);
try {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
logger.debug(responseString);
CookieStore cookieStore = context.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
logger.debug("Cookie {}: {}", cookie.getName(), cookie.getValue());
if (cookie.getName().equalsIgnoreCase("admin_session")) {
adminSession = cookie.getValue();
}
}
} finally {
response.close();
}
if (adminSession == null) {
throw new TwoFaException("LinOTP issued no admin session. Cannot continue.");
}
LinotpConnection linotpConnection = new LinotpConnection(configMap);
linotpConnection.requestAdminSession();
LinotpTokenResultList resultList = linotpConnection.getTokenList(user);
if (configMap.containsKey("readOnly") && configMap.get("readOnly").equalsIgnoreCase("true")) {
resultList.setReadOnly(true);
}
else {
resultList.setReadOnly(false);
}
httpPost = new HttpPost(configMap.get("url") + "/admin/show");
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
if (configMap.containsKey("userId"))
nvps.add(new BasicNameValuePair("user", configMap.get("userId")));
else
nvps.add(new BasicNameValuePair("user", user.getEppn()));
if (configMap.containsKey("realm"))
nvps.add(new BasicNameValuePair("realm", configMap.get("realm")));
nvps.add(new BasicNameValuePair("session", adminSession));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
response = httpClient.execute(targetHost, httpPost, context);
try {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
logger.debug(responseString);
ObjectMapper om = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> map = om.readValue(responseString, Map.class);
if (map.get("result") instanceof Map<?, ?>) {
Map<?, ?> resultMap = (Map<?, ?>) map.get("result");
logger.debug("value: " + resultMap.get("value").getClass().toString());
if (resultMap.get("value") instanceof Map<?, ?>) {
Map<?, ?> valueMap = (Map<?, ?>) resultMap.get("value");
logger.debug("data: " + valueMap.get("data").getClass().toString());
List<?> dataList = getDataList(valueMap);
for (Object data : dataList) {
if (data instanceof Map<?, ?>) {
Map<?, ?> dataMap = (Map<?, ?>) data;
logger.debug("ID: " + dataMap.get("LinOtp.TokenId"));
}
}
return dataList;
}
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
return null;
} catch (IOException | URISyntaxException e) {
throw new TwoFaException(e);
if (configMap.containsKey("managementUrl")) {
resultList.setManagementUrl(configMap.get("managementUrl"));
}
return resultList;
}
protected List<?> getDataList(Map<?, ?> valueMap) {
logger.debug("data: " + valueMap.get("data").getClass().toString());
if (valueMap.get("data") instanceof List<?>) {
List<?> dataList = (List<?>) valueMap.get("data");
return dataList;
}
else {
return null;
}
}
}
......@@ -11,7 +11,6 @@
package edu.kit.scc.webreg.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
......@@ -22,6 +21,7 @@ import org.slf4j.Logger;
import edu.kit.scc.webreg.entity.UserEntity;
import edu.kit.scc.webreg.service.UserService;
import edu.kit.scc.webreg.service.twofa.LinotpTokenResultList;
import edu.kit.scc.webreg.service.twofa.TwoFaException;
import edu.kit.scc.webreg.service.twofa.TwoFaService;
import edu.kit.scc.webreg.session.SessionManager;
......@@ -50,7 +50,7 @@ public class TwoFaUserBean implements Serializable {
private FacesMessageGenerator messageGenerator;
private UserEntity user;
private List<?> tokenList;
private LinotpTokenResultList tokenList;
public void preRenderView(ComponentSystemEvent ev) {
if (user == null) {
......@@ -64,7 +64,15 @@ public class TwoFaUserBean implements Serializable {
}
}
public List<?> getTokenList() {
public Boolean getReadOnly() {
return tokenList.getReadOnly();
}
public String getManagementUrl() {
return tokenList.getManagementUrl();
}
public LinotpTokenResultList getTokenList() {
return tokenList;
}
......
......@@ -24,14 +24,21 @@
<ui:define name="content">
<h:form id="form">
<p:panel header="#{messages.twofa}">
<p:messages id="messageBox" for="key_error" showDetail="true" />
<p:messages id="messageBox" for="key_error" showDetail="true" />
<p:panel header="#{messages.twofa_list}" rendered="#{twoFaUserBean.readOnly}">
<div><h:outputText value="#{messages.twofa_list_readonly}"/></div>
<div><a href="#{twoFaUserBean.managementUrl}" target="_blank">#{twoFaUserBean.managementUrl}</a></div>
<p:repeat var="token" value="#{twoFaUserBean.tokenList}">
<div><h:outputText value="#{token.serial}" /></div>
</p:repeat>
</p:panel>
<p:panel header="#{messages.twofa_list}" rendered="#{! twoFaUserBean.readOnly}">
<p:repeat var="token" value="#{twoFaUserBean.tokenList}">
<div>
<h:outputText value="#{token.get('LinOtp.TokenSerialnumber')}" />
</div>
<div><h:outputText value="#{token.serial}" /></div>
</p:repeat>
</p:panel>
</h:form>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment