How to set and get Cookies in Cakephp 3.5 - cakephp-3.4

I have read the Cakephp documentation but it doesn't working well.
Here is my code,
$this->response = $this->response->withCookie('remember_me', [
'value' => 'yes',
'path' => '/',
'httpOnly' => true,
'secure' => false,
'expire' => strtotime('+1 year')
]);
$rememberMe = $this->request->getCookie('remember_me');

Please look at the documentation. You will find it in the following link:
https://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Http\Cookie\CookieCollection
To create a cookie
use Cake\Http\Cookie\Cookie;
$cookie = new Cookie(
'remember_me', // name
1, // value
new DateTime('+1 year'), // expiration time, if applicable
'/', // path, if applicable
'example.com', // domain, if applicable
false, // secure only?
true // http only ? );
Now add the cookie in the cookie collection:
use Cake\Http\Cookie\CookieCollection;
$cookies = new CookieCollection([$cookie]);//To create new collection
$cookies = $cookies->add($cookie);//to add in existing collection
Now read cookie this way.
$cookie = $cookies->get('remember_me');
Hope you will find it's working.
Here should mention an important point: Cookie writing and reading must be two separate http request.

Related

How to use Wasabi (AmazonS3) in sabre/dav?

I am building a WebDAV server using sabre/dav, I want to create a WebDAV server file storage location in Wasabi which is compatible with AmazonS3, I did some research and found something that looks like AWS.php but I don't know how to use it. If anyone knows how to do this specifically, please respond.
What we tried:
・Download s3dav (https://github.com/audionamix/s3dav) and install the file.
・Server.php was written as follows
<?php
use Sabre\DAV;
use Aws\S3\S3Client;
// The autoloader
require 'vendor/autoload.php';
$raw_credentials = array(
'credentials' => array(
'key' => '<insert-access-key>',
'secret' => '<insert-secret-key>'
),
//'profile' => 'wasabi',
'endpoint' => 'https://s3.wasabisys.com',
'region' => 'us-east-1',
'version' => 'latest',
'use_path_style_endpoint' => true,
'use_path_style' => true,
'use_ssl' => true,
'port' => 443,
'hostname' => 's3.wasabisys.com',
'bucket' => '<bucket-name>',
);
// establish an S3 Client.
$s3 = S3Client::factory($raw_credentials);
// Now we're creating a whole bunch of objects
//$rootDirectory = new DAV\FS\Directory('public');
$rootDirectory = new DAV\FS\S3Directory("/",'<bucket-name>',$s3);
// The server object is responsible for making sense out of the WebDAV protocol
$server = new DAV\Server($rootDirectory);
// If your server is not on your webroot, make sure the following line has the
// correct information
$server->setBaseUri('/server.php/');
// The lock manager is reponsible for making sure users don't overwrite
// each others changes.
$lockBackend = new DAV\Locks\Backend\File('data/locks');
$lockPlugin = new DAV\Locks\Plugin($lockBackend);
$server->addPlugin($lockPlugin);
// This ensures that we get a pretty index in the browser, but it is
// optional.
$server->addPlugin(new DAV\Browser\Plugin());
// All we need to do now, is to fire up the server
$server->exec();
Result:
The file name list is displayed, but it is displayed as 0 bytes.
Uploading is working, but other operations are not working (file size is correct on Wasabi).
”4.4.0 Exception Cannot traverse an already closed generator" is displayed.

How to send a patch api request using a variable

I am trying to update a user(s) type in the Zoom conference application using their API. I use PATCH as per their documentation, and this works when I hard code the userId in the URL, but I need to use an array variable instead because multiple users will need to be updated at once.
This code works with the manually entered userId.
The userId and bearer code are made up for the purpose of this question.
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->PATCH('https://api.zoom.us/v2/users/jkdflg4589jlmfdhw7', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer my token goes here',
],
'body' => json_encode([
'type' => '1',
])
]);
$body = $response->getBody() ;
$string = $body->getContents();
$json = json_decode($string);
This way the code works and changes my user's type to 1.
The following code is the one that doesn't work.
In the Zoom API reference there is a test section and the userId can be added in a tab called Settings under the field: Path Parameters.
https://marketplace.zoom.us/docs/api-reference/zoom-api/users/userupdate
Hence I can add the userId there and when I run it, it actually replaces {userId} in the URL with the actual userId into the url patch command.
Hence from this ->
PATCH https://api.zoom.us/v2/users/{userId}
It becomes this after all transformations, scripts,
and variable replacements are run.
PATCH https://api.zoom.us/v2/users/jkdflg4589jlmfdhw7
However, when I try it in my code it doesn't work, I don't know where to add the path params. I am more used to PHP but I'll use whatever I can to make it work. Also I would like userId to be a variable that may contain 1 or more userIds (array).
This is my code that doesn't work:
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->PATCH('https://api.zoom.us/v2/users/{userId}', [
'params' => [
'userId' => 'jkdflg4589jlmfdhw7',
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer my token goes here',
],
'body' => json_encode([
'type' => '1',
])
]);
$body = $response->getBody() ;
$string = $body->getContents();
$json = json_decode($string);
My code fails with error:
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `PATCH https://api.zoom.us/v2/users/%7BuserId%7D` resulted in a `404 Not Found` response: {"code":1001,"message":"User not exist: {userId}"}
in /home/.../Zoom_API_V2/guzzle_response/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Stack trace:
#0 /home/.../Zoom_API_V2/guzzle_response/vendor/guzzlehttp/guzzle/src/Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /home/.../Zoom_API_V2/guzzle_response/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /home/.../Zoom_API_V2/guzzle_response/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 /home/.../publ in /home/.../Zoom_API_V2/guzzle_response/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 113
If I understood you correctly, then this is basic string concatenation in PHP that you are trying to do
$userId = 'jkdflg4589jlmfdhw7';
$response = $client->PATCH('https://api.zoom.us/v2/users/' . $userId, [
// other options
]);
However, when I try it in my code it doesn't work, I don't know where to add the path params.
You add URL path in the first argument, since path is part of the URL. You can however set query parameters (e.g. for GET requests) and form data (e.g. for POST form requests) through Guzzle options, but not the path.
Also I would like userId to be a variable that may contain 1 or more userIds (array).
Using just a simple implode to convert an array to a comma separated list should work, but the API point you linked to does not seem to support multiple user IDs.
$userId = ['jkdflg4589jlmfdhw7', 'asdfa123sdfasdf'];
$response = $client->PATCH('https://api.zoom.us/v2/users/' . implode(',', $userId), [
// other options
]);

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

Passport - "Unauthenticated." - Laravel 5.3

I hope someone could explain why I'm unauthenticated when already has performed a successfull Oauth 2 authentication process.
I've set up the Passport package like in Laravel's documentation and I successfully get authenticated, receives a token value and so on. But, when I try to do a get request on, let say, /api/user, I get a Unauthenticated error as a response. I use the token value as a header with key name Authorization, just as described in the docs.
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware("auth:api");
This function is suppose to give back my self as the authenticated user, but I'm only getting Unauthenticated. Likewise, if I just return the first user, I'm again getting Unauthenticated.
Route::get('/test', function(Request $request) {
return App\User::whereId(1)->first();
})->middleware("auth:api");
In a tutorial from Laracast, guiding through the setup of Passport, the guider doesn't have the ->middleware("auth:api") in his routes. But if its not there, well then there's no need for authentication at all!
Please, any suggestions or answers are more then welcome!
You have to set an expiration date for the tokens you are generating,
set the boot method in your AuthServiceProvider to something like the code below and try generating a new token. Passports default expiration returns a negative number
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
Check your user model and the database table, if you have modified the primary id field name to say something other than "id" or even "user_id" you MIGHT run into issues. I debugged an issue regarding modifying the primary id field in my user model and database table to say "acct_id" instead of keeping it as just "id" and the result was "Unauthenticated" When I tried to get the user object via GET /user through the auth:api middleware. Keep in mind I had tried every other fix under the sun until I decided to debug it myself.
ALSO Be sure to UPDATE your passport. As it has had some changes made to it in recent weeks.
I'll link my reference below, it's VERY detailed and well defined as to what I did and how I got to the solution.
Enjoy!
https://github.com/laravel/passport/issues/151
I had this error because of that I deleted passport mysql tables(php artisan migrate:fresh), php artisan passport:install helps me. Remember that after removing tables, you need to re-install passport!
I had exactly the same error because I forgot to put http before the project name.
use Illuminate\Http\Request;
Route::get('/', function () {
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://consumer.dev/callback',
'response_type' => 'code',
'scope' => '',
]);
// The redirect URL should start with http://
return redirect('passport.dev/oauth/authorize?'.$query);
});
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://passport.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3,
'client_secret' => 'M8y4u77AFmHyYp4clJrYTWdkbua1ftPEUbciW8aq',
'redirect_uri' => 'http://consumer.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});

How to set cookie before test in Laravel?

I need to test a specific behaviour based on the presence of a cookie, how do I set a cookie before sending the request (or visiting the page) ? For the moment the following fails, it behaves likes nothing was set.
$this->actingAs($user)
->withSession(['user' => $user, 'profile' => $profile]) ;
#setcookie( 'locale_lc', "fr", time() + 60 * 60 * 24 * 900, '/', "domain.com", true, true) ;
$this->visit('/profile') ;
Or
$cookie = ['locale_lc' => Crypt::encrypt('fr')] ;
$this->actingAs($user)
->withSession(['user' => $user, 'profile' => $profile])
->makeRequest('GET', '/profile', [], $cookie) ;
The problem was in the setting and reading of cookies. Neither #setcookie nor $_COOKIE will work from a testing context. The method makeRequest with a cookie array is the right one.
However !
The reading script (controller, middleware) must be using Laravel's $request->cookie() method and not directly try to access it with $_COOKIE. In my case the cookie needs to be read by another app on our domain so I also had to disable the encryption for that specific cookie, which can be done in EncryptCookies.php
EncryptCookies
<?php
protected $except = [
'locale_lc'
];
Test
<?php
$cookie = ['locale_lc' => 'fr'] ;
$this->actingAs($user)
->withSession(['user' => $user, 'profile' => $profile])
->makeRequest('GET', '/profile', [], $cookie) ;
Middleware
<?php
public function handle($request, Closure $next){
if($request->cookie('locale_lc')){...}
}