diff --git a/app/classes/user.php b/app/classes/user.php
index 9c2e11e..9d0333e 100644
--- a/app/classes/user.php
+++ b/app/classes/user.php
@@ -9,12 +9,51 @@ class User {
// registration
public function register($username, $password) {
- $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
- $query = $this->db->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
- $query->bindParam(':username', $username);
- $query->bindParam(':password', $hashedPassword);
+ try {
+ // we have two inserts, start a transaction
+ $this->db->beginTransaction();
- return $query->execute();
+ // hash the password, don't store it plain
+ $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
+
+ // insert into users table
+ $sql = 'INSERT
+ INTO users (username, password)
+ VALUES (:username, :password)';
+ $query = $this->db->prepare($sql);
+ $query->bindValue(':username', $username);
+ $query->bindValue(':password', $hashedPassword);
+
+ // execute the first query
+ if (!$query->execute()) {
+ // rollback on error
+ $this->db->rollBack();
+ return false;
+ }
+
+ // insert the last user id into users_meta table
+ $sql2 = 'INSERT
+ INTO users_meta (user_id)
+ VALUES (:user_id)';
+ $query2 = $this->db->prepare($sql2);
+ $query2->bindValue(':user_id', $this->db->lastInsertId());
+
+ // execute the second query
+ if (!$query2->execute()) {
+ // rollback on error
+ $this->db->rollBack();
+ return false;
+ }
+
+ // if all is OK, commit the transaction
+ $this->db->commit();
+ return true;
+
+ } catch (Exception $e) {
+ // rollback on any error
+ $this->db->rollBack();
+ return $e->getMessage();
+ }
}
// login
diff --git a/app/pages/login.php b/app/pages/login.php
index ebb34f0..2694cbb 100644
--- a/app/pages/login.php
+++ b/app/pages/login.php
@@ -1,7 +1,5 @@
register($username, $password);
+
// redirect to login
- if ( $userObject->register($username, $password) ) {
+ if ($result === true) {
$_SESSION['notice'] = "Registration successful.
You can log in now.";
header('Location: index.php');
exit();
// registration fail, redirect to login
} else {
- $_SESSION['error'] = "Registration failed.";
+ $_SESSION['error'] = "Registration failed. $result";
header('Location: index.php');
exit();
}
}
} catch (Exception $e) {
- $error = getError('There was an unexpected error. Please try again.', $e->getMessage());
+ $error = $e->getMessage();
}
include '../app/templates/block-message.php';
diff --git a/app/templates/form-register.php b/app/templates/form-register.php
index 5a72c16..f95a36d 100644
--- a/app/templates/form-register.php
+++ b/app/templates/form-register.php
@@ -3,7 +3,7 @@
Enter credentials for registration:
-