Criando webservice com cakePHP e AuthComponent ?
Salve galera
Estou tentando criar um WebService usando o CakePHP 2.x. Criei um Painel para fazer o CRUD que preciso, nesse painel eu tenho a tela de login que uso o AuthComponent com authenticate = Form, isso funciona bem, faz login e bloqueia as actions que preciso normalmente.
O problema eh quanto ao WebService, eu crio as functions para retornar os JSON mas quando tento executar pela URL me retorna a página principal da minha aplicação. Acredito que para conseguir trabalhar com os JSON do meu webservice eu preciso fazer a autenticação por Header, pra isso estou tentando configurar o Basic Auth do CakePHP junto com o Form.
Configuro tudo, mas assim que adiciono o Basic deixa de funcionar o login no Painel, eh como se o Basic liberasse todo o Painel para acesso, eu consigo acessar qualquer action pela URL sem fazer o login.
Como eu consigo fazer para que o Form e o Basic do AuthComponent funcionem juntos e eu consiga consumir o webservice ?
Estou tentando assim.
//AppController
class AppController extends Controller {
public $components = array("RequestHandler", "Auth", "Session");
public function beforeFilter(){
$this->Auth->authenticate = array(
'Basic' => array('userModel' => 'User',
'fields'=> array(
'username' => 'email',
'password' => 'senha'
),
'scope' => array(
'User.status' => 1
)
),
'Form' => array('userModel' => 'User',
'fields'=> array(
'username' => 'email',
'password' => 'senha'
),
'scope' => array(
'User.status' => 1
)
),
);
$this->Auth->loginAction = array(
'controller' => 'users',
'action' => 'login'
);
$this->Auth->loginRedirect = array(
'controller' => 'matriculas',
'action' => 'index'
);
$this->Auth->logoutRedirect = array(
'controller' => 'users',
'action' => 'login'
);
$this->Auth->authorize = "Controller";
$this->Auth->authError = "Efetue login de acesso";
$this->Auth->allow("login");
}
public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true; // Admin pode acessar todas actions
}
return false; // Os outros usuários não podem
}
}
//UsersController
class UsersController extends AppController {
/**
* Components
*
* @var array
*/
public $components = array('Paginator');
public function beforeFilter() {
parent::beforeFilter();
//$this->Auth->allow('loginApp', 'showPostJson');
}
/**
* index method
*
* @return void
*/
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
/**
* view method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
/**
* edit method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
/**
* delete method
*
* @throws NotFoundException
* @param string $id
* @return void
*/
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->request->allowMethod('post', 'delete');
if ($this->User->delete()) {
$this->Session->setFlash(__('The user has been deleted.'));
} else {
$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}
public function login(){
$this->layout = "layout";
if($this->request->is("post")){
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash(__('Usuário ou senha inválido'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}
/*** metodos de webservice ****/
/** retorna para o App todos os usuarios cadastrados **/
public function findAll(){
$this->set("usuarios", $this->User->find('all'));
$this->set(array(
"_serialize" => 'usuarios',
));
}
/** adiciona novo usuario pelo App
*
* JSON to send
*
* {
* 'User':{
* 'email':'myself@gmail.com',
* 'senha':'aaaa',
* }
* }
*
*
* **/
public function addNewUser(){
$this->layout=null;
$data = $this->request->input("json_decode", true);
echo $data;
}
}Discussão (2)
Carregando comentários...