Skip to content

Instantly share code, notes, and snippets.

@ralph-tice
Created September 29, 2012 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralph-tice/3803105 to your computer and use it in GitHub Desktop.
Save ralph-tice/3803105 to your computer and use it in GitHub Desktop.
<?php
use ORM;
class User {
protected $userId;
protected $userName;
protected $role;
protected $row = null;
// username and password means check password and load from database, and set in session
// passing a row means hydrate a User directly
public function __construct($userName, $password, $login = true, $row = null) {
if (isset($row)) {
loadByRow($row);
} else {
login($userName, $password);
}
if ($login) {
$_SESSION['user'] = serialize($this);
}
}
private function login($userName, $password) {
$hasher = new \Hautelook\Phpass\PasswordHash(8, false);
$user = ORM::for_table('users')
->where_equal('userName', $userName)
->find_one();
if ($user && $hasher->CheckPassword($password, $user->password)) {
loadByRow($user);
} else {
$this->role = 'authfail';
}
}
private function loadByRow($row) {
$this->userId = $row->userid;
$this->userName = $row->username;
$this->role = $row->role;
$this->row = $row;
}
public function getUserName() {
return $this->userName;
}
public function getRole() {
return $this->role;
}
public function getUserId() {
return $this->userId;
}
// admin gets every role
public function belongsToRole($roleToCheck) {
return $this->role == $roleToCheck || $this->role == 'admin';
}
public static function fetchFromSession() {
if (isset($_SESSION) && isset($_SESSION['user'])) {
return unserialize($_SESSION['user']);
}
return null;
}
public static function createUser($username, $password, $role) {
$hasher = new \Hautelook\Phpass\PasswordHash(8, false);
$hash = $hasher->HashPassword($password);
$newUser = ORM::for_table("users")->create();
$newUser->set('username', $username);
$newUser->set('password', $hash);
$newUser->set('role', $role);
$newUser->save();
return new User($newUser->username, $password, false);
}
public static function listUsers() {
$rows = ORM::for_table("users")->find_many();
$users = array();
foreach ($rows as $row) {
$users[] = new User(null, null, false, $row);
}
return $users;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment