Can i convert whole cakephp website to web services? - cakephp-2.0

Hey I m working on project in cakephp. There will also be apps for Android as well as iPhone. How can i convert my web code to web services.

Yes, There is a way to convert complete site in web-services of any version of cakephp.
There is step to follow:
1. Put "Router::parseExtensions("pdf", "json");" this line to your routes.php in config folder before routing rules.
2. Overwrite your "beforeRender" and "Redirect" function in AppController with following:
function beforeRender() {
if (Configure::read("debug") == 0) {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
} else {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
}
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if ($this->Session->check("Message.flash") && is_array($this->Session->read("Message.flash"))) {
foreach ($this->Session->read("Message.flash") as $key => $value) {
$this->set($key, $value);
}
}
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (isset($this->viewVars["params"])) {
unset($this->viewVars["params"]);
}
if (isset($this->viewVars["request"])) {
unset($this->viewVars["request"]);
}
$response = $this->viewVars;
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
}
}
public function redirect($url, $status = NULL, $exit = true) {
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
} else {
parent::redirect($url, $status = NULL, $exit = true);
}
}
Note: If you are checking for Ajax request using that request is ajax or not, and you want to response to your ajax, you have to put your response in "IF" condition
if (!isset($this->params["ext"])) {
// echo json_encode($response);
// echo "success";
// die;
}
Otherwise you can render your view in response.

I would start by reading this
You basically need to modify your routes. You also need to modify (serialize) what your controllers return.

Related

save the record of bulk sms sent into db laravel

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

Get a return value from http.post

My question is the following I have this code here:
$http.post("dologin", data).then(function(resposta)
When I give a console.log (response.data) it returns the following:
string(40) "7f9870111b7c032f6203d144c97b8aa5a3e3f0c5"
{"status":"success","type_user":"secretary"}
I need to get the "status" value. Before I was using the following and it worked fine
if (response.data.status === 'success') {
if (answer.data.type_user === 'teacher') {
$ location.path ('teacher_view');
} else if (response.data.type_user === 'candidate') {
$ location.path ('candidate_view');
} else if (answer.data.type_user === 'secretary') {
$ location.path ('secretaria_view');
}
Now it does not work anymore and when I give console.log (response.data.status); it returns undefined
My backend php
public function do_login(){
$this->load->model('LoginM');
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
$cpf = trim($data->cpf);
$senha = trim($data->senha);
$tipo = trim($data->tipo);
$response = $this->LoginM->do_login($cpf, $senha, $tipo);
if ($response["status"] === "success"){
if ($tipo == 'admin') {
$data = array(
'logged_in' => true,
'cod_user' => $response["cod_user"]
);
$message = array("status"=>"success", "tipo_user"=>"secretaria");
}elseif ($tipo == 'professor') {
$data = array(
'logged_in' => true,
'cod_professor' => $response["cod_professor"]
);
$message = array("status"=>"success", "tipo_user"=>"professor");
}elseif ($tipo == 'candidato') {
$data = array(
'logged_in' => true,
'cod_candidato' => $response["cod_candidato"]
);
$message = array("status"=>"success", "tipo_user"=>"candidato");
}
$this->session->set_userdata($data);
}else{
$message = array("status"=>"error","message"=>"CPF ou senha incorretos");
}
echo json_encode ($message);
}
Test with response from console.log (response.data) and console.log (response.data.status)
Image console.log
Below thing should do the trick:
var state = JSON.parse('{'+res.data.split("{")[1]);
if (state.status === 'success') {
if (state.type_user === 'teacher') {
$ location.path ('teacher_view');
} else if (state.type_user === 'candidate') {
$ location.path ('candidate_view');
} else if (state.type_user === 'secretary') {
$ location.path ('secretaria_view');
}
But, i would strongly suggest you to fix your server response from string which you are getting right now, to the JSON which you were getting earlier

Change called Controller at runtime in Cakephp 3.x

I am trying to halt the action performed by the user if it is not authorized.
So i decided to write a function in AppController and call it in beforeFilter() function like This
public function beforeFilter(Event $event)
{
$this->requestData = $this->request->data;
if (isset($this->request->params['prefix']) && $this->request->params['prefix'] == 'api/v1') {
$this->checkAuthToken(); // My function to check authentication
}
parent::beforeFilter($event);
}
My function to check authentication
public function checkAuthToken()
{
if (empty($this->request->header('AUTH-TOKEN')) || empty($this->requestData['employee_id'])) {
$this->DATA['error'] = 'Access Denied. Contact admin';
$this->DATA['error_code'] = 2;
} else {
$this->loadModel('Employees');
$employee = $this->Employees->get($this->requestData['employee_id']);
if ($employee->status == 'B') {
$this->DATA['error'] = 'Your account is blocked. Contact admin';
$this->DATA['error_code'] = 3;
} else if ($employee->status == 'I') {
$this->DATA['error'] = 'Your account is not active yet. Contact Admin';
$this->DATA['error_code'] = 4;
} else if ($employee->auth_token != $this->request->header('AUTH-TOKEN')) {
$this->DATA['error'] = 'Access Denied! Invalid Request';
$this->DATA['error_code'] = 5;
} else if ($employee['fail_attempts'] > 3) {
$this->DATA['error'] = 'Due to so many attempts you account is blocked! Contact admin';
$this->DATA['error_code'] = 6;
}
}
}
After this in beforeRender
public function beforeRender(Event $event)
{
$debugApi = true;
if (!$debugApi) {
if (isset($this->DATA['error_debug'])) {
$this->log($this->DATA['error_debug']);
$this->DATA['error'] = 'Something went wrong! Please try again';
}
}
$this->set('data', $this->DATA);
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
What is going wrong is if a user request for the API and my authentication gives error then i have to halt calling the controller action and give him error message. Or if i can change the controller to blank one.
Thanks
You can call setAction method if authentication fails. Something like:
if ($this->DATA['error']) {
return $this->setAction('error_method');
}
if ($this->DATA['error']) {
$this->redirect(['controller'=>'test', 'action'=>'/']);
exit;
}

Codeigniter - Array dont work correctly

Whenever I call this function, I get the user_id correctly but the password isnt checked...
Model:
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots',
'users' => 'users'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows()) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id));
return $q;
}
public function check_user_data($user_incredials, $user_password) {
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1){
$q = $this->get('users', array('user_name' => $this->security->xss_clean($user_incredials)));
return $q['user_id'];
}
return FALSE;
}
}
?>
My function-calling at the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index(){
if($this->input->post('user_login')){
var_dump($this->prometheus_model->check_user_data($this->input->post('user_incredials'), $this->input->post('user_password')));
}
$this->load->view('login_index');
}
}
How can i fixx this ?
In your check_user_data() method you are using
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1)
I think (logically) following code
$this->encrypt->decode($user_password)
should be
$this->encrypt->encode($user_password)
because, you are calling num_rows() method and it is
public function num_rows($table, $where = NULL)
{
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
which is actually querying the data base something like, for example,
select * from USERS where user_name = 'heera' and password = decode('abcde12345')
In this case, the password you are trying to match is need to be encrypted using encode (not decode) method, because the user has given you a non-encrypted (plain) password and the password saved in the database is already encrypted, so encode the plain password using encode method before you query the database to match with already encoded passwords.

registration and login in cakephp2.0

Good day! I am now migrating my codes from 1.3 to 2.0 of CakePHP. And I just want to ask, how can I do this code (from 1.3) to 2.0? Here is the code:
function register() {
if(!empty($this->data)) {
// unset unrequired validation rules
unset($this->User->validate['username']['check_user']);
// validate & save data
if($this->User->save($this->data)) {
$this->data['User']['Password'] = md5($this->data['User']['Password']);
$this->User->save($this->data);
// set Flash & redirect
$this->Session->setFlash('You have successfully registered.','default',array('class'=>'flash_good'));
$this->redirect(array('action'=>'login'));
}
else{
//$this->Session->setFlash(__('The user could not be saved.' , true));
//$this->redirect(array('action' => 'register'));
}
}
}
and here is my attempt code that I tried to resolve:
public function register() {
if($this->request->is('post')) {
//unset($this->User->validate['username']['check_user']);
// validate & save data
//$this->data['User']['Password'] = md5($this->data['User']['Password']);
$this->request->data('User.Password', $this->request->data('User.Password'));
// $this->User->save($this->data);
// set Flash & redirect
if($this->User->save($this->request->data)) {
$this->Session->setFlash('You have successfully registered.','default',array('class'=>'flash_good'));
$this->redirect(array('action'=>'login'));
}
else{
//$this->Session->setFlash(__('The user could not be saved.' , true));
//$this->redirect(array('action' => 'register'));
}
}
}
This code is for the login, made in 1.3
function login() {
//echo $_SESSION['User']['auth'];
if(!isset($_SESSION['User']['id'])){
if(!empty($this->data)) {
if(($user = $this->User->validateLogin($this->data['User'])) == true)
{
//print_r(md5($this->data['User']['password']));
$user = $this->User->find('first',array('conditions'=>array('Username'=>$this->data['User']['Username'],'Password'=>md5($this->data['User']['Password']))));
//print_r ($user);
if(!empty($user)){
$_SESSION['User']['id'] = $user['User']['id'];
$_SESSION['User']['name'] = $user['User']['Name'];
$_SESSION['User']['auth'] = $user['User']['auth'];
$this->redirect(array('controller'=>'ads','action'=>'index'));
}else{
$this->Session->setFlash('Username/Password not match');
$this->redirect(array('action'=>'login'));
}
}
}
}
else{
$this->Session->setFlash('Login First.');
$this->redirect(array('controller'=>'ads','action'=>'index'));
}
}
and here is my code in 2.0 and still it is not working also.
public function login() {
if(!($this->Session->read('user_id'))){
if($this->request->is('post')) {
//$user = $this->User->find('first',array('conditions'=>array('Username'=>$this->data['User']['Username'],'Password'=>md5($this->data['User']['Password']))));
if(!empty($user)){
$this->Session->write('user_id',$user['User']['id']);
$this->Session->write('name',$user['User']['Name']);
//$this->Session->write('name',$user['User']['Name']);
$this->redirect(array('controller'=>'ads','action'=>'index'));
}else{
$this->Session->setFlash('Username/Password not match');
$this->redirect(array('action'=>'login'));
}
}
}else{
$this->redirect(array('controller'=>'ads','action'=>'index'));
}
}//end login
I hope that someone respond to my question. Thanks in advance.
I would first try running the migration on your existing code and you might be surprised. here is the link to the upgrade shell:
http://book.cakephp.org/2.0/en/console-and-shells/upgrade-shell.html#upgrade-shell
Try that first.

Resources