Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php defined('SYSPATH') OR die('No direct access allowed.');
- class Auth {
- protected static $config;
- protected static $current_user;
- protected static $instance;
- public static function instance()
- {
- if ( ! isset(Auth::$instance))
- Auth::$instance = new Auth;
- return Auth::$instance;
- }
- public function init()
- {
- Auth::$config = Kohana::config('auth');
- Auth::$current_user = ORM::factory('user', Session::instance()->get(Auth::$config['session_key']));
- }
- public function load_user()
- {
- if (Auth::$current_user->loaded())
- return Auth::$current_user;
- return FALSE;
- }
- public function login($account, $unique_key, $password, $remember = FALSE)
- {
- $user = ORM::factory('user')->where(array(
- Auth::$config['unique_key'] => $unique_key,
- 'password' => Auth::hash_password($password)
- ))->find();
- if ($user->loaded())
- {
- $session->regenerate();
- Session::instance()->set(Auth::$config['session_key'], $user->id);
- return $user;
- }
- return FALSE;
- }
- public static function logout($destroy = TRUE)
- {
- if ($destroy === TRUE)
- {
- Session::instance()->destroy();
- }
- else
- {
- Session::instance()->delete($this->config['session_key']);
- Session::instance()->regenerate();
- }
- }
- public static function hash_password($password)
- {
- return hash(Auth::$config['hash_method'], $password.$this->salt($password));
- }
- private function salt($password)
- {
- $salt = '';
- $salt_pattern = preg_split('/,\s*/', $this->config['salt_pattern']);
- foreach ($salt_pattern as $i => $offset)
- $salt .= substr($password, $offset + $i, 1);
- return $salt;
- }
- public function auto_login()
- {
- if ($token = cookie::get('authautologin'))
- {
- // Load the token and user
- $token = ORM::factory('user_token', array('token' => $token));
- if ($token->loaded() AND $token->user->loaded())
- {
- if ($token->user_agent === sha1(Request::$user_agent))
- {
- // Save the token to create a new unique token
- $token->save();
- // Set the new token
- cookie::set('authautologin', $token->token, $token->expires - time());
- // Complete the login with the found data
- $this->complete_login($token->user);
- // Automatic login was successful
- return TRUE;
- }
- // Token is invalid
- $token->delete();
- }
- }
- return FALSE;
- }
- public static function generate_password($length = 8)
- {
- $password = '';
- $chars = "023456789bcdfghjkmnpqrstvwxyz";
- $i = 0;
- while ($i < $length)
- {
- $char = substr($chars, mt_rand(0, strlen($chars)-1), 1);
- if (!strstr($password, $char))
- {
- $password .= $char;
- $i++;
- }
- }
- return $password;
- }
- }
Add Comment
Please, Sign In to add comment