diff --git a/nb-configuration.xml b/nb-configuration.xml index ed22016..8731a78 100644 --- a/nb-configuration.xml +++ b/nb-configuration.xml @@ -16,5 +16,6 @@ Any value defined here will override the pom.xml file value but is only applicab 1.7-web gfv3ee6 ide + true diff --git a/pom.xml b/pom.xml index 75b6874..c8b00e5 100644 --- a/pom.xml +++ b/pom.xml @@ -41,6 +41,7 @@ 5.1.41 jar + org.bitbucket.b_c jose4j @@ -48,6 +49,7 @@ jar + org.codehaus.jettison jettison @@ -68,17 +70,32 @@ jersey-json 1.8 + com.google.code.gson gson 2.2.4 jar + + + org.hibernate + hibernate-core + 5.0.12.Final + jar + + + + org.hibernate.common + hibernate-commons-annotations + 5.0.3.Final + + javax javaee-web-api 7.0 - provided + jar @@ -86,16 +103,19 @@ jaxb-impl 2.0.1 + com.fasterxml.jackson.core jackson-core 2.9.5 + com.fasterxml.jackson.core jackson-databind 2.9.5 + com.wordnik swagger-jersey-jaxrs_2.10 @@ -107,6 +127,7 @@ + diff --git a/src/hibernate.cfg.xml b/src/hibernate.cfg.xml new file mode 100644 index 0000000..5be655f --- /dev/null +++ b/src/hibernate.cfg.xml @@ -0,0 +1,52 @@ + + + + + + org.hibernate.dialect.MySQLDialect + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/mydb?zeroDateTimeBehavior=convertToNull + valdr + nomad123 + + + + diff --git a/src/main/java/xyz/somch/db/ConexionBD.java b/src/main/java/xyz/somch/db/ConexionBD.java index 8fd7be2..f5f46c0 100644 --- a/src/main/java/xyz/somch/db/ConexionBD.java +++ b/src/main/java/xyz/somch/db/ConexionBD.java @@ -5,23 +5,19 @@ */ package xyz.somch.db; - -import java.sql.SQLException; -import java.sql.Connection; -import java.sql.DriverManager; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; /** * * @author dark_ */ public class ConexionBD { - public static Connection crearConexion() throws SQLException, ClassNotFoundException { - Class.forName("com.mysql.jdbc.Driver"); - Connection conexion; - conexion = DriverManager.getConnection(ConstantesBD.dbUrl, ConstantesBD.dbUser, ConstantesBD.dbPwd); - return conexion; + public static SessionFactory crearConexion() { + SessionFactory factory = new Configuration().configure().buildSessionFactory(); + return factory; } - public static void destruirConexion(Connection conexion) throws SQLException { - conexion.close(); + public static void destruirConexion(SessionFactory factory){ + factory.close(); } } diff --git a/src/main/java/xyz/somch/filtro/FiltroAutorizacion.java b/src/main/java/xyz/somch/filtro/FiltroAutorizacion.java index 2a7560b..2083b8b 100644 --- a/src/main/java/xyz/somch/filtro/FiltroAutorizacion.java +++ b/src/main/java/xyz/somch/filtro/FiltroAutorizacion.java @@ -11,10 +11,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Date; -import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; @@ -25,7 +23,6 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; -import static javax.ws.rs.core.Response.Status.FOUND; import static javax.ws.rs.core.Response.Status.OK; import org.jose4j.jwt.consumer.InvalidJwtException; import org.jose4j.lang.JoseException; @@ -80,7 +77,7 @@ public void filter(ContainerRequestContext requestContext) throws IOException { String id = getClaimsJwtToken(jwt); User userLogin = usuario.findByID(id).get(0); String password = userLogin.getPassword(); - if (!usuario.getSesion(userLogin)) { + if (!userLogin.getSesion()) { requestContext.abortWith(ConstructorResponse.createResponse(Response.Status.UNAUTHORIZED, ACCESS_NO_SESSION)); return; } @@ -102,10 +99,10 @@ public void filter(ContainerRequestContext requestContext) throws IOException { usuario = new UserBD(); String id = (String) ex.getJwtContext().getJwtClaims().getClaimValue("id"); User user = usuario.findByID(id).get(0); - if (usuario.getSesion(usuario.findByID(id).get(0)) && ex.hasExpired()) { + if (user.getSesion() && ex.hasExpired()) { try { String jwt = ex.getJwtContext().getJwt(); - if (usuario.getToken(user).equals(jwt)) { + if (user.getToken().equals(jwt)) { jwt = TokenSecurity.refreshJwtToken(user); user.setToken(jwt); user.setRefreshToken((new SimpleDateFormat("HHmmssddMMyyyy")).format((new Date()))); @@ -128,9 +125,9 @@ public void filter(ContainerRequestContext requestContext) throws IOException { } } - private boolean isUserAllowed(final String userRole, final Set rolesSet) { + private boolean isUserAllowed(final List userRole, final Set rolesSet) { boolean isAllowed = false; - if (rolesSet.contains(userRole)) { + if (rolesSet.contains(userRole.get(0))) { isAllowed = true; } return isAllowed; diff --git a/src/main/java/xyz/somch/hibernate/HibernateUtil.java b/src/main/java/xyz/somch/hibernate/HibernateUtil.java new file mode 100644 index 0000000..1b95ea4 --- /dev/null +++ b/src/main/java/xyz/somch/hibernate/HibernateUtil.java @@ -0,0 +1,32 @@ +/* + * 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 xyz.somch.hibernate; + +import org.hibernate.HibernateException; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +/** + * + * @author dark_ + */ +public class HibernateUtil { + private static final SessionFactory sessionFactory; + static{ + try{ + sessionFactory = new Configuration().configure().buildSessionFactory(); + } + catch (HibernateException he){ + System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he); + throw new ExceptionInInitializerError(he); + } + } + + public static SessionFactory getSessionFactory() + { + return sessionFactory; + } + +} diff --git a/src/main/java/xyz/somch/model/Rol.java b/src/main/java/xyz/somch/model/Rol.java new file mode 100644 index 0000000..48d80ea --- /dev/null +++ b/src/main/java/xyz/somch/model/Rol.java @@ -0,0 +1,46 @@ +/* + * 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 xyz.somch.model; + +import javax.persistence.*; + +/** + * + * @author dark_ + */ + +@Entity +@Table(name = "ROL") +public class Rol { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "ID_ROL") + private int id; + @Column(name = "NOMBRE") + private String nombre; + + public Rol(){} + public Rol(String nombre){ + this.id = 1; + this.nombre = "User"; + } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + +} diff --git a/src/main/java/xyz/somch/model/User.java b/src/main/java/xyz/somch/model/User.java index 8b36616..09b3021 100644 --- a/src/main/java/xyz/somch/model/User.java +++ b/src/main/java/xyz/somch/model/User.java @@ -5,27 +5,43 @@ */ package xyz.somch.model; - - - +import java.io.Serializable; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import xyz.somch.utilidades.JsonSerializable; +import javax.persistence.*; /** * * @author dark_ */ -public class User implements JsonSerializable{ +@Entity +@Table(name = "USUARIO") +public class User implements JsonSerializable, Serializable { + + @Id + @GeneratedValue + @Column(name = "ID_USUARIO") private String id; + @Column(name = "NOMBRE") private String nombre; + @Column(name = "PASSWORD") private String password; - private List rol; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private List rol = new ArrayList(); + @Column(name = "TOKEN") private String token; + @Column(name = "SESION") + private Boolean sesion; + @Column(name = "REFRESHTOKEN") private String refreshToken; + public User() { + } + public String getRefreshToken() { return refreshToken; } @@ -66,25 +82,37 @@ public void setPassword(String password) { this.password = password; } - public List getRol() { + public List getRol() { return rol; } - public void setRol(List rol) { + public Boolean getSesion() { + return sesion; + } + + public void setSesion(Boolean sesion) { + this.sesion = sesion; + } + + public void setRol(List rol) { this.rol = rol; } - - public void setUIID(){ + + public void addRol(Rol rol) { + this.rol.add(rol); + } + + public void setUIID() { id = UUID.randomUUID().toString().replace("-", ""); } - + @Override - public String toString(){ + public String toString() { return "id: " + id + " nombre: " + nombre + " password: " + password; } @Override - public JSONObject toJson() throws JSONException{ + public JSONObject toJson() throws JSONException { JSONObject json = new JSONObject(); json.put("id", getId()); json.put("nombre", getNombre()); @@ -93,5 +121,5 @@ public JSONObject toJson() throws JSONException{ return json; } - + } diff --git a/src/main/java/xyz/somch/model/UserBD.java b/src/main/java/xyz/somch/model/UserBD.java index 057eed1..390e995 100644 --- a/src/main/java/xyz/somch/model/UserBD.java +++ b/src/main/java/xyz/somch/model/UserBD.java @@ -5,12 +5,10 @@ */ package xyz.somch.model; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.Transaction; import xyz.somch.db.ConexionBD; /** @@ -18,18 +16,17 @@ * @author dark_ */ public class UserBD implements UserDAO { - final String tableUserBD = "USUARIO"; - final String tableRolBD = "ROL"; - final String idUserBD = "ID_USUARIO"; - final String nombreBD = "NOMBRE"; - final String passwordBD = "PASSWORD"; - final String idRolBD = "ID_ROL"; - final String sesionBD = "SESION"; - final String tokenBD = "TOKEN"; - final String refreshTokenBD = "REFRESHTOKEN"; + @Override public List findByID(String id) { - try { + Session sesion = ConexionBD.crearConexion().openSession(); + Transaction tx = sesion.beginTransaction(); + String hql = "FROM User user WHERE user.id = " + id; + Query query = sesion.createQuery(hql); + tx.commit(); + sesion.close(); + return query.list(); + /*try { List usuarios = new ArrayList(); User usuario = new User(); Connection conexion = ConexionBD.crearConexion(); @@ -38,23 +35,31 @@ public List findByID(String id) { stmt.setString(1, id); ResultSet rs = stmt.executeQuery(); if (rs.next()) { - usuario.setId(rs.getString(idUserBD)); - usuario.setNombre(rs.getString(nombreBD)); - usuario.setPassword(rs.getString(passwordBD)); - usuario.setToken(rs.getString(tokenBD)); - usuario.setRefreshToken(refreshTokenBD); - usuarios.add(usuario); + usuario.setId(rs.getString(idUserBD)); + usuario.setNombre(rs.getString(nombreBD)); + usuario.setPassword(rs.getString(passwordBD)); + usuario.setToken(rs.getString(tokenBD)); + usuario.setRefreshToken(refreshTokenBD); + usuarios.add(usuario); } return usuarios; - } catch (SQLException | ClassNotFoundException ex) { + } catch (SQLException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); - } - return null; + } + return null;*/ } @Override public List findByNombre(String nombre) { - try { + + Session sesion = ConexionBD.crearConexion().openSession(); + Transaction tx = sesion.beginTransaction(); + String hql = "FROM User user WHERE user.nombre = " + nombre; + Query query = sesion.createQuery(hql); + tx.commit(); + sesion.close(); + return query.list(); + /*try { List usuarios = new ArrayList(); Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; @@ -73,12 +78,19 @@ public List findByNombre(String nombre) { } catch (SQLException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); } - return null; + return null;*/ } @Override public List findAll() { - try { + Session sesion = ConexionBD.crearConexion().openSession(); + Transaction tx = sesion.beginTransaction(); + String hql = "FROM User"; + Query query = sesion.createQuery(hql); + tx.commit(); + sesion.close(); + return query.list(); + /*try { List usuarios = new ArrayList(); Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; @@ -95,12 +107,19 @@ public List findAll() { } catch (SQLException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); } - return null; + return null;*/ } @Override public boolean insertarUsuario(User user) { - try { + Session sesion = ConexionBD.crearConexion().openSession(); + Transaction tx = sesion.beginTransaction(); + user.addRol(new Rol("User")); + sesion.save(user); + tx.commit(); + sesion.close(); + return true; + /*try { Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; stmt = conexion.prepareStatement("INSERT INTO usuario(id,"+ nombreBD+","+passwordBD+") VALUES (?,?,?,?);"); @@ -112,10 +131,25 @@ public boolean insertarUsuario(User user) { } catch (SQLException | ClassNotFoundException ex) { System.out.println(ex.getMessage()); } - return false; + return false;*/ } + /* public boolean setSesion(User user, Boolean sesion) { + Session session = HibernateUtil.getSessionFactory().openSession(); + Transaction tx = session.beginTransaction(); + String hql = "UPDATE User set sesion = :sesion WHERE id = :id_usuario"; + Query query = session.createQuery(hql); + query.setParameter("sesion", sesion); + query.setParameter("id_usuario", user.getId()); + int res = query.executeUpdate(); + if(res==0){ + session.close(); + return false; + }else{ + session.close(); + return true; + } try { Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; @@ -128,24 +162,8 @@ public boolean setSesion(User user, Boolean sesion) { System.out.println(ex.getMessage()); } return false; - } - - public boolean getSesion(User user) { - try { - Connection conexion = ConexionBD.crearConexion(); - PreparedStatement stmt; - stmt = conexion.prepareStatement("SELECT sesion FROM usuario WHERE id=?;"); - stmt.setString(1, user.getId()); - ResultSet rs = stmt.executeQuery(); - if (rs.next()) { - return rs.getBoolean("sesion"); - } - } catch (SQLException | ClassNotFoundException ex) { - System.out.println(ex.getMessage()); - } - return false; - } - + } + public boolean setToken(User user) { try { Connection conexion = ConexionBD.crearConexion(); @@ -207,11 +225,19 @@ public String getRefreshToken(User user) { System.out.println(ex.getMessage()); } return null; - } + }*/ @Override public boolean actualizarUsuario(User oldUser, User newUser) { - try { + Session sesion = ConexionBD.crearConexion().openSession(); + Transaction tx = sesion.beginTransaction(); + sesion.update(newUser); + tx.commit(); + sesion.close(); + return true; + } + + /*try { Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; @@ -229,11 +255,19 @@ public boolean actualizarUsuario(User oldUser, User newUser) { System.out.println(ex.getMessage()); } return false; - } + }*/ @Override public boolean eliminarUsuario(User user) { - try { + Session sesion = ConexionBD.crearConexion().openSession(); + User u = (User) sesion.get(User.class, user.getId()); + Transaction tx = sesion.beginTransaction(); + sesion.delete(u); + tx.commit(); + sesion.close(); + return true; + } + /*try { Connection conexion = ConexionBD.crearConexion(); PreparedStatement stmt; stmt = conexion.prepareStatement("DELETE FROM usuario WHERE id=? AND nombre=? AND password=? AND rol=?;"); @@ -247,6 +281,6 @@ public boolean eliminarUsuario(User user) { System.out.println(ex.getMessage()); } return false; - } + }*/ } diff --git a/src/main/java/xyz/somch/prototiporestjava/LoginREST.java b/src/main/java/xyz/somch/prototiporestjava/LoginREST.java index f667c5f..375c78e 100644 --- a/src/main/java/xyz/somch/prototiporestjava/LoginREST.java +++ b/src/main/java/xyz/somch/prototiporestjava/LoginREST.java @@ -57,8 +57,8 @@ public Response autenticarUsuario(User user) { user = controlador.findByNombre(user.getNombre()).get(0); String token = generarJwt(user); user.setToken(token); + user.setSesion(true); if (controlador.actualizarUsuario(user, user)) { - controlador.setSesion(user, true); Response response = ConstructorResponse.createResponse(Response.Status.FOUND, "sesion iniciada con exito"); return Response.status(FOUND).header(AUTHORIZATION_PROPERTY,token).entity(response.getEntity()).build(); } else { @@ -95,7 +95,6 @@ public Response obtenerUsuarios() { @Produces("application/json") public Response registrarUsuario(User usuario) { try { - usuario.setRol("user"); usuario.setUIID(); UserBD controlador = new UserBD(); if (controlador.insertarUsuario(usuario)) { @@ -136,7 +135,7 @@ public Response cerrarSesion(User usuario) { System.out.println("Cerrar sesion"); UserBD controlador = new UserBD(); usuario = controlador.findByNombre(usuario.getNombre()).get(0); - controlador.setSesion(usuario, false); + usuario.setSesion(false); usuario.setToken(""); usuario.setRefreshToken(""); if (controlador.actualizarUsuario(usuario, usuario)) { diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml new file mode 100644 index 0000000..5be655f --- /dev/null +++ b/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,52 @@ + + + + + + org.hibernate.dialect.MySQLDialect + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/mydb?zeroDateTimeBehavior=convertToNull + valdr + nomad123 + + + +