Last active
August 9, 2018 00:31
-
-
Save walison17/a9623a5813962623906707fcc94ff55d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Authenticator | |
{ | |
const SESSION_KEY = 'auth'; | |
protected $ci; | |
public function __construct() | |
{ | |
$this->ci =& get_instance(); | |
$this->ci->load->model('user_model'); | |
} | |
/** | |
* Faz o login do usuário | |
* | |
* @param string $username | |
* @param string $password | |
* @return bool | |
*/ | |
public function login($username, $password) | |
{ | |
$user = $this->ci->user_model->get_with_perfil($username); | |
if (password_verify($user->pws, $password)) { | |
$this->save_on_session($user); | |
$this->update_login_related_fields($user); | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Retorna o usuário ativo/logado | |
* | |
* @return mixed | |
*/ | |
public function get_current_user() | |
{ | |
if ($this->check()) { | |
$username = $this->ci->session->userdata[self::SESSION_KEY]['username']; | |
return $this->user_model->get($username); | |
} | |
return null; | |
} | |
/** | |
* Verifica se sistema possui usuário ativo | |
* | |
* @return bool | |
*/ | |
public function check() | |
{ | |
return $this->ci->session->has_userdata(self::SESSION_KEY); | |
} | |
/** | |
* Armazena informações do usuário na sessão | |
* | |
* @param mixed $user | |
* @return void | |
*/ | |
private function save_on_session($user) | |
{ | |
$data = [ | |
'username' => $user->username, | |
'full_name' => $user->full_name, | |
'id_perfil' => $user->id_perfil, | |
]; | |
$this->ci->session->set_userdata([self::SESSION_KEY => $data]); | |
} | |
/** | |
* Faz logout do usuário | |
* | |
* @return void | |
*/ | |
public function logout() | |
{ | |
$this->ci->session->unset_userdata(self::SESSION_KEY); | |
} | |
/** | |
* Atualiza campos relacionados ao login | |
* | |
* @param mixed $user | |
* @return void | |
*/ | |
public function update_login_related_fields($user) | |
{ | |
$this->ci->user_model->update( | |
$user->username, | |
[ | |
'qtde_acessos' => '(qtde_acessos + 1)', | |
'dt_ultacesso' => date('Y-m-d H:i:s') | |
] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment