How can I validate an nonce passed to another domain and back trough URL? - json

I'm creating an Wordpress nonce on an user api login (domain1) and then send this nonce back to the domain (domain2) where the request came from. From domain2 there is another call made to domain1 for retrieving data, again through api, with the nonce created on login. This nonce is used for verifying this action.
Is this the right thing to do, if correct; Why is the result of wp_verify_nonce false?
My code:
function login() {
$creds = array();
$creds['user_login'] = $_GET["username"];
$creds['user_password'] = $_GET["password"];
$user = wp_signon($creds, false);
if (!is_wp_error($user))
{
$nonce = wp_create_nonce('wp_rest');
$url = "http://hongarijestek2/view/login.html?nonce=" . $nonce;
wp_redirect( $url );
exit;
}
}
function get_visitors( $data ) {
global $wpdb;
$nonce = $_GET['nonce'];
if( wp_verify_nonce( $_GET['nonce'], 'wp-rest' ) ) {
echo "Nonce is ok!";
} else {
echo "Nonce is not ok!";
die();
}
$visitors = $wpdb->get_results("SELECT * FROM cp_visitors_present");
if ( empty( $visitors ) ) {
return null;
}
return $visitors;
}

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

Using AJAX returned JSON encoded data in Codeigniter

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));

Codeigniter session value access

I recently bought project management system, I was trying to add new forms but my forms are not working. I think my problem is the model, I am failing to get a session value (project_code) submitted to the database to make sure that the specific entry is visible to the specific project. The system I bought is ekushey available on codecanyon.
Model
function client_invoicing_add($project_code = '') {
//$data['project_code'] = $project_code;
//$data['project_code'] = $this->session->userdata('project_code');
$data['client_payment_milestone'] = $this->input->post('client_payment_milestone');
$data['client_payment_deliverables'] = $this->input->post('client_payment_deliverables');
$data['client_payment_date'] = $this->input->post('client_payment_date');
$data['client_payment_amount'] = $this->input->post('client_payment_amount');
$data['timestamp'] = strtotime($this->input->post('timestamp'));
$data['client_id'] = $this->session->userdata('login_user_id');
$data['project_code'] = $this->db->get_where('project' , array('project_id' => $project_id))->row()->project_code;
//$data['project_id'] = $this->db->get_where('project' , array('project_code' => $project_code))->row()->project_id;
$this->db->insert('client_invoicing' , $data);
}
Controller
// Client invoicing
function client_invoicing($param1 = '' , $param2 = '' , $param3 = '') {
if ($this->session->userdata('client_login') != 1) {
$this->session->set_userdata('last_page', current_url());
redirect(base_url(), 'refresh');
}
if ($param1 == 'add') {
$this->crud_model->client_invoicing_add($param2); // param2 = project code
}
if ($param1 == 'edit') {
$this->crud_model->client_invoicing_edit($param2); // param2 = client payment id
}
if ($param1 == 'delete') {
$this->crud_model->client_invoicing_delete($param2); // param2 = client payment id
}
}
you can use var_dump($this->session->all_userdata()); to print all session objects. and from them you can check if session is already set or not.
Session array is available through the $_SESSION global:
$name = $_SESSION['name'];
// or:
$name = $this->session->name
// or:
$name = $this->session->userdata('name');
If you want to retrieve all of the existing userdata
$_SESSION
// or:
$this->session->userdata();
Note : The userdata() method returns NULL if the item you are trying
to access does not exist.

UPS php api - create order

I am trying to integrate UPS php api to generate online order for sending stuff.
I am able to validate address and get rates for stuff transfer but i am not able to find any solution for generating order and labels for courir, can somebody help me in getting that.
UPS Developer Kit and API is quite a good reference to all API related development, including in PHP. It can be downloaded from here: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
Here is some code example, for the PHP ship accept code (from the API zip):
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$accessSchemaFile = " Add AccessRequest Schema File";
$requestSchemaFile = " Add ShipAcceptRequest Schema File";
$responseSchemaFile = "Add ShipAcceptResponse Schema File";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
try
{
//create AccessRequest data object
$das = SDO_DAS_XML::create("$accessSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->AccessLicenseNumber=$access;
$root->UserId=$userid;
$root->Password=$passwd;
$security = $das->saveString($doc);
//create ShipAcceptRequest data oject
$das = SDO_DAS_XML::create("$requestSchemaFile");
$requestDO = $das->createDataObject('','RequestType');
$requestDO->RequestAction='01';
//$requestDO->RequestOption='01';
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Request = $requestDO;
$root->ShipmentDigest = 'test-Invalid-digest';
$request = $das->saveString($doc);
//create Post request
$form = array
(
'http' => array
(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => "$security$request"
)
);
//print form request
print_r($form);
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
if(!$browser)
{
throw new Exception("Connection failed.");
}
//get response
$response = stream_get_contents($browser);
fclose($browser);
if($response == false)
{
throw new Exception("Bad data.");
}
else
{
//save request and response to file
$fw = fopen($outputFileName,'w');
fwrite($fw , "Response: \n" . $response . "\n");
fclose($fw);
//get response status
$resp = new SimpleXMLElement($response);
echo $resp->Response->ResponseStatusDescription . "\n";
}
}
catch(SDOException $sdo)
{
echo $sdo;
}
catch(Exception $ex)
{
echo $ex;
}
?>

Facebook php Oauth is not working

I'm new to facebook apps and php in general, and I have a bit of a problem. I cannot get OAuth to work correctly with my application. When you go the application itself, it does not redirect to the oAuth dialog. It merely displays a blank page that does nothing. If anyone can help me with this, I really need it haha. Thanks!
So far, my code is as follows:
<?php
include_once ('santatree/facebook.php');
$app_id = '276853929000834';
$application_secret = 'e3a12b11221f3fef1e06952e15fdc8e4';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
?><?
if ($facebook->getSession())
{
$user = $facebook->getUser();
}
else
{
$loginUrl = "https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834
&redirect_uri=http://apps.facebook.com/digitalsanta/&scope=user_photos";
header("Location: https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834 &redirect_uri=http://apps.facebook.com/digitalsanta/ &scope=user_photos");
echo '';
}
I do my redirects based on the session token.
This assumes that you will be using the most recent php-sdk 3.1.1 and have Oauth2 enabled in your app settings.
SAMPLE HERE: login / out url is in footer of plugin. http://apps.facebook.com/anotherfeed/TimeLineFeed.php?ref=facebook-stackoverflow
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $_SESSION['fb_135669679827333_access_token'];
if (!$access_token) {
echo '<script>';
echo 'top.location.href = "'.loginUrl.'";';
echo '</script>';
} else {
echo 'Logout';
}
?>
https://developers.facebook.com/apps to edit your app.
If you do not have an app you will need to create one.
You will also need to set up the canvas and secure canvas urls to avoid errors.
You only defined the variable $loginUrl, but you haven't redirect user to go to the URL. Consider using
header("Location: $loginUrl");
to forward your user if you haven't sent your header yet.