log-in.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. /* Authenticates the user or returns error if the credentials are not correct */
  3. $params = array();
  4. parse_str($_POST['sign_in_data'], $params);
  5. if(!array_key_exists('email-login', $params) || !array_key_exists('password-login', $params)) {
  6. echo 400; // Missing parameters
  7. }
  8. else {
  9. // Retrieve user credentials
  10. $email = $params['email-login'];
  11. $password = $params['password-login'];
  12. require_once('db_utils.php');
  13. $conn = db_connect(); // Connect to the database
  14. // Check if the username already exists
  15. if(!($result = mysqli_query($conn, "SELECT * FROM user WHERE username = '$email'"))) {
  16. echo 400; // Wrong query
  17. }
  18. else {
  19. if(mysqli_num_rows($result) != 1) { // User not registered or duplicated
  20. echo 401;
  21. }
  22. else {
  23. $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
  24. mysqli_free_result($result);
  25. $activated = $row['activated'];
  26. if($activated == FALSE)
  27. echo 402; // Email not activated
  28. else { // Email verified
  29. $hash = $row['password'];
  30. $full_salt = substr($hash, 0, 29);
  31. $new_hash = crypt($password, $full_salt);
  32. if ($hash == $new_hash) {
  33. session_start(); // Start session for this user
  34. $_SESSION['userlogin'] = $email; // Save email in the session
  35. echo 200; // Authentication successful
  36. }
  37. else
  38. echo 401; // Wrong username or password
  39. }
  40. }
  41. }
  42. mysqli_free_result($result);
  43. db_close($conn); // Close the database
  44. }
  45. ?>