Skip to content

Instantly share code, notes, and snippets.

@sergiopvilar
Created September 25, 2011 02:23
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 sergiopvilar/1240133 to your computer and use it in GitHub Desktop.
Save sergiopvilar/1240133 to your computer and use it in GitHub Desktop.
Problema com Hash de senhas
/**
* App Controller
*
* @link http://book.cakephp.org/pt/view/957/A-classe-AppController
*/
class AppController extends Controller
{
/**
* Define os componentes disponíveis por padrão
*
* @var array
* @access public
*/
var $components = array(
'Auth',
'Session',
'Cookie'
);
/**
* Define os helpers disponíveis por padrão
*
* @var array
* @access public
*/
var $helpers = array(
'Html',
'Form',
'Session',
'Ajax',
'Paginator'
);
/**
* Before Filter
*
* Função de callback executada antes que qualquer outra
*
* @access public
* @link http://book.cakephp.org/pt/view/984/Callbacks
*/
function beforeFilter()
{
Security::setHash('md5'); // Método de Hash da senha
$this->Auth->userModel = "Usuario"; // Nome do modelo para os usuários
$this->Auth->fields = array(
'username'=>'username', // Troque o segundo parametro se desejar
'password'=>'password', // Troque o segundo parametro se desejar
);
$this->Auth->userScope = array(
'Usuario.active' => '1' // Permite apenas usuários ativos
);
$this->Auth->authorize = 'controller'; // Utiliza a função isAuthorize para autorizar os usuários
$this->Auth->autoRedirect = true; // Redireciona o usuário para a requisição anterior que foi negada após o login
$this->Auth->loginAction = array(
'controller' => 'Usuarios',
'action' => 'login',
'admin' => false
);
$this->Auth->loginRedirect = array(
'controller' => 'painel',
'action' => 'admin_index',
'admin' => true
);
$this->Auth->logoutRedirect = array(
'controller' => 'pages',
'action' => 'home',
'admin' => false
);
$this->Auth->loginError = __('Usuário ou senha inválidos.', true);
$this->Auth->authError = __('Você não tem permissão para acessar.', true);
// Libera acesso para actions sem prefixo admin
if ( !(isset($this->params['admin'])) )
{
$this->Auth->allow('*'); // Libera acesso
}
//$this->Auth->allow('*');
} // beforefilter
/**
* Is Authorized
*
* Faz a autorização do usuário
*
* @return boolean
* @access public
*/
function isAuthorized() {
// Pode ser mais complexo antes de liberar o acesso
return true;
}
}
class RegistroController extends AppController {
var $helpers = array ('Html','Form','javascript','Session');
var $name = 'Registro';
var $components = array ('Email','Session','RequestHandler');
var $uses = array('Usuario');
function index(){
if ($this->Auth->user('id')){
$this->redirect('/admin/painel');
}
$this->set('title_for_layout', 'Registre-se no Alter');
if (!empty($this->data)) {
$this->Usuario->create();
$this->Usuario->set(array(
'code' => md5(base64_encode($this->data['Usuario']['email']))
));
if ($this->Usuario->save($this->data)) {
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'sergiovilar.r@gmail.com',
'password'=>'#Extreme8542#8826',
);
$this->Email->to = $this->data['Usuario']['email'];
$this->Email->bcc = array('sergio@feelsen.com');
$this->Email->subject = 'Seja bem vindo ao Alter';
$this->Email->replyTo = 'alter@feelsen.com';
$this->Email->from = 'Alter <noreply@feelsen.com>';
$this->Email->template = 'registro'; // note no '.ctp'
//Send as 'html', 'text' or 'both' (default is 'text')
$this->Email->sendAs = 'html'; // because we like to send pretty mail
$mensagem = array(
'nome' => $this->data['Usuario']['name'],
'codigo' => md5(base64_encode($this->data['Usuario']['email'])),
);
$this->set('Mensagem', $mensagem);
//Do not pass any args to send()
$this->Email->send();
// Redireciona para página de concluído
$this->redirect(array('action' => 'add'));
}else{
$this->Session->setFlash('Houve um erro ao validar seus dados.','flash_error');
}
}
}
function add() {
$this->set('title_for_layout', 'Registro concluído');
$this->Session->setFlash('Nós te enviamos um email de confirmação, por favor, cheque sua caixa de entrada e desfrute ao máximo do Alter.','flash_info');
}
function confirm($code = null){
$usuario = $this->Usuario->find(array('Usuario.code'=>$code));
if(count($usuario['Usuario'])!=0 && $usuario['Usuario']['active']==0):
$this->Usuario->set(array(
'id' => $usuario['Usuario']['id'],
'active' => '1'
));
$this->Usuario->save($this->data);
$this->Session->setFlash('Seu registro foi confirmado com sucesso! Faça login abaixo.','flash_success');
$this->redirect(array('controller'=>'Usuarios','action' => 'login'));
else:
$this->Session->setFlash('Este não é um link válido.','flash_error');
$this->redirect(array('controller'=>'Usuarios','action' => 'login'));
endif;
}
}
class UsuariosController extends AppController {
var $name = 'Usuarios';
var $components = array ('Email','Session','RequestHandler');
function admin_index() {
if($this->Auth->User('level')<10):
$this->redirect('/');
endif;
$this->Usuario->recursive = 0;
$this->set('usuarios', $this->paginate());
$this->set('title', 'Administrar Usuários');
}
function admin_view($id = null) {
if($this->Auth->User('level')<10):
$this->redirect('/');
endif;
if (!$id) {
$this->Session->setFlash('Invalid usuario', true);
$this->redirect(array('action' => 'index'));
}
$this->set('usuario', $this->Usuario->read(null, $id));
}
function admin_add() {
if($this->Auth->User('level')<10):
$this->redirect('/');
endif;
if (!empty($this->data)) {
$this->Usuario->create();
if ($this->Usuario->save($this->data)) {
$this->Session->setFlash('O usuário foi cadastrado com sucesso.', 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('O usuário não pôde ser cadastrado. Por favor, tente novamente.', 'flash_warning');
}
}
}
function admin_edit($id = null) {
if($this->Auth->User('level')<10):
$this->redirect('/');
endif;
if (!$id && empty($this->data)) {
$this->Session->setFlash('Usuário inválido', 'flash_warning');
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Usuario->save($this->data)) {
$this->Session->setFlash('O usuário foi atualizado com sucesso.', 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('O usuário não pôde ser salvo. Por favor, tente novamente.', 'flash_error');
}
}
if (empty($this->data)) {
$this->data = $this->Usuario->read(null, $id);
}
}
function admin_delete($id = null) {
if($this->Auth->User('level')<10):
$this->redirect('/');
endif;
if (!$id) {
$this->Session->setFlash('ID de usuário inválida.', 'flash_warning');
$this->redirect(array('action'=>'index'));
}
if ($this->Usuario->delete($id)) {
$this->Session->setFlash('O usuário foi excluído com sucesso.', 'flash_info');
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash('O usuário não pôde ser apagado.', 'flash_error');
$this->redirect(array('action' => 'index'));
}
/**
* Login
*
* @access public
*/
function login()
{
//var_dump($this->data);
// Aqui é tudo automagic. O Auth Component se encarrega de fazer tudo sozinho.
}
/**
* Logout
*
* @access public
*/
function logout()
{
$this->Session->setFlash(__('Sua sessão foi encerrada.', true)); // Mensagem de logout
$this->redirect($this->Auth->logout()); // Redireciona para tela de logout
}
function beforeFilter() {
parent::beforeFilter();
}
function sendpassword(){
if(!empty($this->data)):
$usuario = $this->Usuario->find(array('Usuario.email'=>$this->data['Usuario']['email']));
if(count($usuario['Usuario'])!=0):
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'sergiovilar.r@gmail.com',
'password'=>'#Extreme8542#8826',
);
$this->Email->to = $this->data['Usuario']['email'];
$this->Email->bcc = array('sergio@feelsen.com');
$this->Email->subject = 'Recuperação de senha';
$this->Email->replyTo = 'alter@feelsen.com';
$this->Email->from = 'Alter <noreply@feelsen.com>';
$this->Email->template = 'passreset'; // note no '.ctp'
$this->Email->sendAs = 'html'; // because we like to send pretty mail
$mensagem = array(
'nome' => $usuario['Usuario']['name'],
'codigo' => md5(base64_encode($this->data['Usuario']['email'])),
);
$this->set('Mensagem', $mensagem);
$this->Email->send();
$this->Session->setFlash('Um email lhe foi enviado parar redefinir sua senha.','flash_info');
$this->redirect(array('controller'=>'Usuarios','action' => 'login'));
else:
$this->Session->setFlash('Este email não consta no nosso banco de dados.','flash_error');
$this->redirect(array('controller'=>'Usuarios','action' => 'sendpassword'));
endif;
endif;
}
function passwordreset($code = null){
Security::setHash('md5'); // Método de Hash da senha
if(!empty($this->data)):
$usuario = $this->Usuario->find(array('Usuario.code'=>$this->data['Usuario']['code']));
if(count($usuario['Usuario'])!=0):
$this->data['Usuario']['password'] = Security::hash($this->data['Usuario']['password']);
/*$this->Usuario->set(array(
'id' => $usuario['Usuario']['id'],
'password' => $this->data['Usuario']['password']
));*/
$this->Usuario->save($this->data);
$this->Session->setFlash('Sua senha foi resetada com sucesso! Faça login abaixo.','flash_success');
$this->redirect(array('controller'=>'Usuarios','action' => 'login'));
else:
$this->Session->setFlash('Este não é um link válido.','flash_error');
$this->redirect(array('controller'=>'Usuarios','action' => 'login'));
endif;
else:
$usuario = $this->Usuario->find(array('Usuario.code'=>$code));
$this->set('code', $code);
$this->set('id',$usuario['Usuario']['id']);
endif;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment