Commit 06ad5dfb by Alonso Moreno

Implementacion WebFilter y autenticacion

parent c46daa5a
package demojsoncrud.servlets;
import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
......@@ -12,6 +14,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
@WebFilter("/*")
public class RequestFilter implements Filter, ServletContextListener {
......@@ -23,20 +26,67 @@ public class RequestFilter implements Filter, ServletContextListener {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
System.out.println("Filter");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
System.out.println("req URI ==> " + request.getRequestURI());
System.out.println("req Path ==> " + request.getContextPath());
String respuesta = "";
String indexPath = "http://localhost:8080/proyecto-estandar/vistas/index.jsp";
String index = "vistas/index.jsp";
String urlRequested = "http://172.16.2.53:8080/security-rest/api/user/verificarLogin";
String login = request.getContextPath() + "/vistas/index.jsp";
String assets = request.getContextPath() + "/plantilla/assets";
String css = request.getContextPath() + "/plantilla/css";
String js = request.getContextPath() + "/plantilla/js";
chain.doFilter(request, response);
if (String.valueOf(request.getRequestURL()).contains("http://localhost:8080/proyecto-estandar/")) {
String login = request.getContextPath() + "/vistas/index.jsp";
String main = request.getContextPath() + "/vistas/main.jsp";
String plantilla = request.getContextPath() + "/plantilla";
String js = request.getContextPath() + "/js";
String url = String.valueOf(request.getRequestURL());
if (url.contains(login) || url.contains(plantilla) || url.contains(js) || url.contains(main) || url.contains(".jsp")) {
chain.doFilter(request, response);
} else {
String auth = request.getHeader("Authorization");
PostRequest postRequest = new PostRequest(urlRequested);
respuesta = postRequest.getRespueta(auth);
JSONObject valid = new JSONObject(respuesta);
if (valid.getBoolean("status")) {
chain.doFilter(request, response);
} else {
if (isAJAXRequest(request)) {
StringBuilder sb = new StringBuilder();
sb.append("");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
PrintWriter pw = response.getWriter();
pw.println(sb.toString());
pw.flush();
return;
}
response.sendRedirect(indexPath);
}
}
} else {
if (isAJAXRequest(request)) {
StringBuilder sb = new StringBuilder();
sb.append("");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
PrintWriter pw = response.getWriter();
pw.println(sb.toString());
pw.flush();
return;
}
response.sendRedirect(indexPath);
}
}
private boolean isAJAXRequest(HttpServletRequest request) {
boolean check = false;
String facesRequest = request.getHeader("Faces-Request");
if (facesRequest != null && facesRequest.equals("partial/ajax")) {
check = true;
}
return check;
}
@Override
......
package demojsoncrud.utilities;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class PostRequest {
private URL url;
String data;
public PostRequest(String url) throws MalformedURLException {
this.url = new URL(url);
data = "";
}
public void add(String propiedad, String valor) throws UnsupportedEncodingException {
//codificamos cada uno de los valores
if (data.length() > 0) {
data += "&" + URLEncoder.encode(propiedad, "UTF-8") + "=" + URLEncoder.encode(valor, "UTF-8");
} else {
data += URLEncoder.encode(propiedad, "UTF-8") + "=" + URLEncoder.encode(valor, "UTF-8");
}
}
public String getRespueta(String authorization) throws IOException {
String respuesta = "";
//abrimos la conexión
URLConnection conn = url.openConnection();
conn.setRequestProperty("Authorization", authorization);
//especificamos que vamos a escribir
conn.setDoOutput(true);
//obtenemos el flujo de escritura
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//escribimos
wr.write(data);
//cerramos la conexión
wr.close();
//obtenemos el flujo de lectura
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String linea;
//procesamos al salida
while ((linea = rd.readLine()) != null) {
respuesta += linea;
}
return respuesta;
}
}
......@@ -67,3 +67,11 @@ let getClosest = (elem, selector) => {
}
return null
}
//document.querySelector('#logOut').addEventListener('click', (e) => {
// Cookies.clear('Authorization')
// Cookies.clear('menu')
// window.location.href = 'index.jsp'
//})
\ No newline at end of file
......@@ -17,11 +17,9 @@ const Cookies = {
return bool ? arr : arr[0]
},
clear: (key, obj) => {
// b = key
// c = obj {path: '/', domain: '.example.com'}
obj || (obj = {});
obj.expiry = -86400;
this.set(key, "", obj)
clear: (b, c) => {
c || (c = {});
c.expiry = -86400;
Cookies.set(b, "", c)
}
};
\ No newline at end of file
const ajaxRequest = obj => {
return new Promise((resolve, reject) => {
$.ajax({
url: obj.url,
type: obj.type,
dataType: obj.dataType,
headers: {
"Authorization": Cookies.get('Authorization')},
data: obj.body,
beforeSend: (xhr, settings) => {
}, success: (response, textStatus, jqXHR) => {
resolve(response)
}, error: (jqXHR, textStatus, errorThrown) => {
reject({
message: `Error making the request`,
status: jqXHR.status,
request: obj
})
}
})
})
}
const ubigeo = {
consultarDepartamento() {
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDepartamento'
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar departamentos")
}
})
return ajaxRequest({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
body: {
accion: 'listarDepartamento'
}
})
},
consultarProvincia(codigoDepartamento) {
let json = {
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarProvincia',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar provincias")
}
})
return ajaxRequest({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
body: {
accion: 'listarProvincia',
json: JSON.stringify(json)
}
})
},
consultarDistrito(codigoDepartamento, codigoProvincia) {
......@@ -44,23 +50,14 @@ const ubigeo = {
codigoProvincia: codigoProvincia,
codigoDepartamento: codigoDepartamento
}
return new Promise((resolve, reject) => {
$.ajax({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
data: {
accion: 'listarDistrito',
json: JSON.stringify(json)
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar distritos")
}
})
return ajaxRequest({
url: '../UbigeoServlet',
dataType: 'json',
type: 'POST',
body: {
accion: 'listarDistrito',
json: JSON.stringify(json)
}
})
}
}
......@@ -120,4 +117,7 @@ ubigeo
.then(() => {
$('#select_departamento').selectpicker('refresh')
})
.catch(err => {
console.log(err)
})
asignarEventos()
\ No newline at end of file
......@@ -62,7 +62,6 @@ const DOMEvents = {
codigoProyecto: "2",
path: `${location.origin}/${location.pathname.split('/')[1]}/`
}
httpRequest.login(params)
.then(data => {
if (data.status) {
......
......@@ -62,6 +62,8 @@ const ajaxRequest = obj => {
url: obj.url,
type: obj.type,
dataType: obj.dataType,
headers: {
"Authorization": Cookies.get('Authorization')},
data: obj.body,
beforeSend: (xhr, settings) => {
}, success: (response, textStatus, jqXHR) => {
......@@ -89,6 +91,9 @@ const persona = {
url: '../PersonaServlet?accion=listarPersona',
type: 'POST',
dataType: 'json',
headers: {
"Authorization": Cookies.get('Authorization')
},
data: {search: txtCriterioBusqueda}
},
columnDefs: [
......
///* global Cookies */
//((window, Cookies) => {
// console.log(Cookies.get('Authorization'))
// if (Cookies.get('Authorization') === undefined) {
// window.location.href = "index.jsp"
// } else {
// console.log("Estas logueado")
// }
//})(window, Cookies);
......@@ -27,5 +27,4 @@
<script type="text/javascript" src="../plantilla/assets/js/plugins/forms/selects/bootstrap_multiselect.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/app.js"></script>
<script src="../js/lib/cookies.js" type="text/javascript"></script>
<!-- /core JS files -->
\ No newline at end of file
......@@ -11,4 +11,7 @@
<link href="../plantilla/assets/css/core.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/components.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/colors.css" rel="stylesheet" type="text/css">
<!-- /global stylesheets -->
\ No newline at end of file
<!-- /global stylesheets -->
<script src="../js/lib/cookies.js" type="text/javascript"></script>
<script src="../js/pages/validate.js" type="text/javascript"></script>
<!-- Main navbar -->
<div class="navbar navbar-default header-highlight">
<div class="navbar-header">
<a class="navbar-brand" href="index.html"><img src="../plantilla/assets/images/logo_light.png" alt=""></a>
<div class="navbar-header">
<a class="navbar-brand" href="../vistas/main.jsp"><img src="../plantilla/assets/images/logo_light.png" alt=""></a>
<ul class="nav navbar-nav visible-xs-block">
<li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
<li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
</div>
<ul class="nav navbar-nav visible-xs-block">
<li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
<li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
</div>
<div class="navbar-collapse collapse" id="navbar-mobile">
<ul class="nav navbar-nav">
<li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
<div class="navbar-collapse collapse" id="navbar-mobile">
<ul class="nav navbar-nav">
<li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown dropdown-user">
<a class="dropdown-toggle" data-toggle="dropdown">
<img src="../plantilla/assets/images/placeholder.jpg" alt="">
<span>Alonso Moreno Postigo</span>
<i class="caret"></i>
</a>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown dropdown-user">
<a class="dropdown-toggle" data-toggle="dropdown">
<img src="../plantilla/assets/images/placeholder.jpg" alt="">
<span>Alonso Moreno Postigo</span>
<i class="caret"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#"><i class="icon-switch2"></i> Logout</a></li>
</ul>
</li>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#" id="logOut"><i class="icon-switch2"></i> Logout</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
<!-- /main navbar -->
\ No newline at end of file
......@@ -30,7 +30,7 @@
<!-- Main navigation -->
<div class="sidebar-category sidebar-category-visible">
<div class="category-content no-padding">
<ul class="navigation navigation-main navigation-accordion">
<ul class="navigation navigation-main navigation-accordion" id="MENU">
<!-- Main -->
<li class="navigation-header">
<span><i class="icon-menu" title="Main pages"></i> MEN PRINCIPAL</span>
......
Markdown is supported
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