Mejora en la gestión de excepciones y errores. Nuevo managedBean para

gestión de errores anto AJAX como en peticiones normales.
This commit is contained in:
Marcos Garcia Nuñez
2020-01-01 21:42:31 +01:00
parent 7e04274255
commit 75ed5e2635
5 changed files with 257 additions and 199 deletions

View File

@@ -48,153 +48,118 @@ public class AuthorizationFilter implements Filter {
HttpServletResponse resp = null;
HttpSession ses = null;
// Si establecemos esta variable a true se realiza el autologin
// TODO: Eliminar esta variable al terminar el desarrollo
boolean Debug = false;
try {
req = (HttpServletRequest) request;
String reqURI = req.getRequestURI();
ses = req.getSession(false);
req = (HttpServletRequest) request;
String reqURI = req.getRequestURI();
resp = (HttpServletResponse) response;
resp = (HttpServletResponse) response;
// TODO: Eliminar este código al terminar el desarrollo.
// Realizamos un login automatico (para agilizar el desarrollo.
if (Debug == true) {
ses = req.getSession(true);
if (SessionUtils.isLogedIn(ses) == false) {
LoginMBean login = new LoginMBean();
login.setUsername("PRO#100");
login.setPassword("asdf");
boolean result = login.autoLogin(ses);
if (result == true)
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR, "Login automático correcto", "Se ha realizado un login automático correctamente.");
else
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR, "El login automático ha fallado.", "No se ha podido realizar el login automático.");
}
}
ses = req.getSession(false);
// Para recursos publicos permitimos el acceso exista sesión o no.
if (reqURI.indexOf("/login.xhtml") >= 0 || reqURI.indexOf("/profile/RegisterUser.xhtml") >= 0 || reqURI.indexOf("/home.xhtml") >= 0
|| reqURI.indexOf("/error.xhtml") >= 0 || reqURI.indexOf("/public/") >= 0 || reqURI.contains("javax.faces.resource")) {
chain.doFilter(request, response);
return;
}
if (this.isAJAXRequest(req) == true) {
chain.doFilter(request, response);
return;
}
// Sesión expirada
if (req.isRequestedSessionIdValid() == false && req.getRequestedSessionId() != null) {
resp.sendRedirect(req.getContextPath() + "/error.xhtml?type=expired");
return;
}
// Si el usuario está logeado comprobamos si está autorizado a ver la página solicitada.
if (SessionUtils.isLogedIn(ses) == true) {
UserType tipoUsuario = SessionUtils.getUserType(ses);
boolean authorized = false;
switch (tipoUsuario) {
case ADMINISTRATOR:
if (reqURI.indexOf("/systemAdmin/ManageSpecialties") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/ManageHealthCareCenters") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/ListDoctorsByCenter") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/AddAdmin") > 0)
authorized = true;
if (reqURI.indexOf("/visit/PatientVisitList") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
break;
case PATIENT:
if (reqURI.indexOf("/visit/VisitView") > 0)
authorized = true;
if (reqURI.indexOf("/visit/AddVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/PatientVisitList") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/Questions") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/SearchSpecialist") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
if (reqURI.indexOf("/profile/ChangeFamilyDoctor") > 0)
authorized = true;
break;
case FAMILY_DOCTOR:
if (reqURI.indexOf("/visit/VisitView") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/VisitList") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/Questions") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
if (reqURI.indexOf("/profile/ChangePrimaryHealthCareCenter") > 0)
authorized = true;
break;
case SPECIALIST_DOCTOR:
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/AddMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/AddImageToMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
break;
}
if (authorized == true) {
chain.doFilter(request, response);
return;
} else {
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR,
"No está autorizado a acceder a la página solicitada. Por favor, utilice el menú principal de la aplicación.",
String.format("Se ha producido una expción de autorización, su usuario no está autorizado a acceder a la página: (%s).", reqURI));
resp.sendRedirect(req.getContextPath() + "/error.xhtml?type=auth");
return;
}
}
resp.sendRedirect(req.getContextPath() + "/login.xhtml");
} catch (Exception e) {
if (Exceptions.is(e, PersistenceException.class) == true) {
if (ses != null)
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR, "Error al intentar acceder a la base de datos", Utils.getExceptionRootCause(e).getLocalizedMessage());
resp.sendRedirect(req.getContextPath() + "/error.xhtml?type=sql");
} else {
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR, "Error interno del servidor", Utils.getExceptionRootCause(e).getLocalizedMessage());
resp.sendRedirect(req.getContextPath() + "/error.xhtml");
}
// Para recursos publicos permitimos el acceso exista sesión o no.
if (reqURI.indexOf("/login.xhtml") >= 0 || reqURI.indexOf("/profile/RegisterUser.xhtml") >= 0 || reqURI.indexOf("/home.xhtml") >= 0 || reqURI.indexOf("/error.xhtml") >= 0
|| reqURI.indexOf("/public/") >= 0 || reqURI.contains("javax.faces.resource")) {
chain.doFilter(request, response);
return;
}
if (this.isAJAXRequest(req) == true) {
chain.doFilter(request, response);
return;
}
// Sesión expirada
if (req.isRequestedSessionIdValid() == false && req.getRequestedSessionId() != null) {
resp.sendRedirect(req.getContextPath() + "/error.xhtml?type=expired");
return;
}
// Si el usuario está logeado comprobamos si está autorizado a ver la página solicitada.
if (SessionUtils.isLogedIn(ses) == true) {
UserType tipoUsuario = SessionUtils.getUserType(ses);
boolean authorized = false;
switch (tipoUsuario) {
case ADMINISTRATOR:
if (reqURI.indexOf("/systemAdmin/ManageSpecialties") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/ManageHealthCareCenters") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/ListDoctorsByCenter") > 0)
authorized = true;
if (reqURI.indexOf("/systemAdmin/AddAdmin") > 0)
authorized = true;
if (reqURI.indexOf("/visit/PatientVisitList") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
break;
case PATIENT:
if (reqURI.indexOf("/visit/VisitView") > 0)
authorized = true;
if (reqURI.indexOf("/visit/AddVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/PatientVisitList") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/Questions") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/SearchSpecialist") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
if (reqURI.indexOf("/profile/ChangeFamilyDoctor") > 0)
authorized = true;
break;
case FAMILY_DOCTOR:
if (reqURI.indexOf("/visit/VisitView") > 0)
authorized = true;
if (reqURI.indexOf("/visit/UpdateVisit") > 0)
authorized = true;
if (reqURI.indexOf("/visit/VisitList") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/Questions") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
if (reqURI.indexOf("/profile/ChangePrimaryHealthCareCenter") > 0)
authorized = true;
break;
case SPECIALIST_DOCTOR:
if (reqURI.indexOf("/medicaltest/MedicalTests") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/AddMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/ViewMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/medicaltest/AddImageToMedicalTest") > 0)
authorized = true;
if (reqURI.indexOf("/profile/UpdateProfile") > 0)
authorized = true;
break;
}
if (authorized == true) {
chain.doFilter(request, response);
return;
} else {
SessionUtils.addMessage(ses, FacesMessage.SEVERITY_ERROR,
"No está autorizado a acceder a la página solicitada. Por favor, utilice el menú principal de la aplicación.",
String.format("Se ha producido una expción de autorización, su usuario no está autorizado a acceder a la página: (%s).", reqURI));
resp.sendRedirect(req.getContextPath() + "/error.xhtml?type=auth");
return;
}
}
resp.sendRedirect(req.getContextPath() + "/login.xhtml");
}
@Override

View File

@@ -0,0 +1,118 @@
package managedbean.common;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import TO.VisitTO;
/***
*
* @author Marcos García Núñez (mgarcianun@uoc.edu)
*
*/
@Named("error")
@RequestScoped
public class errorMBean extends ManagedBeanBase implements Serializable {
private static final long serialVersionUID = 1L;
private String errorType;
private String requestURI;
private boolean renderBack;
@PostConstruct
public void init() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
this.setRenderBack(false);
if (fc != null) {
HttpServletRequest req = (HttpServletRequest) fc.getExternalContext().getRequest();
Map<String, String> requestParams = fc.getExternalContext().getRequestParameterMap();
this.errorType = this.getRequestParameter(requestParams,"type");
if (this.errorType.equals("") == true) {
this.requestURI = this.getRequestAttribute(req, "javax.servlet.error.request_uri");
if (requestURI.equals("") == true)
this.requestURI = req.getContextPath().concat("/home.xhtml");
setRenderBack(true);
this.errorType = this.getRequestAttribute(req, "javax.servlet.error.exception_type").replaceFirst("class ", "");
// Si no hay error volvemos al home.
if (this.errorType.equals("") == true)
fc.getExternalContext().redirect(req.getContextPath().concat("/home.xhtml"));
switch (this.errorType) {
case "javax.faces.application.ViewExpiredException":
this.errorType = "expired";
this.addFacesMessage(FacesMessage.SEVERITY_WARN, "Sesión caducada", "Su sesión ha caducado, debe logearse de nuevo");
break;
case "java.sql.SQLException":
case "org.hibernate.exception.GenericJDBCException":
case "java.net.ConnectException":
case "javax.persistence.PersistenceException":
this.errorType = "sql";
this.addFacesMessage(FacesMessage.SEVERITY_ERROR, "Error interno del servidor", this.getRequestAttribute(req, "javax.servlet.error.message"));
break;
default:
this.errorType = "runtime";
this.addFacesMessage(FacesMessage.SEVERITY_ERROR, "Error interno del servidor", this.getRequestAttribute(req, "javax.servlet.error.message"));
}
}
}
}
private String getRequestAttribute(HttpServletRequest req, String attrName) {
Object attr = req.getAttribute(attrName);
if (attr != null)
return attr.toString();
else
return "";
}
private String getRequestParameter(Map<String, String> pars, String paramName) {
Object par = pars.get(paramName);
if (par != null)
return par.toString();
else
return "";
}
public String getErrorType() {
return errorType;
}
public void setErrorType(String errorType) {
this.errorType = errorType;
}
public String getRequestURI() {
return requestURI;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public boolean isRenderBack() {
return renderBack;
}
public void setRenderBack(boolean renderBack) {
this.renderBack = renderBack;
}
}