Advertisement
Guest User

webo

a guest
Jan 7th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.09 KB | None | 0 0
  1. package api;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4. import java.security.Key;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.text.SimpleDateFormat;
  10. import java.time.LocalDate;
  11. import java.util.Date;
  12.  
  13. import javax.ws.rs.Consumes;
  14. import javax.ws.rs.FormParam;
  15. import javax.ws.rs.POST;
  16. import javax.ws.rs.Path;
  17. import javax.ws.rs.Produces;
  18. import javax.ws.rs.core.MediaType;
  19. import javax.ws.rs.core.Response;
  20.  
  21. import com.auth0.jwt.JWT;
  22. import com.auth0.jwt.JWTVerifier;
  23. import com.auth0.jwt.algorithms.Algorithm;
  24. import com.auth0.jwt.interfaces.DecodedJWT;
  25. import com.google.gson.Gson;
  26.  
  27. import io.jsonwebtoken.Jwts;
  28. import io.jsonwebtoken.SignatureAlgorithm;
  29. import io.jsonwebtoken.impl.crypto.MacProvider;
  30. import modelos.Constants;
  31. import modelos.User;
  32.  
  33. @Path("/login")
  34. public class Authentication {
  35.  
  36.     // private final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
  37.     // private final static String JDBC_CONNECTION_STRING =
  38.     // "jdbc:mysql://localhost:3306/campus_aula?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
  39.     // private final static String JDBC_CONNECTION_USER = "AD";
  40.     // private final static String JDBC_CONNECTION_PASS = "AccesoADatos";
  41.  
  42.     private final static String AUTHENTICATION_SCHEME = "bearer";
  43.  
  44.     @POST
  45.     @Produces(MediaType.APPLICATION_JSON)
  46.     @Consumes(MediaType.APPLICATION_JSON)
  47.     public Response autenticarUsuario(String json) {
  48.  
  49.         Gson gson = new Gson();
  50.         User user1 = gson.fromJson(json, User.class);
  51.         String token = null;// = generateToken(username);
  52.         String tokenBD = null;
  53.  
  54.         User user2 = null;
  55.         boolean actu = false;
  56.         boolean userValidated = false;
  57.         try {
  58.  
  59.             Class.forName(Constants.JDBC_DRIVER);
  60.             Connection con = DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
  61.                     Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
  62.  
  63.             PreparedStatement p = con.prepareStatement("SELECT usuario FROM usuarios WHERE usuario = ?");
  64.             p.setString(1, user1.getUsername());
  65.  
  66.             ResultSet rs = p.executeQuery();
  67.  
  68.             if (rs.next()) {
  69.  
  70.                 user1.setToken(generateToken(user1.getUsername()));
  71.                 userValidated = true;
  72.  
  73.             }
  74.             con.close();
  75.  
  76.         } catch (Exception e) {
  77.  
  78.             return Response.status(500).build();
  79.         }
  80.  
  81.         user1.setPassword("");
  82.         if (userValidated) {
  83.             return Response.status(200).entity(gson.toJson(user1)).build();
  84.         } else {
  85.             return Response.status(401).build();
  86.         }
  87.  
  88.     }
  89.  
  90.     // String username = user1.getUsername();
  91.     // System.out.println(username);
  92.     // String password = user1.getPassword();
  93.     // System.out.println(password);
  94.     // boolean verified = auth(username, password);
  95.     // System.out.println(verified);
  96.     //
  97.     // if (verified) {
  98.     // token = generateToken(username);
  99.     //
  100.     // PreparedStatement p1 = con.prepareStatement("UPDATE usuarios SET token = ?
  101.     // WHERE usuario = ?");
  102.     // p1.setString(1, token);
  103.     // p1.setString(2, username);
  104.     //
  105.     // if (p1.executeUpdate() > 0) {
  106.     // actu = true;
  107.     // }
  108.     //
  109.     // user2 = new User(token);
  110.  
  111.     // public boolean auth(String username, String password) {
  112.     //
  113.     // boolean encontrado = false;
  114.     // boolean verificado = false;
  115.     //
  116.     // try {
  117.     // Class.forName(Constants.JDBC_DRIVER);
  118.     // Connection con =
  119.     // DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
  120.     // Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
  121.     //
  122.     // PreparedStatement p = con.prepareStatement("SELECT * FROM usuarios WHERE
  123.     // usuario = ? AND password = ?");
  124.     // p.setString(1, username);
  125.     // p.setString(2, password);
  126.     //
  127.     // ResultSet rs = p.executeQuery();
  128.     // if (rs.next()) {
  129.     // System.out.println("CONSULTA HECHA");
  130.     // verificado = true;
  131.     // } else {
  132.     // System.out.println("CONSULTA NO HECHA");
  133.     // verificado = false;
  134.     // }
  135.     // con.close();
  136.     //
  137.     // } catch (Exception e) {
  138.     // System.out.println("ERROR");
  139.     // return false;
  140.     // }
  141.     // if (verificado) {
  142.     // return true;
  143.     // } else {
  144.     // return false;
  145.     // }
  146.     //
  147.     // }
  148.  
  149.     public String generateToken(String username) throws Exception {
  150.  
  151.         String token = null;
  152.  
  153.         Algorithm a = Algorithm.HMAC256(Constants.TOKEN_KEY);
  154.  
  155.         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  156.         Date issuedDate = format.parse(LocalDate.now().toString());
  157.         Date expirationDate = format.parse(LocalDate.now().plusMonths(1).toString());
  158.  
  159.         token = JWT.create().withSubject(username).withIssuedAt(issuedDate).withExpiresAt(expirationDate).sign(a);
  160.         /*
  161.          * Key key = MacProvider.generateKey(); token =
  162.          * Jwts.builder().setSubject(username).signWith(SignatureAlgorithm.HS512,
  163.          * key).compact();
  164.          */
  165.  
  166.         return token;
  167.     }
  168.  
  169.     public void validateToken(String token) throws Exception {
  170.  
  171.         Algorithm a = Algorithm.HMAC256(Constants.TOKEN_KEY);
  172.         JWTVerifier verifier = JWT.require(a).build();
  173.         DecodedJWT jwt = verifier.verify(token);
  174.  
  175.     }
  176.  
  177.     private boolean isTokenValid(String token) {
  178.         return token != null && token.toLowerCase().startsWith(AUTHENTICATION_SCHEME + " ");
  179.     }
  180.  
  181.     public boolean compareToken(String token) {
  182.  
  183.         try {
  184.             if (!isTokenValid(token)) {
  185.                 return false;
  186.             } else {
  187.                 token = token.substring(AUTHENTICATION_SCHEME.length()).trim();
  188.                 validateToken(token);
  189.                 return true;
  190.             }
  191.         } catch (Exception e) {
  192.             return false;
  193.         }
  194.  
  195.         // boolean comparacion = false;
  196.         //
  197.         // String[] tok = token.split(" ");
  198.         // String tokenComp = tok[1];
  199.         // System.out.println(tokenComp);
  200.         // try {
  201.         //
  202.         // Class.forName(Constants.JDBC_DRIVER);
  203.         // Connection con =
  204.         // DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
  205.         // Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
  206.         //
  207.         // PreparedStatement p = con.prepareStatement("SELECT token FROM usuarios WHERE
  208.         // token = ?");
  209.         // p.setString(1, tokenComp);
  210.         //
  211.         // ResultSet rs = p.executeQuery();
  212.         //
  213.         // if (rs.next()) {
  214.         // comparacion = true;
  215.         // }
  216.         //
  217.         // } catch (Exception e) {
  218.         // comparacion = false;
  219.         // }
  220.         //
  221.         // if (comparacion) {
  222.         // return true;
  223.         // } else {
  224.         // return false;
  225.         // }
  226.  
  227.     }
  228.  
  229. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement