Commit 06ad5dfb by Alonso Moreno

Implementacion WebFilter y autenticacion

parent c46daa5a
package demojsoncrud.servlets; package demojsoncrud.servlets;
import demojsoncrud.utilities.PostRequest;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter; import javax.servlet.Filter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.FilterConfig; import javax.servlet.FilterConfig;
...@@ -12,6 +14,7 @@ import javax.servlet.ServletResponse; ...@@ -12,6 +14,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
@WebFilter("/*") @WebFilter("/*")
public class RequestFilter implements Filter, ServletContextListener { public class RequestFilter implements Filter, ServletContextListener {
...@@ -23,20 +26,67 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -23,20 +26,67 @@ public class RequestFilter implements Filter, ServletContextListener {
@Override @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
System.out.println("Filter");
HttpServletRequest request = (HttpServletRequest) req; HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res; 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"; if (String.valueOf(request.getRequestURL()).contains("http://localhost:8080/proyecto-estandar/")) {
String assets = request.getContextPath() + "/plantilla/assets"; String login = request.getContextPath() + "/vistas/index.jsp";
String css = request.getContextPath() + "/plantilla/css"; String main = request.getContextPath() + "/vistas/main.jsp";
String js = request.getContextPath() + "/plantilla/js"; String plantilla = request.getContextPath() + "/plantilla";
String js = request.getContextPath() + "/js";
chain.doFilter(request, response); 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 @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) => { ...@@ -67,3 +67,11 @@ let getClosest = (elem, selector) => {
} }
return null 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 = { ...@@ -17,11 +17,9 @@ const Cookies = {
return bool ? arr : arr[0] return bool ? arr : arr[0]
}, },
clear: (key, obj) => { clear: (b, c) => {
// b = key c || (c = {});
// c = obj {path: '/', domain: '.example.com'} c.expiry = -86400;
obj || (obj = {}); Cookies.set(b, "", c)
obj.expiry = -86400;
this.set(key, "", obj)
} }
}; };
\ 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 = { const ubigeo = {
consultarDepartamento() { consultarDepartamento() {
return new Promise((resolve, reject) => { return ajaxRequest({
$.ajax({ url: '../UbigeoServlet',
url: '../UbigeoServlet', dataType: 'json',
dataType: 'json', type: 'POST',
type: 'POST', body: {
data: { accion: 'listarDepartamento'
accion: 'listarDepartamento' }
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar departamentos")
}
})
}) })
}, },
consultarProvincia(codigoDepartamento) { consultarProvincia(codigoDepartamento) {
let json = { let json = {
codigoDepartamento: codigoDepartamento codigoDepartamento: codigoDepartamento
} }
return new Promise((resolve, reject) => { return ajaxRequest({
$.ajax({ url: '../UbigeoServlet',
url: '../UbigeoServlet', dataType: 'json',
dataType: 'json', type: 'POST',
type: 'POST', body: {
data: { accion: 'listarProvincia',
accion: 'listarProvincia', json: JSON.stringify(json)
json: JSON.stringify(json) }
}, beforeSend: function (xhr) {
}, success: function (data, textStatus, jqXHR) {
resolve(data)
}, error: function (jqXHR, textStatus, errorThrown) {
reject("Error al listar provincias")
}
})
}) })
}, },
consultarDistrito(codigoDepartamento, codigoProvincia) { consultarDistrito(codigoDepartamento, codigoProvincia) {
...@@ -44,23 +50,14 @@ const ubigeo = { ...@@ -44,23 +50,14 @@ const ubigeo = {
codigoProvincia: codigoProvincia, codigoProvincia: codigoProvincia,
codigoDepartamento: codigoDepartamento codigoDepartamento: codigoDepartamento
} }
return ajaxRequest({
return new Promise((resolve, reject) => { url: '../UbigeoServlet',
$.ajax({ dataType: 'json',
url: '../UbigeoServlet', type: 'POST',
dataType: 'json', body: {
type: 'POST', accion: 'listarDistrito',
data: { json: JSON.stringify(json)
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")
}
})
}) })
} }
} }
...@@ -120,4 +117,7 @@ ubigeo ...@@ -120,4 +117,7 @@ ubigeo
.then(() => { .then(() => {
$('#select_departamento').selectpicker('refresh') $('#select_departamento').selectpicker('refresh')
}) })
.catch(err => {
console.log(err)
})
asignarEventos() asignarEventos()
\ No newline at end of file
...@@ -62,7 +62,6 @@ const DOMEvents = { ...@@ -62,7 +62,6 @@ const DOMEvents = {
codigoProyecto: "2", codigoProyecto: "2",
path: `${location.origin}/${location.pathname.split('/')[1]}/` path: `${location.origin}/${location.pathname.split('/')[1]}/`
} }
httpRequest.login(params) httpRequest.login(params)
.then(data => { .then(data => {
if (data.status) { if (data.status) {
......
...@@ -62,6 +62,8 @@ const ajaxRequest = obj => { ...@@ -62,6 +62,8 @@ const ajaxRequest = obj => {
url: obj.url, url: obj.url,
type: obj.type, type: obj.type,
dataType: obj.dataType, dataType: obj.dataType,
headers: {
"Authorization": Cookies.get('Authorization')},
data: obj.body, data: obj.body,
beforeSend: (xhr, settings) => { beforeSend: (xhr, settings) => {
}, success: (response, textStatus, jqXHR) => { }, success: (response, textStatus, jqXHR) => {
...@@ -89,6 +91,9 @@ const persona = { ...@@ -89,6 +91,9 @@ const persona = {
url: '../PersonaServlet?accion=listarPersona', url: '../PersonaServlet?accion=listarPersona',
type: 'POST', type: 'POST',
dataType: 'json', dataType: 'json',
headers: {
"Authorization": Cookies.get('Authorization')
},
data: {search: txtCriterioBusqueda} data: {search: txtCriterioBusqueda}
}, },
columnDefs: [ 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 @@ ...@@ -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/plugins/forms/selects/bootstrap_multiselect.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/app.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 --> <!-- /core JS files -->
\ No newline at end of file
...@@ -11,4 +11,7 @@ ...@@ -11,4 +11,7 @@
<link href="../plantilla/assets/css/core.css" rel="stylesheet" type="text/css"> <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/components.css" rel="stylesheet" type="text/css">
<link href="../plantilla/assets/css/colors.css" rel="stylesheet" type="text/css"> <link href="../plantilla/assets/css/colors.css" rel="stylesheet" type="text/css">
<!-- /global stylesheets --> <!-- /global stylesheets -->
\ No newline at end of file <script src="../js/lib/cookies.js" type="text/javascript"></script>
<script src="../js/pages/validate.js" type="text/javascript"></script>
<!-- Main navbar --> <!-- Main navbar -->
<div class="navbar navbar-default header-highlight"> <div class="navbar navbar-default header-highlight">
<div class="navbar-header"> <div class="navbar-header">
<a class="navbar-brand" href="index.html"><img src="../plantilla/assets/images/logo_light.png" alt=""></a> <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"> <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 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> <li><a class="sidebar-mobile-main-toggle"><i class="icon-paragraph-justify3"></i></a></li>
</ul> </ul>
</div> </div>
<div class="navbar-collapse collapse" id="navbar-mobile"> <div class="navbar-collapse collapse" id="navbar-mobile">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">
<li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li> <li><a class="sidebar-control sidebar-main-toggle hidden-xs"><i class="icon-paragraph-justify3"></i></a></li>
</ul> </ul>
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li class="dropdown dropdown-user"> <li class="dropdown dropdown-user">
<a class="dropdown-toggle" data-toggle="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown">
<img src="../plantilla/assets/images/placeholder.jpg" alt=""> <img src="../plantilla/assets/images/placeholder.jpg" alt="">
<span>Alonso Moreno Postigo</span> <span>Alonso Moreno Postigo</span>
<i class="caret"></i> <i class="caret"></i>
</a> </a>
<ul class="dropdown-menu dropdown-menu-right"> <ul class="dropdown-menu dropdown-menu-right">
<li><a href="#"><i class="icon-switch2"></i> Logout</a></li> <li><a href="#" id="logOut"><i class="icon-switch2"></i> Logout</a></li>
</ul>
</li>
</ul> </ul>
</div> </li>
</ul>
</div>
</div> </div>
<!-- /main navbar --> <!-- /main navbar -->
\ No newline at end of file
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
<!-- Main navigation --> <!-- Main navigation -->
<div class="sidebar-category sidebar-category-visible"> <div class="sidebar-category sidebar-category-visible">
<div class="category-content no-padding"> <div class="category-content no-padding">
<ul class="navigation navigation-main navigation-accordion"> <ul class="navigation navigation-main navigation-accordion" id="MENU">
<!-- Main --> <!-- Main -->
<li class="navigation-header"> <li class="navigation-header">
<span><i class="icon-menu" title="Main pages"></i> MEN PRINCIPAL</span> <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