Skip to content

Instantly share code, notes, and snippets.

@srph
Last active January 10, 2018 18:51
Show Gist options
  • Select an option

  • Save srph/097ccefb9018c6f4a67db7b47dd7d48d to your computer and use it in GitHub Desktop.

Select an option

Save srph/097ccefb9018c6f4a67db7b47dd7d48d to your computer and use it in GitHub Desktop.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
<?php
class Auth {
/**
* Our unique session key
*/
protected $key = '__MY_APP_AUTH__';
/**
* PDO Instance
*/
protected $db;
/**
* Our user's data
*/
protected $data;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;port=3600', 'root', 'root')
$this->user()
}
/**
* Check if a user is authenticated
*/
public function check() {
return null != $this->data;
}
/**
* Opposite of `check`. Check if a user is not authenticated.
*/
public function guest() {
return null == $this->data;
}
/**
* Get the user data
*/
public function user() {
if ($this->data) {
return $this->data;
}
$prepared = $this->db->query("SELECT * FROM users WHERE username = :id LIMIT 1")
return $this->data = $prepared->query(['id' => $_SESSION[$this->key]]);
}
/**
* Login the user with the provided credentials
*/
public static function login($credentials) {
$prepared = $this->db->query("SELECT * FROM users WHERE username = :username LIMIT 1")
$user = $prepared->query(['username' => $credentials['username']])
if (null == $user) {
return false;
}
if ($credentials['password'] !== $user->password) {
return false;
}
$_SESSION[$this->key] = $this->data->id
$this->data = $user;
return true;
}
/**
* Logout the authenticated user
*/
public static function logout() {
delete $_SESSION[$this->key];
$this->data = null;
}
}
$auth = new Auth();
$auth->guest()
$auth->check()
$auth->login(['username' => 'admin', 'password' => '12369']);
$auth->user()
$auth->logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment