Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package api;
- import java.io.UnsupportedEncodingException;
- import java.security.Key;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.text.SimpleDateFormat;
- import java.time.LocalDate;
- import java.util.Date;
- import javax.ws.rs.Consumes;
- import javax.ws.rs.FormParam;
- import javax.ws.rs.POST;
- import javax.ws.rs.Path;
- import javax.ws.rs.Produces;
- import javax.ws.rs.core.MediaType;
- import javax.ws.rs.core.Response;
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.JWTVerifier;
- import com.auth0.jwt.algorithms.Algorithm;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import com.google.gson.Gson;
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.SignatureAlgorithm;
- import io.jsonwebtoken.impl.crypto.MacProvider;
- import modelos.Constants;
- import modelos.User;
- @Path("/login")
- public class Authentication {
- // private final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
- // private final static String JDBC_CONNECTION_STRING =
- // "jdbc:mysql://localhost:3306/campus_aula?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
- // private final static String JDBC_CONNECTION_USER = "AD";
- // private final static String JDBC_CONNECTION_PASS = "AccesoADatos";
- private final static String AUTHENTICATION_SCHEME = "bearer";
- @POST
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public Response autenticarUsuario(String json) {
- Gson gson = new Gson();
- User user1 = gson.fromJson(json, User.class);
- String token = null;// = generateToken(username);
- String tokenBD = null;
- User user2 = null;
- boolean actu = false;
- boolean userValidated = false;
- try {
- Class.forName(Constants.JDBC_DRIVER);
- Connection con = DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
- Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
- PreparedStatement p = con.prepareStatement("SELECT usuario FROM usuarios WHERE usuario = ?");
- p.setString(1, user1.getUsername());
- ResultSet rs = p.executeQuery();
- if (rs.next()) {
- user1.setToken(generateToken(user1.getUsername()));
- userValidated = true;
- }
- con.close();
- } catch (Exception e) {
- return Response.status(500).build();
- }
- user1.setPassword("");
- if (userValidated) {
- return Response.status(200).entity(gson.toJson(user1)).build();
- } else {
- return Response.status(401).build();
- }
- }
- // String username = user1.getUsername();
- // System.out.println(username);
- // String password = user1.getPassword();
- // System.out.println(password);
- // boolean verified = auth(username, password);
- // System.out.println(verified);
- //
- // if (verified) {
- // token = generateToken(username);
- //
- // PreparedStatement p1 = con.prepareStatement("UPDATE usuarios SET token = ?
- // WHERE usuario = ?");
- // p1.setString(1, token);
- // p1.setString(2, username);
- //
- // if (p1.executeUpdate() > 0) {
- // actu = true;
- // }
- //
- // user2 = new User(token);
- // public boolean auth(String username, String password) {
- //
- // boolean encontrado = false;
- // boolean verificado = false;
- //
- // try {
- // Class.forName(Constants.JDBC_DRIVER);
- // Connection con =
- // DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
- // Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
- //
- // PreparedStatement p = con.prepareStatement("SELECT * FROM usuarios WHERE
- // usuario = ? AND password = ?");
- // p.setString(1, username);
- // p.setString(2, password);
- //
- // ResultSet rs = p.executeQuery();
- // if (rs.next()) {
- // System.out.println("CONSULTA HECHA");
- // verificado = true;
- // } else {
- // System.out.println("CONSULTA NO HECHA");
- // verificado = false;
- // }
- // con.close();
- //
- // } catch (Exception e) {
- // System.out.println("ERROR");
- // return false;
- // }
- // if (verificado) {
- // return true;
- // } else {
- // return false;
- // }
- //
- // }
- public String generateToken(String username) throws Exception {
- String token = null;
- Algorithm a = Algorithm.HMAC256(Constants.TOKEN_KEY);
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- Date issuedDate = format.parse(LocalDate.now().toString());
- Date expirationDate = format.parse(LocalDate.now().plusMonths(1).toString());
- token = JWT.create().withSubject(username).withIssuedAt(issuedDate).withExpiresAt(expirationDate).sign(a);
- /*
- * Key key = MacProvider.generateKey(); token =
- * Jwts.builder().setSubject(username).signWith(SignatureAlgorithm.HS512,
- * key).compact();
- */
- return token;
- }
- public void validateToken(String token) throws Exception {
- Algorithm a = Algorithm.HMAC256(Constants.TOKEN_KEY);
- JWTVerifier verifier = JWT.require(a).build();
- DecodedJWT jwt = verifier.verify(token);
- }
- private boolean isTokenValid(String token) {
- return token != null && token.toLowerCase().startsWith(AUTHENTICATION_SCHEME + " ");
- }
- public boolean compareToken(String token) {
- try {
- if (!isTokenValid(token)) {
- return false;
- } else {
- token = token.substring(AUTHENTICATION_SCHEME.length()).trim();
- validateToken(token);
- return true;
- }
- } catch (Exception e) {
- return false;
- }
- // boolean comparacion = false;
- //
- // String[] tok = token.split(" ");
- // String tokenComp = tok[1];
- // System.out.println(tokenComp);
- // try {
- //
- // Class.forName(Constants.JDBC_DRIVER);
- // Connection con =
- // DriverManager.getConnection(Constants.JDBC_CONNECTION_STRING,
- // Constants.JDBC_CONNECTION_USER, Constants.JDBC_CONNECTION_PASS);
- //
- // PreparedStatement p = con.prepareStatement("SELECT token FROM usuarios WHERE
- // token = ?");
- // p.setString(1, tokenComp);
- //
- // ResultSet rs = p.executeQuery();
- //
- // if (rs.next()) {
- // comparacion = true;
- // }
- //
- // } catch (Exception e) {
- // comparacion = false;
- // }
- //
- // if (comparacion) {
- // return true;
- // } else {
- // return false;
- // }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement