Passing Multiple Value For PHP API Function - php

I am new in PHP and working to modify one API. Its built with Laravel Framework. I have API function like below in my controller.
public function DeleteOneMail(Request $request)
{
$uid = $request->uid;
if (\Request::is('api/*')) {
if ($request->has('key')) {
if (in_array($request->input('key'), explode(',', env('API_KEY')))) {
if ($uid == '') {
return response()->make('Please Enter UID', 401);
} else {
$client = Client::account('default');
$client->connect();
$inbox = $client->getFolder('INBOX');
$message = $inbox->getMessage($uid);
if ($message) {
return response(['success' => 1], 200);
} else {
return response(['success' => 0, 'message' => 'No Data Found'], 200);
}
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
}
}
I am calling API like below
https://example.com/api/delete-one-mail?key=2221212&uid=214
Its working fine without any issue. Now I want pass multiple uid with request and so I can process that uid one by one with my api function. I am not getting idea how I can pass arrary and process it. Let me know if any expert can help me for solve my puzzle. Thanks!

Your can pass an array like this
https://example.com/api/delete-one-mail?key=2221212&uid[]=214&uid[]=111&uid[]=222
$request->uid should be an array but you can make sure (if anyone use the old url with ony one uid) by doing
$uids = Arr::wrap($request->uid);

If you want to send an array by GET request just use []
https://example.com/api/delete-one-mail?key=2221212&uid[]=1&uid[]=2
In your controller you will get an array
$uid = $request->uid;
dd($uid);
As a result you will get
[1, 2]

Related

Laravel View:make() and view() returns null over API but works fine on web

I have a project which prepares PDF documents. I want to have several servers that prepares the html for the PDFs over an API. I therefore have a function in the remote server as shown below:
public function getData(Request $request)
{
$data = $request->all();
$data['scheme'] = null;
// return $data['scheme'];
$credentials = $data['credentials'];
$bot = Bot::where("username", $credentials['username'])->first();
if (!$bot || !Hash::check($credentials['password'], $bot->password)) {
return response()->json([
"message" => "Failed",
], 401);
}
view()->share($data);
if ($data['type'] == 'download') {
return (string) \View::make('pdfs.myPDF');
} else {
return view('pdfs.previewPDF');
}
}
Unfortunately it returns null yet when I call that function over normal web session it works fine. So my question is, does it mean you cannot load a view over API?

How to resolve passing of same USER_ID for every post request in laravel JWT auth

I am working with Laravel, Vue.js and I am currently using JWT auth for user authentication. I have implemented function for my buttons where I click the up button the vote increases and when I click the down it decreases but the problem is that if I switch user and login with another user I am still able do decrement another user's vote. The user_id in database is still the same and is not updated with new request. I am unable to find the problem please help as I am new to these technologies.
I have tried passing the id manually and then it works sometimes. I guess it is some problem with the authentication or my passing of user_id
this is my vote code:
public function vote(Request $request, $id) {
$issue = Issue::findOrFail($id);
$issueVotes = new \App\IssueVotes();
$issueVotes->user_id = auth()->id();
$issueVotes->issue_id = $request->issue_id;
if($request->vote_type =='up') {
$already_voted = \App\IssueVotes::where('user_id', auth()->id())->where('issue_id', $request->issue_id)->where('vote_type', $request->vote_type)->first();
if(!$already_voted) {
$issue->increment('votes');
$issueVotes->vote_type = $request->vote_type;
$issueVotes->save();
}
} elseif ($request->vote_type =='down') {
$voted_up = \App\IssueVotes::where('user_id', auth()->id())->where('issue_id', $request->issue_id)->where('vote_type', 'up')->first();
if($voted_up) {
#$delete_down = \App\IssueVotes::where('user_id', auth()->id())->where('issue_id', $request->issue_id)->where('vote_type', 'up')->delete();
$issue->decrement('votes');
$issueVotes->vote_type = 'down';
// $issueVotes->save();
}
}
return response()->json($request->post_id, 200);
}
And my JWT auth login code is:
public function login(Request $request)
{
$credentials = $request->json()->all();
try{
if (!$token = JWTAuth::attempt($credentials)){
return response()->json(['error'=>'invalid_credentials'], 400);
}
}catch(JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500); // something went wrong whilst attempting to encode the token
}
return response()->json(compact('token'));
}
public function getAuthenticatedUser()
{
try{
if(!$user = JWTAuth::parseToken()->authenticate()){
return response()->json(['user_not_found'], 404);
}
}catch(Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
return response()->json(['token_expired'], $e->getStatusCode());
}catch(Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
return response()->json(['token_invalid'], $e->getStatusCode());
}catch(Tymon\JWTAuth\Exceptions\JWTException $e){
return response()->json(['token_absent'], $e->getStatusCode());
}
return $user;
}
What I am trying to achieve is that only the user who is logged in can change the vote value but of the posts on which he has given votes not on every post.
Here is the screenshot of my database where I switched the user but the user_id remains the same

strpos() expects parameter 1 to be string, object given laravel 5.5

This is my code:
public function getLists(Request $request)
{
$user = $request->user()->id;
$apikey = DB::table('apikey')->where('api_key', '=', $user);
if($apikey){
$mc = new MailChimp($apikey);
$mailchimp_ping = $mc->get('lists',['fields' =>
'lists.id,lists.name']);
return Response::json($mailchimp_ping, 200);
}
else
{
$errorResponse = [
'message' => 'Lists not found!',
'error' => '401'
];
return Response::json( $errorResponse);
}
}
I am trying to get mailchimp list based on logged in user id where i am doing wrong? is my where clause expects something else?
Any help would be highly appreciated!
Use the value() method to execute the query and get the key. For example, if a column with key is called apikey:
$apikey = DB::table('apikey')->where('api_key', $user)->value('apikey');
In my case this error came up when changed this:
Route::view('/report', '/main_pages/orders_parts/report')->name('guzorishi_order_1');
to
Route::get('/report/{order_id}', function ($order_id) {... })->name('guzorishi_order_1');
but forgot Route::view one
rename to Route::get

Sync Token Exception google-api-client-service php people Service

I have a problem with the Google API. I need to get all the contacts of a user in my application, however I don't want to load all the data each time, because I store the data in my database.
It's why I want to use the Sync Token functionality which let's us get only data who has been changed since our last query.
For this i Use the Google APIs PHP client library.
I wrote my code and it throws an exception (Google_Service_Exception) which explains that my Sync Token is not valid anymore, so I decided to use a try/catch system to reset syncToken if it is not valid.
My problem is each time i made the request I go in the catch (the google_service_exception) is raised even if my token is valid.
I store the token in my database so I tested it in the API explorer here: https://developers.google.com/people/api/rest/v1/people.connections/list and it work fine, so I don't understand why my application doesn't work properly.
Here's my code:
$personFields = 'metadata,names,addresses,biographies,birthdays,emailAddresses,genders,memberships,organizations,phoneNumbers';
$user = $this->get('security.token_storage')->getToken()->getUser();
$syncToken = $user->getContactSyncToken();
$nextPagetoken = '';
$contactData = array();
$people_service = new \Google_Service_PeopleService($client);
do {
try {
$data = $people_service->people_connections->listPeopleConnections(
'people/me',
array(
'personFields' => $personFields,
'requestSyncToken' => true,
'syncToken' => $syncToken,
'pageToken' => $nextPagetoken,
)
);
}catch (\Google_Service_Exception $e){
$data = $people_service->people_connections->listPeopleConnections(
'people/me',
array(
'personFields' => $personFields,
'requestSyncToken' => true,
'syncToken' => '',
'pageToken' => $nextPagetoken,
)
);
}finally{
$syncToken = $data->getNextSyncToken();
$nextPagetoken = $data->getNextPageToken();
if (count($data->getConnections()) != 0) {
$contactData[] = $data->getConnections();
}
}
}while ($nextPagetoken !== null);
$user->setContactSyncToken($syncToken);
$this->getDoctrine()->getManager()->flush();
return $contactData;
Thank you for your help and sorry for my english i'm not a native and not very good at it.
Sorry i found the problem, in my User class i had:
public function getContactSyncToken()
{
if($token = $this->contactSyncToken !== null){
return $token;
}else{
return '';
}
}
And it always return ' ', now it works with:
public function getContactSyncToken()
{
$token = $this->contactSyncToken;
if($token !== null){
return $token;
}else{
return '';
}
}

Laravel trigger route after filter

I built a filter which checks some keys and ids sent and then gives the go or no go. The problem is that a filter in Laravel should return a string while I just wnat to return a boolean and let it trigger the intended route.
Filter:
Route::filter('api_checkauth', function($route)
{
//user"ok"
$user_id = (int) $route->getParameter('user_id');
$sig = $route->getParameter('sig');
$user = User::find($user_id);
if($user) {
//user email
$email = $user->email;
//user api key
$api_key = $user->api_key;
//recreate signature
$_sig = hash_hmac("sha256", $email . $user_id, $api_key);
if($_sig === $sig) {
return Response::json(array("message"=>"Request Ok"),200);
} else {
return Response::json(array("message"=>"Request Bad"),400);
}
} else {
return Response::json(array("message"=>"Request not authorized"),401);
}
});
Routes:
// Route group for API versioning
Route::group(array('prefix' => 'api/v1', 'before' => 'api_checkauth'), function()
{
Route::get('/pim/{user_id}/{sig}', 'MoreOrLessController#index');
});
So the question is, how can I still trigger the route which i defined in the group? Because what happens now is a that only a message is printed instead of a controller method that should be triggered.
Thanks
In Laravel, if a filter returns a response, that response is considered the response to the request and the route is not executed. So, in order for the route to be executed return a response only if the user is not authorized.
if($user) {
$email = $user->email;
$api_key = $user->api_key;
$_sig = hash_hmac("sha256", $email . $user_id, $api_key);
if($_sig !== $sig) {
return Response::json(array("message"=>"Request Bad"),400);
}
} else {
return Response::json(array("message"=>"Request not authorized"),401);
}
The answer is that you're returning your 200 HTTP response in the wrong place.
As you noted, you will always get a JSON string response from the filter no matter what happens, due to the structure of your if/else statement.
Instead of returning your 200 response in the filter, handle that in your MoreOrLessController#index action. So, to clarify, *do not return ANYTHING in the filter when you confirm $_sig === $sig*.
That should do it!

Categories