i was trying to check api on postman using phalcon and i got respon 400 - phalcon

I got this error when i try to check using postman... u can see the error below
i got this massage
"code":400,"response":"Failed","message":"Your username is not registered. Please register a new user now!","data":null
public function loginAction()
{
$this->view->disable();
$credentials = $this->request->getJsonRawBody();
$response = new Response();
$username = $credentials->username;
$password = $credentials->password;
// $user = User::findFirst("user_username = '$username'");
$user = User::findFirst([
'conditions' => 'username = :username:',
'bind' => [
'username' => $username
]
]);
if($user !== NULL) {
$checkPassword = $this->security->checkHash($password, $user->password);
if($checkPassword === true) {
$this->session->set('username', [
'id' => $username->id,
'username' => $user->username,
]);

Related

Problem to upload file with from-param in Laravel 8 external api with guzzle or HTTP client

I am using Mirakl api. I faced an issue with the file upload with form-peram in Laravel 8 external api with guzzle or HTTP client.I got 400 Bad Request.The api expects file with from-param like this
{
"order_documents": [{
"file_name": String,
"type_code": String
}]
}
The documentation of my endpoint can be found from this link (http://185.29.149.41/eci/mir/doc/api/OR74.html) and here is my codes --
public function upload_order(Request $request)
{
$order_id = $request->order_id;
if ($files = $request->file('files')) {
$name = $files->getClientOriginalName();
Storage::disk('invoice')->put($name, file_get_contents($files->getRealPath()));
$path = Storage::disk('invoice')->path($name);
}
$file['order_documents'][] = [
'file_name' => $name,
'type_code' => $request->type_code,
];
$json = json_encode($file);
$data = [
['name' => 'order_documents','contents' => $json],
];
$data[] = [
'name' => 'files',
'contents' => mb_convert_encoding($path, 'UTF-8', 'UTF-8'),
'filename' => $name,
];
$body['multipart'] = $data;
$configApi = $this->configApi($this->getMarketplaceID($request->marketplace), auth()->user()->id);
$url = $configApi['url'].'/api/orders/'.$order_id.'/documents';
$client = new Client(['verify' => false]);
$response = $client->request(
'POST',
$url,
[
'multipart' => $data,
'headers' => $configApi['headers']
]);
return json_decode($response->getBody(), true);
}

get data value from jsonResponse Laravel 8

I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?
I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way

How can i set expire time in otp in laravel8?

When i am trying to expiry otp, is not working but i do not know what i am doing wrong. I set expiry time with Carbon but still not working. What should i do?. It needs config in app/config or something?
This is a part of my controller code
if(!$device_serial_number)
{
return ('error');
} else {
$otp = rand(100000,999999);
// Cache::put([$otp], now()->addSeconds(20));
$otp_expires_time = Carbon::now()->addSeconds(20);
Cache::put(['otp_expires_time'], $otp_expires_time);
Log::info("otp = ".$otp);
$user = User::where('phonenumber', $request->phonenumber)->update(['otp' => $otp]);
$token = auth()->user()->createToken('Laravel Password Grant Client')->accessToken;
// Log::info($request);
// $user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')]])->first();
return response()->json(array(
'otp_expires_at'=> $otp_expires_time,
'otp' => $otp,
'token' => $token));
This is a part of my middleware code
Log::info($request);
$user = User::where([['phonenumber', '=', request('phonenumber')],['otp','=', request('otp')],['otp_expires_time', '=', request('otp_expires_time')]])->first();
$otp_expires_time = Carbon::now()->addSeconds(20);
if($user)
{
if(!$otp_expires_time > Carbon::now())
{
return response('the time expired');
} else {
Auth::login($user, true);
return response()->json(array(
'message' => 'You are logged in',
['user' => auth()->user()]));
return response('You are logged in');
$otp = rand(1000,9999);
Cache::put([$otp], now()->addSeconds(10));
$otp_expires_time = Carbon::now('Asia/Kolkata')->addSeconds(10);
Log::info("otp = ".$otp);
Log::info("otp_expires_time = ".$otp_expires_time);
Cache::put('otp_expires_time', $otp_expires_time);
$user = User::where('email','=',$request->email)->update(['otp' => $otp]);
$user = User::where('email','=',$request->email)->update(['otp_expires_time' => $otp_expires_time]);

How do I send multiple query parameters to the api?

I'm calling the API to get a list of shipments but I can't seem to page through the results.
The API call is successful with only one query parameter but when I call it with two query parameters, I get the error "The signature is invalid. Verify and try again". I'm including my test code below.
<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = 'htj8ze6ntr0mz1s4hjxrqeicia8rxgt4';
$consumerSecret = 'djjzdwfgbbr7ganlkv01qr6p3l7ptvfe';
$accessToken = '60o0mfrvqnjvin7tjuqsv37arijrqe9e';
$accessTokenSecret = 'caq9wfdx99zaygwgbhw91i9imj89p4zb';
$method = 'GET';
/* test 1 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria'=>'all'];
/* test 2 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria[pageSize]'=>'10'];
/* test 3 FAIL "The signature is invalid. Verify and try again" */
$url = 'http://localhost/rest/V1/shipments/';
$qs = ['searchCriteria[pageSize]'=>'10', 'searchCriteria[currentPage]'=>'1'];
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data = array_merge($data, $qs);
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url .'?' .http_build_query($qs),
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
echo($result);
The code includes three tests.
If I uncomment test 1 and comment test 2 and 3, the code works properly and I get a list of shipments.
If I uncomment test 2 and comment test 1 and 3, the code works properly and I get a list of shipments.
If I run the code as is, I get the the message "The signature is invalid. Verify and try again."
I'm running Magento ver. 2.3.2
The trick is to sort the parameters. I have some client code anyone is interested.
<?php
function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha1', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
function recursive_sort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recursive_sort($value);
}
return ksort($array);
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
$consumerKey = 'htj8ze6ntr0mz1s4hjxrqeicia8rxgt4';
$consumerSecret = 'djjzdwfgbbr7ganlkv01qr6p3l7ptvfe';
$accessToken = '60o0mfrvqnjvin7tjuqsv37arijrqe9e';
$accessTokenSecret = 'caq9wfdx99zaygwgbhw91i9imj89p4zb';
$method = 'GET';
/* test 1 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria'=>'all'];
/* test 2 PASS */
//$url = 'http://localhost/rest/V1/shipments/';
//$qs = ['searchCriteria[pageSize]'=>'10'];
/* test 3 FAIL "The signature is invalid. Verify and try again" */
$url = 'http://localhost/rest/V1/shipments/';
$qs = ['searchCriteria'=>['pageSize'=>10,'currentPage'=>1]];
$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data = array_merge($data, $qs);
recursive_sort($data);
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url .'?' .http_build_query($qs),
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
curl_close($curl);
echo($result);
Though this question is old, I want to post the answer for future cases.
The code in the question is good, and it helped me a lot.
It is needed to sort parameters by key. Also, please consider that the searchCriteria is a multidimensional array. So, the array must be sorted by key recursively.

Change Password in hashed function in laravel 5.6

I want to change my password which is been hashed while saving.
How can i change the password?
'password' => Hash::make($data->password).
My Controller
$request->validate([
'oldpass' => 'required',
'password' => 'required|alphaNum|min:6',
'password_confirmation' => 'required|same:newpass',
]);
$id = $request->id;
$users = Auth::user()->whereId($id)->get();
foreach ($users as $user) {
if ($oldpass == $user->password) {
$user->update([
'password' => Hash::make($request->newpass)
]);
return view('\balance');
} else {
return 'error';
}
}
You should use Hash::check($old_password, $hashed_password), something like this:
public function passwordChange(Request $request, User $user_name) {
// find the loggedin user
$user = User::find(Auth::user()->id);
// validate rules
$validator = Validator::make($request->all(), [
'old_password' => 'required|min:6',
'password' => 'required_with:password_confirmation|required|min:6',
'password_confirmation' => 'confirmed|required|min:6',
]);
// what to do if validator fails
if ($validator->fails()) {
return redirect($user->user_name . '/settings')->withErrors($validator)->withInput();
} else {
$old_password = $request->input('old_password');
$new_password = $request->input('password');
$hashed_password = Auth::user()->password;
// checking the old pass with new one
if (Hash::check($old_password, $hashed_password)) {
$user->update([
'password'=> Hash::make($new_password)
]);
return redirect($user->user_name . '/settings')->with('success', 'Your Password updated.');
} else {
return redirect($user->user_name . '/settings')->with('success', 'Your Old password is wrong!');
}
}
}
Please also notice 'password' => 'required_with:password_confirmation and 'password_confirmation' => 'required|same:newpass' on validator. Hope it helps.