Commit dddd3ba6 by Percy Quispe

ADD conexion entre apps

parent 78ec98cf
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demojsoncrud.servlets;
import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author sistem08user
*/
public class LogOut extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String LOG_OUT = "http://172.16.2.53:8080/security-rest/api/user/logout"; //Cambiar por la URL del servidor de produccion
String auth = request.getHeader("Cookie");
if (auth.contains("Bearer")) {
int indiceBearer = 0;
int indiceToken = 0;
Cookie cookieAuth = new Cookie("Authorization", "");
Cookie cookieMenu = new Cookie("menu", "");
cookieAuth.setMaxAge(0);
cookieMenu.setMaxAge(0);
response.addCookie(cookieAuth);
response.addCookie(cookieMenu);
PostRequest postRequest = new PostRequest(LOG_OUT);
String respuesta = "";
String[] parts = auth.split(";");
for (int i = 0; i < parts.length - 1; i++) {
if (parts[i].contains("Bearer")) {
indiceBearer = i;
break;
}
}
String authorization = parts[indiceBearer];
if (authorization.contains("%20")) {
parts = authorization.split("%20");
} else if (authorization.contains(" ")) {
parts = authorization.split(" ");
}
for (int i = 0; i < parts.length; i++) {
if (parts[i].startsWith("ey")) {//El token empieza
indiceToken = i;
break;
}
}
auth = "Bearer " + parts[indiceToken];
respuesta = postRequest.getRespueta(auth.replaceAll("\"", ""));
request.getRequestDispatcher("/vistas/login.jsp").forward(request, response);
} else {
request.getRequestDispatcher("/vistas/login.jsp").forward(request, response);
}
}
}
...@@ -5,11 +5,11 @@ ...@@ -5,11 +5,11 @@
*/ */
package demojsoncrud.servlets; package demojsoncrud.servlets;
import demojsoncrud.services.PersonaService;
import demojsoncrud.utilities.PostRequest; import demojsoncrud.utilities.PostRequest;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
...@@ -17,37 +17,72 @@ import org.json.JSONObject; ...@@ -17,37 +17,72 @@ import org.json.JSONObject;
/** /**
* *
* @author Percy * @author sistem08user
*/ */
public class RedireccionarServlet extends HttpServlet { public class RedireccionarServlet extends HttpServlet {
@Override @Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
listarPersona(request, response); final String URL = "http://172.16.2.53:8080/security-rest/api/proyecto/enviarNuevoToken";
} String auth = request.getParameter("t");
private void listarPersona(HttpServletRequest request, HttpServletResponse response) { if (auth.contains("Bearer ")) {
final String URL = "http://localhost:8080/security-rest/api/proyecto/enviarNuevoToken"; // int indiceBearer = 0;
response.setContentType("application/json"); // String[] parts = auth.split(";");
PrintWriter pw = null; //
JSONObject salida = new JSONObject(); // for (int i = 0; i < parts.length - 1; i++) {
try { // if (parts[i].contains("Bearer")) {
pw = response.getWriter(); // indiceBearer = i;
String authorization =request.getHeader("Authorization"); // break;
if(authorization!=null && authorization.contains("Bearer ")){ // }
// }
PostRequest sendPost = new PostRequest(URL); // String authorization = parts[indiceBearer];
String respuesta = sendPost.getRespueta(authorization); // parts = authorization.split("%20");
JSONObject obj = new JSONObject(respuesta); // auth = "Bearer " + parts[1];
salida=obj; PostRequest sendPost = new PostRequest(URL);
}else{ String respuesta = sendPost.getRespueta(auth);//Crearia una sesion con el codigo usuario
salida.put("status", false); JSONObject obj = new JSONObject(respuesta);
salida.put("message", "Credenciales incorrectas."); JSONObject menu = new JSONObject(obj.get("menu"));
} Cookie cookieAuth = new Cookie("Authorization", "Bearer "+obj.getString("token"));
} catch (Exception e) { Cookie cookieMenu =new Cookie("menu", menu.toString());
salida.put("status", false); System.out.println("Menu de la cookie ;: "+menu.toString());
salida.put("message", e.getMessage()); cookieAuth.setMaxAge(36000);//10horas
cookieMenu.setMaxAge(36000);//10horas
response.addCookie(cookieAuth);
response.addCookie(cookieMenu);
request.getRequestDispatcher("/vistas/main.jsp").forward(request, response);
} else {
Cookie cookieAuth = new Cookie("Authorization", "");
Cookie cookieMenu = new Cookie("menu", "");
cookieAuth.setMaxAge(0);
cookieMenu.setMaxAge(0);
response.addCookie(cookieAuth);
response.addCookie(cookieMenu);
request.getRequestDispatcher("/vistas/index.jsp").forward(request, response);
} }
pw.print(salida); }
}
private void listarPersona(HttpServletRequest request, HttpServletResponse response) throws ServletException {
// response.setContentType("application/json");
// PrintWriter pw = null;
// JSONObject salida = new JSONObject();
// try {
// pw = response.getWriter();
// String authorization =request.getHeader("Authorization");
// if(authorization!=null && authorization.contains("Bearer ")){
//
// PostRequest sendPost = new PostRequest(URL);
// String respuesta = sendPost.getRespueta(authorization);
// JSONObject obj = new JSONObject(respuesta);
// salida=obj;
// }else{
// salida.put("status", false);
// salida.put("message", "Credenciales incorrectas.");
// }
// } catch (Exception e) {
// salida.put("status", false);
// salida.put("message", e.getMessage());
// }
// pw.print(salida);
}
} }
...@@ -4,6 +4,8 @@ import demojsoncrud.utilities.GeneralUtils; ...@@ -4,6 +4,8 @@ import demojsoncrud.utilities.GeneralUtils;
import demojsoncrud.utilities.PostRequest; import demojsoncrud.utilities.PostRequest;
import demojsoncrud.utilities.VistasExtras; import demojsoncrud.utilities.VistasExtras;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import javax.servlet.Filter; import javax.servlet.Filter;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
...@@ -14,6 +16,7 @@ import javax.servlet.ServletException; ...@@ -14,6 +16,7 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException; import javax.ws.rs.WebApplicationException;
...@@ -61,8 +64,10 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -61,8 +64,10 @@ public class RequestFilter implements Filter, ServletContextListener {
System.out.println(js); System.out.println(js);
String url = String.valueOf(request.getRequestURL()); String url = String.valueOf(request.getRequestURL());
System.out.println("URI _"+request.getRequestURI()); System.out.println("URI _"+request.getRequestURI());
if (url.equalsIgnoreCase(BASE) || url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains(css)|| url.contains("index.jsp")||url.contains("main.jsp") System.out.println("URL _ "+url);
|| url.contains("RedireccionarServlet")||url.contains("cargando.jsp")) { /*Colocar sus recursos*/
if (url.equalsIgnoreCase(BASE) || url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains(css)|| url.contains("index.jsp")//||url.contains("main.jsp")
||url.contains(".png")||url.contains(".jpg")|| url.contains("RedireccionarServlet")||url.contains("vistas/logout")) {
chain.doFilter(request, response); chain.doFilter(request, response);
} else { } else {
PostRequest postRequest = new PostRequest(urlRequested); PostRequest postRequest = new PostRequest(urlRequested);
...@@ -73,6 +78,7 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -73,6 +78,7 @@ public class RequestFilter implements Filter, ServletContextListener {
if(auth!=null){ if(auth!=null){
if(auth.contains("Bearer")){ if(auth.contains("Bearer")){
int indiceBearer = 0; int indiceBearer = 0;
int indiceToken = 0;
String[] parts = auth.split(";"); String[] parts = auth.split(";");
for (int i = 0; i < parts.length-1; i++) { for (int i = 0; i < parts.length-1; i++) {
...@@ -82,8 +88,18 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -82,8 +88,18 @@ public class RequestFilter implements Filter, ServletContextListener {
} }
} }
String authorization = parts[indiceBearer]; String authorization = parts[indiceBearer];
parts = authorization.split("%20"); if(authorization.contains("%20")){
auth = "Bearer "+parts[1]; parts = authorization.split("%20");
}else if(authorization.contains(" ")){
parts = authorization.split(" ");
}
for (int i = 0; i < parts.length; i++) {
if(parts[i].startsWith("ey")){//El token empieza
indiceToken=i;
break;
}
}
auth = "Bearer "+parts[indiceToken].replaceAll("\"", "");
System.out.println(auth); System.out.println(auth);
}else{ }else{
setError(response); setError(response);
...@@ -95,36 +111,33 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -95,36 +111,33 @@ public class RequestFilter implements Filter, ServletContextListener {
auth = request.getHeader("Authorization"); auth = request.getHeader("Authorization");
} }
try{ try{
respuesta = postRequest.getRespueta(auth); respuesta = postRequest.getRespueta(auth.replaceAll("\"", ""));
}catch(Exception ex){ }catch(Exception ex){
setError(response); setError(response);
} }
valid = new JSONObject(respuesta); valid = new JSONObject(respuesta);
if (valid.getBoolean("status")) { if (valid.getBoolean("status")) {
List<Object> vistas=new ArrayList<>();
JSONObject menu=new JSONObject(valid.getString("menu"));//Obtiene el menu JSONObject menu=new JSONObject(valid.getString("menu"));//Obtiene el menu
JSONArray views = new JSONArray(menu.get("vistas").toString());//Obtiene las vistas disponibles del usuario System.out.println(menu);
List<Object> vistas=views.toList(); JSONArray menus = menu.getJSONArray("menu");
System.out.println(menus.toString());
for (int i = 0; i < menus.length(); i++) {
JSONObject obj = new JSONObject(menus.get(i).toString());
JSONArray getVistas=new JSONArray(obj.get("vistas").toString());
List<Object> views=getVistas.toList();
HashSet hs = new HashSet();
hs.addAll(views);
vistas.addAll(hs);
}
vistas.add("main.jsp");//Agregando la vista principal
String ruta = request.getRequestURI(); String ruta = request.getRequestURI();
int indice = GeneralUtils.obtenerIndex(ruta); int indice = GeneralUtils.obtenerIndex(ruta);
String rutaJsp = ruta.substring(indice, ruta.length()); String rutaJsp = ruta.substring(indice, ruta.length());
if(url.contains(".jsp")){ if(url.contains(".jsp")){
boolean acceso = false; boolean acceso = addVistas(vistas,rutaJsp);
for(int i= 0;vistas.size()>i;i++){
Object vista = vistas.get(i);
/*Esta condicional solo aplica cuando sí se tiene páginas detalle propias del sistema (que no estan registrados en SEGURIDAD) mas informacion VistasExtras.java */
switch(vista.toString()){//Agrega las vistas detalle
case VistasExtras.MANTENIMIENTO_PERSONA:VistasExtras.getVistasExtrasMantenimientoPersona(vistas); break;
case VistasExtras.OTROS:VistasExtras.getVistasExtrasMantenimientoOtros(vistas);break;//Ejemplo
case VistasExtras.REPORTE_PERSONA:VistasExtras.getVistasExtrasMantenimientoOtros(vistas);break;
}
System.out.println("Vista : "+vista +" rutaJSP : "+rutaJsp);
if(vista.toString().equalsIgnoreCase(rutaJsp)){
acceso=true;
break;
}
}
if(!acceso){ if(!acceso){
setError(response); setError(response);
} }
...@@ -132,14 +145,40 @@ public class RequestFilter implements Filter, ServletContextListener { ...@@ -132,14 +145,40 @@ public class RequestFilter implements Filter, ServletContextListener {
// List<String> views = (List<String>) ; // List<String> views = (List<String>) ;
chain.doFilter(request, response); chain.doFilter(request, response);
} else { } else {
sendError(response); // sendError(response);
/*Borrando credenciales*/
deleteCredenciales(request, response);
request.getRequestDispatcher("/vistas/index.jsp").forward(request, response);
} }
} }
// } else { // } else {
// sendError(response); // sendError(response);
// } // }
} }
private void deleteCredenciales(HttpServletRequest request,HttpServletResponse response){
Cookie cookieAuth=new Cookie("Authorization", "");
Cookie cookieMenu=new Cookie("menu", "");
cookieAuth.setMaxAge(0);
cookieMenu.setMaxAge(0);
response.addCookie(cookieAuth);
response.addCookie(cookieMenu);
}
private boolean addVistas(List<Object> vistas,String rutaJsp){
for(int i= 0;vistas.size()>i;i++){
Object vista = vistas.get(i);
/*Esta condicional solo aplica cuando sí se tiene páginas detalle propias del sistema (que no estan registrados en SEGURIDAD) mas informacion VistasExtras.java */
switch(vista.toString()){//Agrega las vistas detalle
case VistasExtras.MANTENIMIENTO_PERSONA:VistasExtras.getVistasExtrasMantenimientoPersona(vistas); break;
case VistasExtras.OTROS:VistasExtras.getVistasExtrasMantenimientoOtros(vistas);break;//Ejemplo
case VistasExtras.REPORTE_PERSONA:VistasExtras.getVistasExtrasMantenimientoOtros(vistas);break;
}
System.out.println("Vista : "+vista +" rutaJSP : "+rutaJsp);
if(vista.toString().equalsIgnoreCase(rutaJsp)){
return true;
}
}
return false;
}
private void sendError (HttpServletResponse response) throws IOException{ private void sendError (HttpServletResponse response) throws IOException{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.sendError(401); response.sendError(401);
......
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
<servlet-class>demojsoncrud.servlets.UbigeoServlet</servlet-class> <servlet-class>demojsoncrud.servlets.UbigeoServlet</servlet-class>
</servlet> </servlet>
<servlet> <servlet>
<servlet-name>LogOut</servlet-name>
<servlet-class>demojsoncrud.servlets.LogOut</servlet-class>
</servlet>
<servlet>
<servlet-name>RedireccionarServlet</servlet-name> <servlet-name>RedireccionarServlet</servlet-name>
<servlet-class>demojsoncrud.servlets.RedireccionarServlet</servlet-class> <servlet-class>demojsoncrud.servlets.RedireccionarServlet</servlet-class>
</servlet> </servlet>
...@@ -24,8 +28,12 @@ ...@@ -24,8 +28,12 @@
<url-pattern>/UbigeoServlet</url-pattern> <url-pattern>/UbigeoServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<servlet-mapping> <servlet-mapping>
<servlet-name>LogOut</servlet-name>
<url-pattern>/vistas/logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RedireccionarServlet</servlet-name> <servlet-name>RedireccionarServlet</servlet-name>
<url-pattern>/RedireccionarServlet</url-pattern> <url-pattern>/vistas/RedireccionarServlet</url-pattern>
</servlet-mapping> </servlet-mapping>
<session-config> <session-config>
<session-timeout> <session-timeout>
......
...@@ -87,10 +87,20 @@ let getClosest = (elem, selector) => { ...@@ -87,10 +87,20 @@ let getClosest = (elem, selector) => {
let logOut = () =>{ let logOut = () =>{
document.querySelector('#logOut').addEventListener('click', (e) => { document.querySelector('#logOut').addEventListener('click', (e) => {
Cookies.clear("menu"); // Cookies.clear("menu");
Cookies.clear("Authorization"); // Cookies.clear("Authorization");
// debugger;
// let urls = Cookies.get("urls");
// let url ="";
// if(urls!==null && urls !==""){
// url = urls.split(";");
// for(u in url){
// $.removeCookie('Authorization', {domain: url[u], path:'/'});
// }
// }
// location.reload(); // location.reload();
window.location.href = 'index.jsp'
window.location.href = 'http://172.16.2.53:8080/proyecto-estandar/vistas/logout'
}) })
} }
/* vista viene = vista de donde viene sin .jsp /* vista viene = vista de donde viene sin .jsp
...@@ -105,4 +115,4 @@ logOut(); ...@@ -105,4 +115,4 @@ logOut();
// Cookies.clear('Authorization') // Cookies.clear('Authorization')
// Cookies.clear('menu') // Cookies.clear('menu')
// window.location.href = 'index.jsp' // window.location.href = 'index.jsp'
//}) //})
\ No newline at end of file
/*!
* jQuery Cookie Plugin v1.4.0
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
} catch(e) {
return;
}
try {
// If we can't parse the cookie, ignore it, it's unusable.
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return true;
}
return false;
};
}));
...@@ -45,16 +45,17 @@ const httpRequest = { ...@@ -45,16 +45,17 @@ const httpRequest = {
"Authorization": Cookies.get('Authorization') "Authorization": Cookies.get('Authorization')
} }
}) })
},
getNewToken() {
return ajaxRequest({
url: '../RedireccionarServlet',
type: 'POST',
headers: {
"Authorization":"Bearer "+getToken()
}
})
} }
// ,
// getNewToken() {
// return ajaxRequest({
// url: '../RedireccionarServlet',
// type: 'POST',
// headers: {
// "Authorization":"Bearer "+getToken()
// }
// })
// }
} }
// domevents // domevents
...@@ -78,7 +79,8 @@ const DOMEvents = { ...@@ -78,7 +79,8 @@ const DOMEvents = {
// window.localStorage.setItem('Authorization', 'Bearer ' + data.token) // window.localStorage.setItem('Authorization', 'Bearer ' + data.token)
// window.localStorage.setItem('menu', JSON.stringify(data.menu)) // window.localStorage.setItem('menu', JSON.stringify(data.menu))
Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000}) Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
Cookies.set('menu', `${JSON.stringify(data.menu)}`) console.log("mnenu"+data.menu)
localStorage.setItem("menu",JSON.stringify(data.menu))
window.location.href = 'main.jsp' window.location.href = 'main.jsp'
} else { } else {
...@@ -110,32 +112,31 @@ let getToken=()=>{ ...@@ -110,32 +112,31 @@ let getToken=()=>{
} }
return authorization[1]; return authorization[1];
} }
let obtenerToken=()=>{ //let obtenerToken=()=>{
debugger // debugger
let token = getToken(); // let token = getToken();
if(token!==null && token!==""){ // if(token!==null && token!==""){
httpRequest.getNewToken() // httpRequest.getNewToken()
.then(data => { // .then(data => {
if (data.status) { // if (data.status) {
delete data["status"] // delete data["status"]
Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000}) // Cookies.set('Authorization', `Bearer ${data.token}`, {expiry: 36000000})
Cookies.set('menu', `${JSON.stringify(data.menu)}`, {expiry: 36000000}) // Cookies.set('menu', `${JSON.stringify(data.menu)}`, {expiry: 36000000})
console.log("MENU main.js"+data.menu); // console.log("MENU main.js"+data.menu);
window.location.href = 'main.jsp'; // window.location.href = 'main.jsp';
// window.history.replaceState( {} , '', 'main.jsp' ); //// window.history.replaceState( {} , '', 'main.jsp' );
} else { // } else {
alert('No tienes autorización') // alert('No tienes autorización')
} // }
console.log(data) // console.log(data)
}) // })
// .then(()=>{ // // .then(()=>{
// promiseSqrt(); // // promiseSqrt();
// }) // // })
.catch(err => console.log(err)) // .catch(err => console.log(err))
} // }
//
} //}
DOMEvents.init() DOMEvents.init()
//obtenerToken();
\ No newline at end of file
...@@ -44,7 +44,10 @@ let obtenerToken=()=>{ ...@@ -44,7 +44,10 @@ let obtenerToken=()=>{
// .then(()=>{ // .then(()=>{
// promiseSqrt(); // promiseSqrt();
// }) // })
.catch(err => console.log(err)) .catch(err => {
console.log(err)
window.location.href = "index.jsp";
})
} }
......
...@@ -28,16 +28,24 @@ let setProyecto = () => { ...@@ -28,16 +28,24 @@ let setProyecto = () => {
delete data["status"]; delete data["status"];
let html=''; let html='';
let proyectos = data.proyectos; let proyectos = data.proyectos;
let auth =Cookies.get('Authorization');
console.log(proyectos) console.log(proyectos)
let urls='';
for(let i in proyectos){ for(let i in proyectos){
urls += proyectos[i].url+";";
// let url = proyectos[i].url;//produccion // let url = proyectos[i].url;//produccion
let url = 'http://172.16.2.53:8080/proyecto-estandar/';//Pruebas let url = 'http://172.16.2.53:8080/proyecto-estandar/';//Pruebas
html+='<li><a href="'+url+'vistas/cargando.jsp?Authorization='+Cookies.get('Authorization')+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> ' html+='<li><a href="'+url+'vistas/RedireccionarServlet?t='+auth.replace("\"","")+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> '
+ '<i class="glyphicon glyphicon-arrow-right"></i>'+proyectos[i].nombre+'</a></li>'; + '<i class="glyphicon glyphicon-arrow-right"></i>'+proyectos[i].nombre+'</a></li>';
} }
/*Pruebas*/ /*Pruebas*/
let url2 = 'http://172.16.2.53:8080/aplicaciones/';//Pruebas let url2 = 'http://172.16.2.53:8080/aplicaciones/;';//Pruebas
html+='<li><a href="'+url2+'vistas/cargando.jsp?Authorization='+Cookies.get('Authorization')+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> ' let url3 = 'http://172.16.2.53:8080/proyecto-estandar/';
urls +=url2;
urls +=url3;
let url4 = 'http://172.16.2.53:8080/aplicaciones/';//Pruebas
Cookies.set("urls",urls,{expiry: 36000000});
html+='<li><a href="'+url4+'vistas/RedireccionarServlet?t='+auth.replace("\"","")+'" class="redirect" class="deutsch" ><img src="assets/images/flags/de.png" alt=""> '
+ '<i class="glyphicon glyphicon-arrow-right"></i>Test</a></li>'; + '<i class="glyphicon glyphicon-arrow-right"></i>Test</a></li>';
/*Pruebas*/ /*Pruebas*/
document.getElementById("proyectos").innerHTML = html; document.getElementById("proyectos").innerHTML = html;
......
let setMenu = () => { let setMenu = () => {
// let location = window.location;
// let position =getUrl(location.pathname,"/");
// let path = location.pathname.substring(position+1);//obtiene el nombre de la vista jsp para activar la clase .active
// let menu = document.getElementById("MENU");
// let contenido = JSON.parse(Cookies.get('menu'));
// console.log(contenido)
// let titulo = contenido.titulo;
// let modulo = titulo.modulo;
// let html = '<li class="navigation-header"><span><i class="icon-menu" title="Main pages"></i>' + titulo['nombre'] + '</span></li>';
// for (let i in modulo){
// let categoria = modulo[i]['categoria'];
// html+='<li >'
// + '<a href="'+modulo[i]['url']+'">'
// + '<i class="fa '+modulo[i]['ico']+' fa-lg"></i>'
// + '<span>'+modulo[i]['nombre']+'</span>'
// + '</a>';
// for(let j in categoria){
// let idCategoria="";
// if (categoria[j]['url'].length>4){
// let categoriaUrl = categoria[j]['url'].toString();
// idCategoria = categoriaUrl.substr(0,categoriaUrl.length-4);//Quitar el .jsp
// console.log("ID CATEGORIA ;: "+idCategoria);
// }
// let subCategoria = modulo[i]['subCategoria'];
// html+= '<ul>';
// if(path === categoria[j]['url']){
// html+= '<li class="active">';
// }else{
// html+= '<li>';
// }
// if(subCategoria===undefined){
// html+= '<a class="" id="'+idCategoria+'" href="../vistas/'+categoria[j]['url']+'">';
// }else{
// html+= '<a class="" id="'+idCategoria+'" href="'+window.location+categoria[j]['url']+'">';
// }
// html+= '<span>'+categoria[j]['nombre']+'</span>'
// + '</a>';
// if(subCategoria!==undefined){
// for(let k in subCategoria){
// html+='<ul class="hidden-ul" style="display: block;">';
// if(path === subCategoria[k]['url']){
// html+= '<li class="active">';
// }else{
// html+= '<li>';
// }
// html+='<a href="'+subCategoria[k]['url']+'">'+subCategoria[k]['nombre']+'</a></li>'
// +'</ul>';
// }
// }
// html+= '</li>'
// + '</ul>';
// }
// html+='</li>';
// }
let location = window.location; let location = window.location;
let position =getUrl(location.pathname,"/"); let position = getUrl(location.pathname, "/");
let path = location.pathname.substring(position+1);//obtiene el nombre de la vista jsp para activar la clase .active let path = location.pathname.substring(position + 1);//obtiene el nombre de la vista jsp para activar la clase .active
let menu = document.getElementById("MENU"); let menu = document.getElementById("MENU");
let contenido = JSON.parse(Cookies.get('menu')); let contenido = JSON.parse(JSON.parse(localStorage.getItem("menu")));
let html = "";
let active = "";
console.log(contenido) console.log(contenido)
let titulo = contenido.titulo; let menus = contenido.menu;
let modulo = titulo.modulo; /* Recorrer titulos */
let html = '<li class="navigation-header"><span><i class="icon-menu" title="Main pages"></i>' + titulo['nombre'] + '</span></li>'; // for (var i in menus) {
for (let i in modulo){ let titulo = menus[0].titulo;
let categoria = modulo[i]['categoria'];
html+='<li >' html += `<li class="navigation-header"><span><i class="${titulo.ico}" title="Main pages"></i>${titulo.nombre}</span></li>`;
+ '<a href="'+modulo[i]['url']+'">' let modulo = titulo.modulo;
+ '<i class="fa '+modulo[i]['ico']+' fa-lg"></i>' for (let i in modulo){
+ '<span>'+modulo[i]['nombre']+'</span>' let categoria = modulo[i]['categoria'];
+ '</a>'; html+='<li >'
for(let j in categoria){ + '<a href="'+modulo[i]['url']+'">'
let idCategoria=""; + '<i class="fa '+modulo[i]['ico']+' fa-lg"></i>'
if (categoria[j]['url'].length>4){ + '<span>'+modulo[i]['nombre']+'</span>'
let categoriaUrl = categoria[j]['url'].toString(); + '</a>';
idCategoria = categoriaUrl.substr(0,categoriaUrl.length-4);//Quitar el .jsp for(let j in categoria){
console.log("ID CATEGORIA ;: "+idCategoria); let idCategoria="";
} if (categoria[j]['url'].length>4){
let subCategoria = modulo[i]['subCategoria']; let categoriaUrl = categoria[j]['url'].toString();
html+= '<ul>'; idCategoria = categoriaUrl.substr(0,categoriaUrl.length-4);//Quitar el .jsp
if(path === categoria[j]['url']){ console.log("ID CATEGORIA ;: "+idCategoria);
html+= '<li class="active">'; }
}else{ let subCategoria = modulo[i]['subCategoria'];
html+= '<li>'; html+= '<ul>';
} if(path === categoria[j]['url']){
if(subCategoria===undefined){ html+= '<li class="active">';
html+= '<a class="" id="'+idCategoria+'" href="../vistas/'+categoria[j]['url']+'">'; }else{
}else{ html+= '<li>';
html+= '<a class="" id="'+idCategoria+'" href="'+window.location+categoria[j]['url']+'">'; }
} if(subCategoria===undefined){
html+= '<span>'+categoria[j]['nombre']+'</span>' html+= '<a class="" id="'+idCategoria+'" href="../vistas/'+categoria[j]['url']+'">';
+ '</a>'; }else{
if(subCategoria!==undefined){ html+= '<a class="" id="'+idCategoria+'" href="'+window.location+categoria[j]['url']+'">';
for(let k in subCategoria){ }
html+='<ul class="hidden-ul" style="display: block;">'; html+= '<span>'+categoria[j]['nombre']+'</span>'
if(path === subCategoria[k]['url']){ + '</a>';
html+= '<li class="active">'; if(subCategoria!==undefined){
}else{ for(let k in subCategoria){
html+= '<li>'; html+='<ul class="hidden-ul" style="display: block;">';
if(path === subCategoria[k]['url']){
html+= '<li class="active">';
}else{
html+= '<li>';
}
html+='<a href="'+subCategoria[k]['url']+'">'+subCategoria[k]['nombre']+'</a></li>'
+'</ul>';
} }
html+='<a href="'+subCategoria[k]['url']+'">'+subCategoria[k]['nombre']+'</a></li>'
+'</ul>';
} }
html+= '</li>'
+ '</ul>';
} }
html+= '</li>' html+='</li>';
+ '</ul>'; }
} // }
html+='</li>';
}
menu.innerHTML=html; menu.innerHTML=html;
} }
let getUrl = (pathname,caracter) => { let getUrl = (pathname,caracter) => {
......
let url = "";
let p = window.location.href;
let slash = 0;
let pos = 0;
for(let i=0 ; p.length>i;i++){
if(p[i] ==="/"){
slash++;
}
if(slash===4){
pos=i;
break;
}
}
url = p.substring(0, pos)
window.location.href = "http://172.16.2.53:8080/servercookie/validar.jsp?p="+url+"&t="+Cookies.get('Authorization');
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
<!-- Core JS files --> <!-- Core JS files -->
<script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/pace.min.js"></script> <script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/pace.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/libraries/jquery.min.js"></script> <script type="text/javascript" src="../plantilla/assets/js/core/libraries/jquery.min.js"></script>
<script src="../js/lib/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript" src="../plantilla/assets/js/core/libraries/bootstrap.min.js"></script> <script type="text/javascript" src="../plantilla/assets/js/core/libraries/bootstrap.min.js"></script>
<script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/blockui.min.js"></script> <script type="text/javascript" src="../plantilla/assets/js/plugins/loaders/blockui.min.js"></script>
......
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