Authentication class with "cumbersome" instantiation methods
Posted: Sat Apr 26, 2008 7:43 pm
How does this authentication look? I wish my instantiation of the class, particularly the method arguments were shorter/easier to work with. Right now I feel like they are very cumbersome. Would you organize this class differently?
Any ideas?
Thank you all in advance.
Any ideas?
Thank you all in advance.
Code: Select all
$mysqli = new mysqli(MYSQL_SERVER,MYSQL_SERVER_USERNAME,MYSQL_SERVER_PASSWORD);
class Authentication {
//Declaring variables
private $username;
private $password;
//Setting username and password
public function __construct($username, $password) {
$this->username = $username;
$this->password = md5($password);
}
/*
The following passes the MySQLi connection, database, table, and field
information to the class, which are then all used to generate a database
query for finding a matching username and password in the table for
login. Results of the query are then counted and, if equal to one, the
provided username and password are passed to the setSession method.
*/
public function doLogin($connection, $database, $table, $usernameField, $passwordField) {
$connection->select_db($database);
$statement = $connection->prepare("SELECT COUNT(*) FROM $table WHERE $usernameField = ? AND $passwordField = ?");
$statement->bind_param('ss', $this->username, $this->password);
$statement->execute();
$statement->bind_result($count);
$statement->fetch();
if ($count == 1) {
$this->setSession($this->username, $this->password);
} else {
return FALSE;
}
}
//Setting the provided username and password to session variables
private function setSession($username, $password) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
return TRUE;
}
/*
The following passes the MySQLi connection, database, table, and field
information to the class, which are then all used to generate a database
query for finding a matching username and permission in the table for
permission granting. Results of the query are then counted and, if equal
to one, TRUE is returned.
*/
public function checkPermission($connection, $database, $table, $usernameField, $permissionField, $permission) {
$connection->select_db($database);
$statement = $connection->prepare("SELECT COUNT(*) FROM $table WHERE $usernameField = ? AND $permissionField = ?");
$statement->bind_param('ss', $this->username, $permission);
$statement->execute();
$statement->bind_result($count);
$statement->fetch();
if ($count == 1) {
return TRUE;
} else {
return FALSE;
}
}
}
$authentication = new Authentication("user1", "pass1");
$authentication->doLogin($mysqli, '_authentication', 'users', 'username', 'password');
$authentication->checkPermission($mysqli, '_authentication', 'permissions', 'username', 'permission_for', 'example_permission');
$mysqli->close();