Commit a700b911 authored by michael.simon's avatar michael.simon
Browse files

reorganize layer to be same as ecpcontroller for

attributequerycontroller
parent 0374e81f
package edu.kit.scc.webreg.service;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import edu.kit.scc.webreg.exc.RestInterfaceException;
public interface UserUpdateService {
Map<String, String> updateUser(String eppn, String serviceShortName,
String localHostName) throws IOException, ServletException,
RestInterfaceException;
Map<String, String> updateUser(Long regId, String localHostName)
throws IOException, ServletException, RestInterfaceException;
}
package edu.kit.scc.webreg.service.impl;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.ServletException;
import org.slf4j.Logger;
import edu.kit.scc.webreg.dao.RegistryDao;
import edu.kit.scc.webreg.dao.ServiceDao;
import edu.kit.scc.webreg.dao.UserDao;
import edu.kit.scc.webreg.drools.KnowledgeSessionService;
import edu.kit.scc.webreg.drools.OverrideAccess;
import edu.kit.scc.webreg.drools.UnauthorizedUser;
import edu.kit.scc.webreg.entity.BusinessRulePackageEntity;
import edu.kit.scc.webreg.entity.RegistryEntity;
import edu.kit.scc.webreg.entity.RegistryStatus;
import edu.kit.scc.webreg.entity.ServiceEntity;
import edu.kit.scc.webreg.entity.UserEntity;
import edu.kit.scc.webreg.exc.LoginFailedException;
import edu.kit.scc.webreg.exc.NoRegistryFoundException;
import edu.kit.scc.webreg.exc.NoServiceFoundException;
import edu.kit.scc.webreg.exc.NoUserFoundException;
import edu.kit.scc.webreg.exc.RestInterfaceException;
import edu.kit.scc.webreg.exc.UserUpdateException;
import edu.kit.scc.webreg.exc.UserUpdateFailedException;
import edu.kit.scc.webreg.service.UserUpdateService;
@Stateless
public class UserUpdateServiceImpl implements UserUpdateService, Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Logger logger;
@Inject
private UserDao userDao;
@Inject
private UserUpdater userUpdater;
@Inject
private KnowledgeSessionService knowledgeSessionService;
@Inject
private RegistryDao registryDao;
@Inject
private ServiceDao serviceDao;
@Override
public Map<String, String> updateUser(String eppn,
String serviceShortName, String localHostName)
throws IOException, ServletException, RestInterfaceException {
UserEntity user = findUser(eppn);
if (user == null)
throw new NoUserFoundException("no such user");
ServiceEntity service = findService(serviceShortName);
if (service == null)
throw new NoServiceFoundException("no such service");
RegistryEntity registry = findRegistry(user, service);
if (registry == null)
throw new NoRegistryFoundException("user not registered for service");
return update(user, service, registry, localHostName);
}
@Override
public Map<String, String> updateUser(Long regId, String localHostName)
throws IOException, ServletException, RestInterfaceException {
RegistryEntity registry = registryDao.findById(regId);
if (registry == null) {
logger.info("No registry found for id {}", regId);
throw new NoRegistryFoundException("registry unknown");
}
return update(registry.getUser(), registry.getService(), registry, localHostName);
}
private Map<String, String> update(UserEntity user, ServiceEntity service, RegistryEntity registry, String localHostName)
throws RestInterfaceException {
// Default expiry Time after which an attrq is issued to IDP in millis
Long expireTime = 10000L;
if (service.getServiceProps() != null && service.getServiceProps().containsKey("attrq_expire_time")) {
expireTime = Long.parseLong(service.getServiceProps().get("attrq_expire_time"));
}
try {
if ((System.currentTimeMillis() - user.getLastUpdate().getTime()) < expireTime) {
logger.info("Skipping attributequery for {} with {}@{}", new Object[] {user.getEppn(),
user.getPersistentId(), user.getIdp().getEntityId()});
}
else {
logger.info("Performing attributequery for {} with {}@{}", new Object[] {user.getEppn(),
user.getPersistentId(), user.getIdp().getEntityId()});
user = userUpdater.updateUserFromIdp(user, service);
}
} catch (UserUpdateException e) {
logger.warn("Could not update user {}: {}", e.getMessage(), user.getEppn());
throw new UserUpdateFailedException("user update failed: " + e.getMessage());
}
if (registry == null)
throw new NoRegistryFoundException("No such registry");
List<Object> objectList = checkRules(user, service, registry);
StringBuilder sb = new StringBuilder();
for (Object o : objectList) {
if (o instanceof OverrideAccess) {
objectList.clear();
sb.setLength(0);
logger.debug("Removing requirements due to OverrideAccess");
break;
}
else if (o instanceof UnauthorizedUser) {
String s = ((UnauthorizedUser) o).getMessage();
sb.append(s);
sb.append("\n");
}
}
if (sb.length() > 0) {
throw new LoginFailedException("user not allowd for service\n" + sb.toString());
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Map<String, String> map = new HashMap<String, String>();
map.put("eppn", user.getEppn());
map.put("email", user.getEmail());
map.put("last_update", df.format(user.getLastUpdate()));
return map;
}
private List<Object> checkRules(UserEntity user, ServiceEntity service, RegistryEntity registry) {
List<Object> objectList;
if (service.getAccessRule() == null) {
objectList = knowledgeSessionService.checkRule("default", "permitAllRule", "1.0.0", user, service, registry, "user-self", false);
}
else {
BusinessRulePackageEntity rulePackage = service.getAccessRule().getRulePackage();
if (rulePackage != null) {
objectList = knowledgeSessionService.checkRule(rulePackage.getPackageName(), rulePackage.getKnowledgeBaseName(),
rulePackage.getKnowledgeBaseVersion(), user, service, registry, "user-self", false);
}
else {
throw new IllegalStateException("checkServiceAccess called with a rule (" +
service.getAccessRule().getName() + ") that has no rulePackage");
}
}
return objectList;
}
private RegistryEntity findRegistry(UserEntity user, ServiceEntity service) {
RegistryEntity registry = registryDao.findByServiceAndUserAndStatus(service, user, RegistryStatus.ACTIVE);
if (registry == null) {
/*
* Also check for Lost_access registries. They should also be allowed to be rechecked.
*/
registry = registryDao.findByServiceAndUserAndStatus(service, user, RegistryStatus.LOST_ACCESS);
}
return registry;
}
private ServiceEntity findService(String serviceShortName) {
ServiceEntity service = serviceDao.findByShortName(serviceShortName);
if (service != null) {
service = serviceDao.findByIdWithServiceProps(service.getId());
}
return service;
}
private UserEntity findUser(String eppn) {
UserEntity user = userDao.findByEppn(eppn);
if (user != null) {
user = userDao.findByIdWithStore(user.getId());
}
return user;
}
}
......@@ -11,46 +11,36 @@
package edu.kit.scc.webreg.rest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import edu.kit.scc.webreg.dao.TextPropertyDao;
import edu.kit.scc.webreg.drools.KnowledgeSessionService;
import edu.kit.scc.webreg.drools.OverrideAccess;
import edu.kit.scc.webreg.drools.UnauthorizedUser;
import edu.kit.scc.webreg.entity.BusinessRulePackageEntity;
import edu.kit.scc.webreg.entity.RegistryEntity;
import edu.kit.scc.webreg.entity.RegistryStatus;
import edu.kit.scc.webreg.entity.ServiceEntity;
import edu.kit.scc.webreg.entity.TextPropertyEntity;
import edu.kit.scc.webreg.entity.UserEntity;
import edu.kit.scc.webreg.exc.LoginFailedException;
import edu.kit.scc.webreg.exc.GenericRestInterfaceException;
import edu.kit.scc.webreg.exc.NoRegistryFoundException;
import edu.kit.scc.webreg.exc.NoServiceFoundException;
import edu.kit.scc.webreg.exc.NoUserFoundException;
import edu.kit.scc.webreg.exc.RestInterfaceException;
import edu.kit.scc.webreg.exc.UserUpdateException;
import edu.kit.scc.webreg.exc.UnauthorizedException;
import edu.kit.scc.webreg.exc.UserUpdateFailedException;
import edu.kit.scc.webreg.rest.dto.AttributeQueryResponse;
import edu.kit.scc.webreg.rest.dto.RestError;
import edu.kit.scc.webreg.service.RegistryService;
import edu.kit.scc.webreg.service.ServiceService;
import edu.kit.scc.webreg.service.UserService;
import edu.kit.scc.webreg.service.UserUpdateService;
@Path("/attrq")
public class AttributeQueryController {
......@@ -59,16 +49,7 @@ public class AttributeQueryController {
private Logger logger;
@Inject
private UserService userService;
@Inject
private ServiceService serviceService;
@Inject
private RegistryService registryService;
@Inject
private KnowledgeSessionService knowledgeSessionService;
private UserUpdateService userUpdateService;
@Inject
private TextPropertyDao textPropertyDao;
......@@ -77,101 +58,121 @@ public class AttributeQueryController {
@Path("/eppn/{service}/{eppn}")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> attributeQuery(@PathParam("eppn") String eppn,
@PathParam("service") String serviceShortName)
@PathParam("service") String serviceShortName, @Context HttpServletRequest request)
throws IOException, ServletException, RestInterfaceException {
return attributeQueryInternJSON(eppn, serviceShortName);
return userUpdateService.updateUser(eppn, serviceShortName, request.getLocalName());
}
@GET
@Path("/regid/{regid}")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> attributeQuery(@PathParam("regid") Long regId)
public Map<String, String> attributeQuery(@PathParam("regid") Long regId, @Context HttpServletRequest request)
throws IOException, ServletException, RestInterfaceException {
RegistryEntity registry = registryService.findById(regId);
if (registry == null) {
logger.info("No registry found for id {}", regId);
throw new NoRegistryFoundException("No such registry");
}
return attributeQueryInternJSON(registry.getUser().getEppn(), registry.getService().getShortName());
return userUpdateService.updateUser(regId, request.getLocalName());
}
@GET
@Path("/eppn-xml/{service}/{eppn}")
@Produces(MediaType.APPLICATION_XML)
public AttributeQueryResponse attributeQueryXML(@PathParam("eppn") String eppn,
@PathParam("service") String serviceShortName)
@PathParam("service") String serviceShortName, @Context HttpServletRequest request)
throws IOException, ServletException, RestInterfaceException {
return attributeQueryInternXML(eppn, serviceShortName);
AttributeQueryResponse response = new AttributeQueryResponse();
try {
userUpdateService.updateUser(eppn, serviceShortName, request.getLocalName());
}
catch (NoUserFoundException e) {
generateFailXml(response, 400, "ecp login failed", "user-not-found");
return response;
}
catch (NoServiceFoundException e) {
generateFailXml(response, 400, "ecp login failed", "no-such-service");
return response;
}
catch (NoRegistryFoundException e) {
generateFailXml(response, 400, "ecp login failed", "user-not-registered");
return response;
}
catch (UserUpdateFailedException e) {
generateFailXml(response, 400, "ecp login failed", "user-update-failed");
return response;
}
catch (UnauthorizedException e) {
response.setCode(405);
response.setMessage("rules failed");
for (UnauthorizedUser uu : e.getUnauthList()) {
addXmlError(response, uu.getMessage(), resolveString(uu.getMessage()));
}
}
catch (GenericRestInterfaceException e) {
generateFailXml(response, 500, "ecp login failed", "generic-error");
return response;
}
catch (RestInterfaceException e) {
logger.warn("Unmapped RestInterfaceException!", e);
generateFailXml(response, 400, "ecp login failed", "unknown-error");
return response;
}
response.setCode(200);
response.setMessage("success");
return response;
}
@GET
@Path("/regid-xml/{regid}")
@Produces(MediaType.APPLICATION_XML)
public AttributeQueryResponse attributeQueryXML(@PathParam("regid") Long regId)
public AttributeQueryResponse attributeQueryXML(@PathParam("regid") Long regId, @Context HttpServletRequest request)
throws IOException, ServletException, RestInterfaceException {
RegistryEntity registry = registryService.findById(regId);
if (registry == null) {
logger.info("No registry found for id {}", regId);
throw new NoRegistryFoundException("No such registry");
}
return attributeQueryInternXML(registry.getUser().getEppn(), registry.getService().getShortName());
}
private AttributeQueryResponse attributeQueryInternXML(String eppn, String serviceShortName) {
AttributeQueryResponse response = new AttributeQueryResponse();
ServiceEntity service = findService(serviceShortName);
if (service == null) {
generateFailXml(response, 400, "attribute query failed", "no-such-service");
return response;
try {
userUpdateService.updateUser(regId, request.getLocalName());
}
UserEntity user = findUser(eppn);
if (user == null) {
generateFailXml(response, 400, "attribute query failed", "no-such-user");
catch (NoUserFoundException e) {
generateFailXml(response, 400, "ecp login failed", "user-not-found");
return response;
}
try {
updateUser(user, service);
} catch (UserUpdateFailedException e) {
generateFailXml(response, 400, "attribute query failed", "user-update-failed");
catch (NoServiceFoundException e) {
generateFailXml(response, 400, "ecp login failed", "no-such-service");
return response;
}
RegistryEntity registry = findRegistry(user, service);
if (registry == null) {
generateFailXml(response, 400, "attribute query failed", "no-registry-found");
catch (NoRegistryFoundException e) {
generateFailXml(response, 400, "ecp login failed", "user-not-registered");
return response;
}
List<Object> objectList = checkRules(user, service, registry);
List<OverrideAccess> overrideAccessList = extractOverideAccess(objectList);
List<UnauthorizedUser> unauthorizedUserList = extractUnauthorizedUser(objectList);
if (unauthorizedUserList.size() == 0 || overrideAccessList.size() > 0) {
response.setCode(200);
response.setMessage("success");
catch (UserUpdateFailedException e) {
generateFailXml(response, 400, "ecp login failed", "user-update-failed");
return response;
}
else {
catch (UnauthorizedException e) {
response.setCode(405);
response.setMessage("rules failed");
for (UnauthorizedUser uu : unauthorizedUserList) {
for (UnauthorizedUser uu : e.getUnauthList()) {
addXmlError(response, uu.getMessage(), resolveString(uu.getMessage()));
}
}
catch (GenericRestInterfaceException e) {
generateFailXml(response, 500, "ecp login failed", "generic-error");
return response;
}
catch (RestInterfaceException e) {
logger.warn("Unmapped RestInterfaceException!", e);
generateFailXml(response, 400, "ecp login failed", "unknown-error");
return response;
}
response.setCode(200);
response.setMessage("success");
return response;
}
private String resolveString(String key) {
String enString = resolveString(key, Locale.ENGLISH);
String deString = resolveString(key, Locale.GERMAN);
......@@ -209,135 +210,7 @@ public class AttributeQueryController {
}
}
private Map<String, String> attributeQueryInternJSON(String eppn, String serviceShortName)
throws RestInterfaceException {
ServiceEntity service = findService(serviceShortName);
if (service == null)
throw new NoServiceFoundException("No such service");
UserEntity user = findUser(eppn);
if (user == null)
throw new NoUserFoundException("No such user");
updateUser(user, service);
RegistryEntity registry = findRegistry(user, service);
if (registry == null)
throw new NoRegistryFoundException("No such registry");
List<Object> objectList = checkRules(user, service, registry);
StringBuilder sb = new StringBuilder();
for (Object o : objectList) {
if (o instanceof OverrideAccess) {
objectList.clear();
sb.setLength(0);
logger.debug("Removing requirements due to OverrideAccess");
break;
}
else if (o instanceof UnauthorizedUser) {
String s = ((UnauthorizedUser) o).getMessage();
sb.append(s);
sb.append("\n");
}
}
if (sb.length() > 0) {
throw new LoginFailedException("user not allowd for service\n" + sb.toString());
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Map<String, String> map = new HashMap<String, String>();
map.put("eppn", user.getEppn());
map.put("email", user.getEmail());
map.put("last_update", df.format(user.getLastUpdate()));
return map;
}
private ServiceEntity findService(String serviceShortName) {
ServiceEntity service = serviceService.findByShortName(serviceShortName);
if (service != null) {
service = serviceService.findByIdWithServiceProps(service.getId());
}
return service;
}
private UserEntity findUser(String eppn) {
UserEntity user = userService.findByEppn(eppn);
if (user != null) {
user = userService.findByIdWithStore(user.getId());
}
return user;
}
private void updateUser(UserEntity user, ServiceEntity service) throws UserUpdateFailedException {
// Default expiry Time after which an attrq is issued to IDP in millis
Long expireTime = 10000L;
if (service.getServiceProps() != null && service.getServiceProps().containsKey("attrq_expire_time")) {
expireTime = Long.parseLong(service.getServiceProps().get("attrq_expire_time"));
}
try {
if ((System.currentTimeMillis() - user.getLastUpdate().getTime()) < expireTime) {
logger.info("Skipping attributequery for {} with {}@{}", new Object[] {user.getEppn(),
user.getPersistentId(), user.getIdp().getEntityId()});
}
else {
logger.info("Performing attributequery for {} with {}@{}", new Object[] {user.getEppn(),
user.getPersistentId(), user.getIdp().getEntityId()});
user = userService.updateUserFromIdp(user, service);
}
} catch (UserUpdateException e) {
logger.warn("Could not update user {}: {}", e.getMessage(), user.getEppn());
throw new UserUpdateFailedException("user update failed: " + e.getMessage());
}
}
private RegistryEntity findRegistry(UserEntity user, ServiceEntity service) {