package tracker_java.Utilities;

import org.glassfish.jersey.server.ContainerRequest;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.mindrot.jbcrypt.BCrypt;
import redis.clients.jedis.Jedis;
import tracker_java.Models.HibernateUtil;

import javax.xml.bind.DatatypeConverter;

/**
 * Created by cristian on 11/10/15.
 */
public final class AuthenticationHandler {

    // all methods are static since they do not store any state in the class
    public static String[] decode(String auth) {
        auth = auth.replaceFirst("[B|b]asic ", "");

        byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth);

        if (decodedBytes == null || decodedBytes.length == 0) {
            return null;
        }

        return new String(decodedBytes).split(":", 2);
    }

    public static boolean checkUserNamePassword(String username, String password) throws Exception{
        try {
            String hashed = null;
            Session s = HibernateUtil.getSessionFactory().openSession();
            Transaction tx = s.beginTransaction();
            Query q = s.createQuery("select password from MemberEntity where username = :username").setParameter("username", username);
            try {
                hashed = (String) q.list().get(0);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            s.flush();
            tx.commit();
            s.close();

            return hashed != null && BCrypt.checkpw(password, hashed);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /*
    stores the token as a key, with userid as value;
    stores the userid as a key, with token as value;
    check and delete if a userid was already assoc. with a previous token;
     */
    public static void saveToken(String theToken, Integer userid) {
        try {
            Jedis redis = JedisPoolInstance.pool.getResource();
            redis.set(theToken, userid.toString());
            if (redis.get(userid.toString())!=null) {
                redis.del(redis.get(userid.toString()));
            }
            redis.set(userid.toString(), theToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Integer getUserIdFromUsername(String username) throws Exception {
        try {
            Session s = HibernateUtil.getSessionFactory().openSession();
            Transaction tx = s.beginTransaction();
            Query q = s.createQuery("select memberid from MemberEntity where username = :username").setParameter("username", username);
            Integer userId = (Integer) q.list().get(0);
            s.flush();
            tx.commit();
            s.close();
            return userId;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}


@@ -283,16 +283,94 @@
 eUtil;%0A%0A
+import javax.ws.rs.WebApplicationException;%0Aimport javax.ws.rs.core.Response;%0A
 import j
@@ -401,16 +401,39 @@
 nverter;
+%0Aimport java.util.UUID;
 %0A%0A/**%0A *
@@ -1754,39 +1754,20 @@
     
-stores the token as a key, wi
+check if 
 th
+e
  use
@@ -1775,144 +1775,118 @@
 id a
-s value;%0A    stores the userid as a key, with token as value;%0A    check and delete if a userid was already assoc. with a previous token;
+lready has a token%0A    if so, return that to the user%0A    else%0A    store newly generated token and return that
 %0A   
@@ -1912,40 +1912,25 @@
 tic 
-void saveToken(
 String 
-th
+sav
 eToken
-, 
+(
 Inte
@@ -1949,32 +1949,33 @@
 %7B%0A        try %7B%0A
+%0A
             Jedi
@@ -2038,28 +2038,41 @@
     
-redis.set(theToken, 
+String existingToken = redis.get(
 user
@@ -2107,45 +2107,179 @@
 if (
-redis.get(userid.toString())!=null) %7B
+existingToken!=null) %7B%0A                return existingToken;%0A            %7D%0A            else %7B%0A                String theToken = UUID.randomUUID().toString().toUpperCase();
 %0A   
@@ -2301,19 +2301,9 @@
 dis.
-del(redis.g
+s
 et(u
@@ -2318,17 +2318,26 @@
 String()
-)
+, theToken
 );%0A     
@@ -2340,33 +2340,23 @@
         
-   %7D%0A
        
-     
 redis.se
@@ -2349,32 +2349,42 @@
       redis.set(
+theToken, 
 userid.toString(
@@ -2376,33 +2376,57 @@
 serid.toString()
-,
+);%0A                return
  theToken);%0A    
@@ -2410,35 +2410,48 @@
  return theToken
-)
 ;%0A
+            %7D%0A
         %7D catch 
@@ -2501,32 +2501,105 @@
 ce();%0A        %7D%0A
+        throw new WebApplicationException(Response.status(500).build());%0A
     %7D%0A%0A    publi

throw exc. on not saving and generating token successfully