I am working on an application using Cakephp on the server side and PhoneGap at the client Side, with JSON as a intermediate to access the server side.
Now, I am working specifically on a login form where the user needs to enter his/her username and password. I put in my controller the following:
public function api_login() {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization");
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
'password' => $this->request->data['password']
)
));
if (count($arrUser) > 0 ) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
}
else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
and in the client side, I am retrieving what JSON encoded as follows:
<script>
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
$username = $("#form-username").val();
$password = $("#form-password").val();
$.ajax({
url : "http://localhost/teslaphonegap_cakephp/" + 'login.json',
cache : false,
data : {
'username' : $username,
'password' : $password },
dataType : 'json',
type : 'POST',
success : function(result) {
if(result.status=="SUCCESS"){
alert("success");
console.log(result);
}else{
alert("username or pass are wrong");
console.log(result);
} },
error : function(xhr, status, err) {
alert("ERROR");
}
});
});
});
</script>
and in my Model I used the beforeSave() in order to hash the passwords before they get added at the very beginning in the Database:
public function beforeSave($options = array()) {
$value=$this->data['User']['password'];
$encrypted = Security::encrypt($value, Configure::read('Security.cipherCriptKey'));
$this->data['User']['password'] = $encrypted;
return true;
}
Now, when I try to login it always returns the error message because it compares a value that is unhashed with other values that are already hashed in my Database. How can I solve this issue? I used the afterFind() but it didn't work:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['User']['password'])){
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
}
return $results;
}
}
-- EDIT
and in my core.php I used the following:
Configure::write('Security.cipherCriptKey','su0HKssPmdbwgK6LdQLqzp0Y7zOmyaTI');
First of all, your afterFind() callback won't work as expected.
The line
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
should be written as
$results[$key]['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
However, changing this won't fix your problem. If you search the database for a record with a password matching $this->request->data['password'], it will return no results. Note that the password in the database is hashed.
You have to fetch the record from table users that matches $this->request->data['username'], decrypt the value of field password and compare it against $this->request->data['password'].
Decryption is already taken care by afterFind(), so your code could be written as follows:
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('first',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
)
));
if ($this->request->data['password'] == $arrUser['User']['password']) {
$this->Session->write('Auth.User',$arrUser['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser['User']['id'] );
//rest of your code
Related
So. I am trying create a fields validation using ajax. I have created the class "validate-field" on the fields where is a necessary a validation.
One Field is email_addres and another is taxvat. On my controller I just created thea action "validate" and then I am trying get the Field ID and Field Value.
Follow the codes below:
-the jQuery:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".continuar").on("click", function(){
url = "<?php echo Mage::getUrl('awmajax/ajax/validar')?>";
jQuery(".required-entry").each(function(){
if(jQuery(this).val() == ""){
jQuery(this).addClass("validation-failed");
}
else {
jQuery(this).removeClass("validation-failed");
}
});
jQuery(".validate-field").each(function(){
fieldName = jQuery(this).attr('id');
fieldValue = jQuery(this).val();
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
data: ({
field : fieldName,
value : fieldValue
}),
success: function(result){
console.log(result);
}
});
});
});
});
</script>
and the php:
public function validarAction(){
$params = $this->getRequest()->getParams();
if($params['field'] == 'taxvat'){
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if($validacao == false){
$resultTaxvat = array(
"response" => "Taxvat is not valid",
"field" => $params['field']
);
}
$this->getResponse()->setBody(json_encode($resultTaxvat));
}
if($params['field'] = 'email_address'){
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
$resultEmail = array(
"response" => $validacaoEmail, //Type a valid Email
"field" => $params['field']
);
$this->getResponse()->setBody(json_encode($resultEmail));
}
}
What is the problem:
I get always just the email response on the second "If".
Any help is welcome.
Cheers
your second IF statement is passing a value and not comparing... I think you were supposed to write if ($params['field'] === 'email_address')
regarding your issue, try this:
public function validarAction()
{
$params = $this->getRequest()->getParams();
$error = false;
$errors = [];
if ($params['field'] == 'taxvat') {
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if (!$validacao) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Taxvat is not valid',
];
}
}
if ($params['field'] === 'email_address') {
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
if (!$$validacaoEmail) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Type a valid Email',
];
}
}
$this->getResponse()->setBody(json_encode([
'error' => $error,
'errors' => $errors
]));
}
...tyr to use a loop construct to refactor this. as this may result in a lot of IF statements if you are going to validate a lot of fields.
EDIT:
Changed $result to $errors and the JSON index status to error. It would be easier to iterate with the updated code on your JS.
I want to check data in database through ajax in codeigniter how can get check name already exist through ajax
controller
public function insert(){
$user = array('Name' => $this->input->post('name'),
'Cnic' => $this->input->post('cnic'),
'Phone' => $this->input->post('phone'),
'Address' => $this->input->post('address'),
);
$this->load->model('suppliermodel');
if($this->suppliermodel->checkData($user['Name'])){
if ($this->session->userdata('user_id'))
$detail = 'Already exist';
$this->load->view('admin/includes/header');
$this->load->view('admin/includes/sidemenu');
$this->load->view('admin/add_supplier',['exist'=>$detail]);
$this->load->view('admin/includes/footer');
$this->load->view('admin/includes/add_supplier_footer');
}
else{
$this->suppliermodel->add($user);
}
}
model
public function checkData()
{
$name = $this->input->post('name');
$this->db->select('*');
$this->db->where('Name', $name);
$this->db->from('suppliers');
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
}
else{
return $query->result();
return false;
}
}
what is ajax code and controller function
How about this?
Controller
public function insert(){
// set a rule that make the Name field is unique by 'set_rules'
$this->form_validation->set_rules('Name', 'Name Field', 'required|is_unique[suppliers.name]');
//$this->form_validation->set_rules('[Other Field]', '[Field Name to Display]', '[Restriction]');
// if the field cannot pass the rule
if ($this->form_validation->run() === FALSE) {
$errors = array();
foreach ($this->input->post() as $key => $value) {
// Add the error message for this field
$errors[$key] = strip_tags(form_error($key));
}
// Clear the empty fields (correct)
$response['errors'] = array_filter($errors);
$response['status'] = false;
}
else {
// otherwise, call the model
$result = $this->suppliermodel->add($user);
if ( $result ) {
$response['status'] = true;
}
}
echo json_encode($response);
}
JavaScript
$.ajax({
url: '//localhost/insert',
data: {
Name: $('input[name=Name]').val(),
Cnic: $('input[name=Cnic]').val(),
Phone: $('input[name=Phone]').val(),
Address: $('input[name=Address]').val()
},
dataType: 'JSON',
type: 'POST',
error: function(xhr) {
alert('request failed!');
},
success: function(response) {
var response = $.parseJSON(JSON.stringify(response));
if (response.status != true) {
$.each(response.errors, function(field, i) {
alert( field+ ' errors with ' + i)
});
}
else {
alert('success!');
}
}
});
Use is_unique[table.fieldToCompare] to make the field is always unique.
Wish it helps.
set_rules restrictions, see the Codeigniter User Guide Form validation
If fails, the controller would return a set of JSON, with field and error message. Then you can handle it in $.ajax's success.
Note: I ended up finding out that the problem was caused by a syntax error on the controller itself.
Ok so, I'm using Laravel to develop a platform.
I have a form that allows the user to register a domain. This form is submited through ajax to "[my domain]/thedomains/create". Here is the code that does so:
$("#btn_doms_create_submit").click(function (){
$.ajax({
type: 'GET',
url: "/thedomains/create",
data: { _token : $("input[name=\"_token\"]").val(),
domain : $("input[name=\"create_dom\"]").val(),
field_ip : $("input[name=\"create_ip\"]").val(),
obs : $("textarea[name=\"create_obs\"]").val(),
active : $("input[name=\"create_active\"]").is(":checked")+"",
itld : $("input[name=\"create_itld\"]").is(":checked")+"" },
dataType: 'json',//returned data
success: function(data){
if (data["errors"] == "")
{
toastr.success(data.message);
$("#doms_create").modal("hide");
updateTable();
}
else
{
var txtError = "";
for (error in data.errors) {
txtError += "<li>" + data.errors[error] + "</li>";
}
toastr.warning(data.message + "<ul>" + txtError + "</ul>");
if (data.errors.domain != null) {
$("#div_create_dom").attr("class","form-group has-error");
}
if (data.errors.field_ip != null) {
$("#div_create_ip").attr("class","form-group has-error");
}
}
}
});
});
The code behind "/thedomains/create" is
public function create(Request $request) {
$return_val = [ "message" => trans("system.dom_succ", ["name" => $request->dom]),
"errors" => "" ];
$validator = Validator::make($request->all(), [
"domain" => "required|max:255|url",
"field_ip" => "max:255"
],[
"domain.required" => trans("system.val_dom_required"),
"domain.max" => trans("system.val_dom_max"),
"domain.url" => trans("system.val_dom_url")
]);
if (!$validator->fails()) {
$dom = new Doms;
$dom->name = $request->domain;
$dom->ip = $request->ip;
$dom->obs = $request->obs;
if ($request->active == "true")
$dom->status = true;
else
$dom->status = false;
if ($request->itld == "true")
$dom->is_top_level_domain = true;
else
$dom->is_top_level_domain = false;
} else {
$return_val["message"] = trans("system.note_errors");
$return_val["errors"] = $validator->errors();
}
return json_encode($return_val);
}
As you can see, I have a validation to verify that all the required data is present and valid, according to the needed standards.
The problem is: When I submit this form with some invalid domain or with no domain at all, the verification occurs naturally, the return is given, etc. But when I have a valid domain, the validation throughs the following error on my browser's (chrome) console:
GET [my domain]/thedomains/create?_token=2vsOrtkcWGid5Ex2HegtY3Fw2E…aE&domain=http%3A%2F%2Ftecnosece.com&field_ip=&obs=&active=true&itld=false 403 (Forbidden)
Idk why this happens. I've already changed the route from "domains" to "thedomains", thinking there could be some kind of blocking from my host, but that didn't solve the problem.
Any idea of what's happening?
Edit:
As requested, here is my routes portion for "/thedomains":
Route::group(['prefix' => 'thedomains'], function () {
Route::get("/",function () {
return view("doms");
});
Route::get("/all", "DomsController#getAll");
Route::post("/get", "DomsController#get");
Route::get("/create", "DomsController#create");
Route::post("/edit", "DomsController#edit");
Route::post("/del", "DomsController#del");
Route::get("/search", "DomsController#search");
Route::post("/migrate", "DomsController#migrate");
});
I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);
I'm new to AngularJS but I've already done a lot of things.
I did a $http.post, that worked like a charm.
Heres the Angular code
$scope.login = function(user, pass) {
$scope.bIsVisible = false;
var dados = {"user": user, "pass": pass};
console.log(dados);
$http.post('http://base.corretoconcursos.com.br/cadernos/index.php/manageUsers/login', dados)
.success(function(data, status, headers, config) {
if (data == false)
{
$scope.isLogged = false;
$scope.bIsVisible = true;
} else {
$scope.isLogged = true;
$scope.userData = data;
console.log(data);
}
})
.error(function(data, status, headers, config) {
alert('failed');
$scope.bIsVisible = true;
});
And the manageUsers/login function
function login()
{
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
$username = $data->user;
$password = md5($data->pass);
$datafrombase = $this->UsersModel->getUser(array(
'user' => $username,
'pass' => $password
));
if ($datafrombase != null) {
$user = array(
'user' => $datafrombase['user'],
'type' => $datafrombase['type'],
'logged_in' => true
);
$this->session->set_userdata($user);
}
if ($datafrombase != null)
print_r(json_encode($datafrombase));
else
return false;
}
Alright. It's working. I retrieve some data from database and OK. The real problem is when I do a $http.get and simply by doing a request on database or not, it doesn't send back the data that I want, when I do the console.log(data), it shows me an entirely HTML page, in fact, the one that is displaying. I'm getting a 200 status OK, but, a HTML page is coming. Don't know why.
Heres the Angular code
$scope.setLoggedOn = function(on) {
if (on) {
$http.get('http://base.corretoconcursos.com.br/cadernos/index.php/manageUsers/retrieveLogin')
.success(function(data, status) {
console.log(data);
})
.error(function(data, status, headers, config) {
alert('failed');
});
}
else
$scope.isLogged = false;
};
And heres the PHP code function I'm retrieving.
function retrieveLogin()
{
$user = null;
$user = array(
'user' => $this->session->userdata('user'),
'type' => $this->session->userdata('type'),
'logged_in' => true
);
print_r(json_encode($user));
}
I'm stuck. I've even tried doing just a 'return true'; inside the php function, return 'string'; but nothing will work. What so wrong am I doing?
Figured it out. If you're using CodeIgniter along sessions; and checking in the constructor if people are logged in to let them see that page or not; when you do the $http.get it will run the constructor and run that condition, and if they cannot see that page, even if you're just doing a request from that controller via AJAX, it won't let you make the request.
I thought that the $http.get would only request the function (i-e, verifyUserInDatabase();), and give the data, but turns out, it doesn't.
Thanks for the help.
$datafrombase is never set in retrieveLogin() so angular isn't going to receive anything.