Advertisement
Guest User

Untitled

a guest
Dec 4th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.37 KB | None | 0 0
  1. package utils;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.util.ArrayList;
  7. import java.util.concurrent.ThreadLocalRandom;
  8.  
  9.  
  10. import utils.GeneralUtils;
  11. import database.MainConnection;
  12. import entity.User;
  13.  
  14. public class UserUtil extends MainConnection {
  15.  
  16. public static void main(String[] args ) throws Exception {
  17. //test da cancellare
  18. //registerUser("mattia3","prova2", hash("password"), "mattia", "paccamiccio", "1994-12-01", "unicam");
  19.  
  20. //test da cancellare
  21. //passwordRecovery("mattia.paccamiccio@studenti.unicam.it");
  22.  
  23. //test da cancellare
  24. //int userId=0;
  25. //userId=getIDFromEmail("zeropaccato@gmail.com");
  26. //System.out.println(userId);
  27.  
  28. }
  29.  
  30. //Metodo che dato in input l'user lo inserisce nel database per la registrazione, aggiungere creazione repository privata
  31. public static Boolean registerUser(User user) throws Exception {
  32. try{
  33. Connection con = getConnection();
  34.  
  35. //la password viene criptata
  36. String hashedPassword = GeneralUtils.hash(user.getPassword());
  37.  
  38. PreparedStatement registerUserQuery = con.prepareStatement("INSERT INTO users (Username, Email, Password, Name, Surname, BirthDate, Affiliation) VALUES (?,?,?,?,?,?,?)");
  39. registerUserQuery.setString(1, user.getUsername());
  40. registerUserQuery.setString(2, user.getEmail());
  41. registerUserQuery.setString(3, hashedPassword);
  42. registerUserQuery.setString(4, user.getName());
  43. registerUserQuery.setString(5, user.getSurname());
  44. registerUserQuery.setString(6, user.getBirthdate());
  45. registerUserQuery.setString(7, user.getAffiliation());
  46. registerUserQuery.executeUpdate();
  47.  
  48. System.out.println("lo user è:"+user.getName()+"++"+user.getSurname()+"++"+user.getBirthdate()+"++"+user.getPassword()+"++"+user.getAffiliation()+"++"+user.getEmail());
  49. System.out.println("registrazione eseguita con successo");
  50.  
  51. int userID = getIDFromEmail(user.getEmail());
  52. createRepositoryForUser(userID);
  53.  
  54. con.close();
  55. return true;
  56. } catch(Exception e) {
  57. System.out.println(e);
  58. }
  59. System.out.println("registrazione fallita");
  60. return false;
  61. }
  62.  
  63. //Dato in input l'username e la password, esegue il login dell'utente se già esiste nel database
  64. public static Boolean userLogin(String username, String password) throws Exception {
  65. Boolean bool = true;
  66. try{
  67. Connection con = getConnection();
  68.  
  69. //la password viene criptata
  70. String hashedPassword = GeneralUtils.hash(password);
  71.  
  72. PreparedStatement query = con.prepareStatement("SELECT * FROM users WHERE Username=? AND Password=?");
  73. query.setString(1, username);
  74. query.setString(2, hashedPassword);
  75. ResultSet result = query.executeQuery();
  76.  
  77. //ArrayList<String> array = new ArrayList<String>();
  78. if(result.next()) {
  79. System.out.println("login effettuato");
  80. con.close();
  81. bool = true;
  82. }else{
  83. System.out.println("login fallito");
  84. con.close();
  85. bool = false;
  86. }
  87. }catch(Exception e) {
  88. System.out.println(e);
  89. }
  90. return bool;
  91. }
  92.  
  93. public static Boolean passwordRecovery(String email) throws Exception {
  94. Boolean bool = null;
  95.  
  96. try{
  97. Connection con = getConnection();
  98.  
  99. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM users WHERE Email=?");
  100. query1.setString(1, email);
  101. ResultSet result1 = query1.executeQuery();
  102.  
  103. String userID = null;
  104.  
  105. if(result1.next()) {
  106. userID = result1.getString("UserID");
  107. System.out.println(userID);
  108. }
  109. else {
  110. System.out.println("Email non trovata");
  111. con.close();
  112. return false;
  113. }
  114.  
  115.  
  116. PreparedStatement query2 = con.prepareStatement("INSERT INTO passwordrecovery (UserID, Token, Used) VALUES (?,?,?)");
  117. query2.setString(1, userID);
  118. query2.setString(2, GeneralUtils.generateRandomString());
  119. query2.setString(3, "false");
  120.  
  121.  
  122. int result2 = query2.executeUpdate();
  123.  
  124. if(result2 > 0) {
  125. System.out.println("query eseguita");
  126. }
  127. else {
  128. System.out.println("query non eseguita");
  129. }
  130. con.close();
  131. } catch(Exception e) {
  132. System.out.println(e); }
  133. return bool;
  134. }
  135.  
  136. //Restituisce "true" se il determinato username è già stato utilizzato, "false" altrimenti
  137. public static Boolean isUsernameUsed(String username) throws Exception {
  138. Boolean bool = false;
  139. Connection con = getConnection();
  140. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM users WHERE username=?");
  141. query1.setString(1, username);
  142. ResultSet result1 = query1.executeQuery();
  143. if(result1.next()) {
  144. bool=true;
  145. }
  146. con.close();
  147. return bool;
  148. }
  149.  
  150. //Restituisce "true" se la determinata Email è già stata utilizzata, "false" altrimenti
  151. public static Boolean isEmailUsed(String e_mail) throws Exception {
  152. Boolean bool = false;
  153. Connection con = getConnection();
  154. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM users WHERE email=?");
  155. query1.setString(1, e_mail);
  156. ResultSet result1 = query1.executeQuery();
  157. if(result1.next()) {
  158. bool=true;
  159. }
  160. con.close();
  161. return bool;
  162. }
  163.  
  164. //Restituisce l'id dell'utente a cui è associata una determinata e-mail, se viene restiuito "0" vuol dire
  165. //che non esiste nessun utente con quella e-mail
  166. public static int getIDFromEmail(String e_mail) throws Exception {
  167. int id=0;
  168. Connection con = getConnection();
  169. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM users WHERE email=?");
  170. query1.setString(1, e_mail);
  171. ResultSet result1 = query1.executeQuery();
  172. if(result1.next()) {
  173. //potrebbe non essere 1 ma 0, da controllare
  174. id=result1.getInt(1);
  175. }
  176. con.close();
  177. return id;
  178. }
  179.  
  180. //restituisce l'ID dell'utente associato al token dato, se l'utente non esiste restituisce 0
  181. public static int getUserIDFromToken(String token) throws Exception {
  182. int id_utente = 0;
  183. Connection con = getConnection();
  184. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM passwordrecovery WHERE token=?");
  185. query1.setString(1, token);
  186. ResultSet result1 = query1.executeQuery();
  187. if(result1.next()) {
  188. id_utente=result1.getInt(1);
  189. }
  190. con.close();
  191. return id_utente;
  192. }
  193.  
  194. //Restituisce la stringa contenente il nuovo token, nel caso in cui non sia riuscita a generare un nuovo
  195. //token restituisce la stringa vuota
  196. public static String createTokenForUser(int userID) throws Exception {
  197. Connection con = getConnection();
  198.  
  199. //Used è zero invece che false perché nel database viene utilizzato il tipo tinyInt
  200. PreparedStatement insertQuery = con.prepareStatement("INSERT INTO passwordrecovery (UserID, Token, Used) VALUES (?,?,0)");
  201. String userIDString = "";
  202. userIDString = Integer.toString(userID);
  203. insertQuery.setString(1, userIDString);
  204.  
  205. /////////////////////////////////////////////////////////////////////////////////
  206. //// DA CAMBIARE /////////////////////////////////////////////////////////
  207. /////////////////////////////////////////////////////////////////////////////////
  208.  
  209. String token = GeneralUtils.generateRandomString();
  210.  
  211. //Genera token come stringhe casuali fino a quando una di queste stringhe
  212. //non è nel database
  213. while(isTokenInDatabase(token)){
  214. token = GeneralUtils.generateRandomString();
  215. }
  216.  
  217. insertQuery.setString(2, token);
  218.  
  219. int result2 = insertQuery.executeUpdate();
  220.  
  221. if(result2==0) {
  222. token="";
  223. }
  224. con.close();
  225. return token;
  226. }
  227.  
  228. //Cambia la password di un utente, se la password è stata cambiata con successo allora viene
  229. //restiuito il valore true, altrimenti false
  230. public static Boolean changeUserPassword(int userID, String password) throws Exception {
  231.  
  232. Connection con = getConnection();
  233. Boolean hasPasswordChanged=false;
  234. String cryptedPassword=GeneralUtils.hash(password);
  235. PreparedStatement changePasswordQuery = con.prepareStatement("UPDATE users SET password=? WHERE UserID=?");
  236. changePasswordQuery.setString(1, cryptedPassword);
  237. changePasswordQuery.setString(2, Integer.toString(userID));
  238. int affectedRecords = changePasswordQuery.executeUpdate();
  239. if(affectedRecords>0) {
  240. hasPasswordChanged = true;
  241. setAllTokenOfUserAsUsed(userID);
  242. }
  243. System.out.println("Password has been changed");
  244. con.close();
  245. return hasPasswordChanged;
  246. }
  247.  
  248.  
  249. //Cambia la password di un utente, se la password è stata cambiata con successo allora viene
  250. //restiuito il valore true, altrimenti false
  251. public static void createRepositoryForUser(int userID) throws Exception {
  252.  
  253. Connection con = getConnection();
  254. PreparedStatement createRepositoryQuery = con.prepareStatement("INSERT INTO repository (OwnerID) VALUES (?)");
  255. createRepositoryQuery.setInt(1, userID);
  256. int affectedRecords = createRepositoryQuery.executeUpdate();
  257. if(affectedRecords>0) {
  258. System.out.println("Repository created");
  259. }
  260. con.close();
  261. }
  262.  
  263. ////////////////////////////////////////////////////////////////////////////////////////////////////
  264. //// INIZIO METODI PRIVATI //////////////////////////////////////////////////////////////////
  265. ///////////////////////////////////////////////////////////////////////////////////////////////////
  266.  
  267. //Metodo che dato in input un token, controlla se quel token è già presente nella tabella passwordrecovery
  268. private static Boolean isTokenInDatabase(String token) throws Exception{
  269. Connection con = getConnection();
  270. Boolean tokenIsInDatabase = false;
  271.  
  272. PreparedStatement query1 = con.prepareStatement("SELECT UserID FROM passwordrecovery WHERE token=?");
  273. query1.setString(1, token);
  274. ResultSet result1 = query1.executeQuery();
  275. if(result1.next()) {
  276. tokenIsInDatabase=true;
  277. }
  278. con.close();
  279. return tokenIsInDatabase;
  280. }
  281.  
  282. //Dato un id utente fa diventare usati tutti i token associati all'utente
  283. private static void setAllTokenOfUserAsUsed(int userId) throws Exception{
  284. Connection con = getConnection();
  285. //Used nella query è = 1 invece che TRUE perché MySQL non accetta tipi booleani e per simularli
  286. //nella tabella è stato usato il tipo "tinyInt" che può contenere solo i valori 0 e 1, quindi 0 corrisponde
  287. //per noi a FALSE e 1 a TRUE
  288. PreparedStatement usedTokenQuery = con.prepareStatement("UPDATE passwordrecovery SET Used=1 WHERE UserID=?");
  289. usedTokenQuery.setString(1, Integer.toString(userId));
  290. usedTokenQuery.executeUpdate();
  291. con.close();
  292. }
  293. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement