Testing updating user profile data - testing

I make http tests in my Laravel 5.7 application with profile page(which has "Profile View" page and "Profile Details" editor ), like :
$newUser->save();
$testing_user_id = $newUser->id;
$newUserGroup = new UserGroup();
$newUserGroup->group_id = USER_ACCESS_USER;
$newUserGroup->user_id = $newUser->id;
$userGroup= Group::find($newUserGroup->group_id);
$newUserSessionData = [
[
'loggedUserAccessGroups' => ['group_id' => $newUserGroup->group_id, 'group_name' => !empty($userGroup) ? $userGroup->name : ''],
'logged_user_ip' => '0',
]
];
$newUserGroup->save();
// 3. OPEN PROFILE PAGE BLOCK START
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->get('/profile/view');
// 3. OPEN PROFILE PAGE BLOCK END
// 4. MAKING CHECKING PROFILE FOR USER CREATED AT 2) BLOCK START
$response->assertStatus(200); // to use HTTP_RESPONSE_OK
$response->assertSee(htmlspecialchars("Profile : " . $newUser->username, ENT_QUOTES));
// 4. MAKING CHECKING PROFILE FOR USER CREATED AT 2) BLOCK END
// 5. OPEN PROFILE DETAILS VIEW PAGE BLOCK START
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->get('profile/view');
$response->assertStatus(200);
$response->assertSee(htmlspecialchars("Profile : " . $newUser->username, ENT_QUOTES));
// 5. OPEN PROFILE DETAILS VIEW PAGE BLOCK END
// 6. OPEN PROFILE DETAILS EDITOR PAGE BLOCK START
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->get('profile/edit-details'); // http://local-votes.com/profile/edit-details
$response->assertStatus(HTTP_RESPONSE_OK);
$response->assertSee(htmlspecialchars("Profile : Details"));
// 6. OPEN PROFILE DETAILS EDITOR PAGE BLOCK END
// 7. MODIFY PROFILE DETAILS PAGE BLOCK START
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->post('profile/edit-details-post', [
'first_name' => 'Modified : ' . $newUser->first_name,
'last_name' => 'Modified : ' . $newUser->last_name,
'phone' => 'Modified : ' . $newUser->phone,
'website' => 'Modified : ' . $newUser->website,
'_token' => $csrf_token
]);
// $response->assertStatus(205); // ???
// 7. MODIFY PROFILE DETAILS PAGE BLOCK END
////////////////////////
// 8. OPEN PROFILE DETAILS VIEW PAGE AFTER MODIFICATIONS BLOCK START
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->get('profile/view');
$response->assertStatus(200);
$response->assertSee( htmlspecialchars('Modified : ' . $newUser->last_name) );
// 8. OPEN PROFILE DETAILS VIEW PAGE AFTER MODIFICATIONS BLOCK END
New user is added and Profile View page is opened ok, but there are problems at step // 7. MODIFY PROFILE DETAILS PAGE BLOCK START
as I see in sql trace new user is inserted but not updated.
In my control app/Http/Controllers/ProfileController.php update method is defined with validation request :
public function update_details(ProfileUserDetailsRequest $request)
{
$userProfile = Auth::user();
$requestData = $request->all();
$userProfile->first_name = $requestData['first_name'];
$userProfile->last_name = $requestData['last_name'];
$userProfile->phone = $requestData['phone'];
$userProfile->website = $requestData['website'];
$userProfile->updated_at = now();
$userProfile->save();
$this->setFlashMessage('Profile updated successfully !', 'success', 'Profile');
return Redirect::route('profile-view');
} // public function update_details(ProfileUserDetailsRequest $request)
1) Can the reason be in ProfileUserDetailsRequest and how to deal this ?
My profile details editor works ok.
My route defined as :
Route::group(array('prefix' => 'profile', 'middleware' => ['auth', 'isVerified']), function(){
Route::post('edit-details-post', array(
'as' => 'profile-edit-details-post',
'uses' => 'ProfileController#update_details'
));
At first I tried PUT, but after that I tried POST - the same without results.
2) Can you advice some proper way of User Profile details checking on // 7. MODIFY PROFILE DETAILS PAGE BLOCK START step ?
MODIFIED BLOCK # 2 :
I tried patch method, but it does not work anyway.
I have debugging method in my app/Http/Controllers/ProfileController.php
public function update_details(ProfileUserDetailsRequest $request)
{
method and when test is run I see that it is not triggered.
I use the same update_details method updating my form in brauser and it work ok(I see debugging info too).
I suppose that could be csrf issue and in header of my test file I wrote:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use DB;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutMiddleware; // Prevent all middleware from being executed for this test class.
public function testProfilePage()
{
$csrf_token = csrf_token();
...
$response = $this->actingAs($newUser)
->withSession($newUserSessionData)
->patch('profile/edit-details-post', [
'first_name' => 'Modified : ' . $newUser->first_name,
'last_name' => 'Modified : ' . $newUser->last_name,
'phone' => 'Modified : ' . $newUser->phone,
'website' => 'Modified : ' . $newUser->website,
// '_token' => $csrf_token / I TRIED TO UNCOMMENT THIS LINE TOO
]);
$response->assertStatus(205); // making this check I see that code 419 was returned
Can decision be to add in file app/Http/Middleware/VerifyCsrfToken.php
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
// ???
];
If in command line I run tests as
vendor/bin/phpunit tests/Feature/ProfilepageTest.php
What have I to add in except?
Thanks!

Other than the PATCH instead of POST following are my recommendations to test your code.
Instead of ProfileUserDetailsRequest try to use simple Request.
Try to log $request variable in your update function and check if the _token and _method are available, method should be PATCH and the request variables are posted correctly.
Make a model of user table and try to update the user with that model using
$user = User::find(Auth::user()->id);
…
$user->save();
Sessions are initiated with a middleware, i think if you are disabling the middleware, session will not work.

If you are using an IDE like Visual Studio Code to run your code then try using a debugger like xdebug. Place a breakpoint in your update_details method and see if it is getting to save and save is executing. If it is then we know save is not updating correctly.
It looks like what you are doing is correct according to the documentation for update:
https://laravel.com/docs/5.7/eloquent#updates example from docs below:
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Off the top of my head my only guess as to why it would fail is maybe getting the user off of the auth object causes problems. Take the id from the user in the auth object and use find() to grab the user then update its values and save and see if that works.

Related

backdrop cms module-created blocks deltas not working

(tagging with drupal7 because i cannot create a tag for backdrop)
i have a fresh backdrop install, with a new theme duped from bartik, and a new layout duped from moscone_flipped. no code changes to those yet.
i have a module that creates 2 simple blocks, mostly just some html. i have implemented hook_block_info() and hook_block_view(). i can place blocks into regions in the layout using the admin ui. i can see each block on the front end page when i place either one of them. but not both. when i have both blocks placed in the layout, for some reason both regions display the output from the same block. and i have verified that it is always the first block defined in the array returned from hook_block_info(). i have cleared caches, checked code, etc.
has anyone seen this before?
btw, i just applied the recent security upgrade, and the behavior is the same both before and after the upgrade.
i will paste in the module code below, in case i have missed something.
thanks for any help anyone can provide.
// implements hook_block_info()
function mbr_block_info()
{
$info = array();
$info['rate-tables'] = array(
'info' => 'Rate Tables (Buttons)',
'description' => 'The displays the rate table links for the sidebar',
);
$info['mbr-footer'] = array(
'info' => 'MBR Footer',
'description' => 'Displays footer links, disclaimer, copyright',
);
return($info);
}
// implements hook_block_view()
function mbr_block_view($delta = '', $settings = array(), $contexts = array())
{
$block = array();
switch($delta)
{
case 'mbr-footer':
$subject = null;
$mbrFooter = getMBRFooterBlock();
$block = array('subject' => $subject, 'content' => $mbrFooter);
case 'rate-tables':
$subject = null;
$rateTables = getRateTablesBlock();
$block = array('subject' => $subject, 'content' => $rateTables);
}
return($block);
}

Error: A required parameter (id) was missing when redirect URL in form Moodle

Moodle 3, developing a block
I'm getting the following error: 'A required parameter (id) was missing'.
It happens in $mform, only when I'm using the array('id' => $instance->id) in the 'Else if' statement in the redirect($url).
Surprisingly, because when I'm using the same code in a button with a redirect url, the code works correct.
I've tried several things, but nothing helps. What could be the problem?
Here is some code:
$id = required_param('id', PARAM_INT);
$instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
$context = \context_block::instance($instance->id);
$mform = new newlink();
if ($mform->is_cancelled()) {
$url = new moodle_url('/my');
redirect($url);
} else if ($fromform = $mform->get_data()) {
// data from form
....
$url = new moodle_url('/blocks/name_of_block/links.php', array('id' => $instance->id)); // HERE IS THE PROBLEM
(Note: when I'm using here the block instance id number 123 directly, the redirect is working correct:
$url = new moodle_url('/blocks/name_of_block/links.php?id=123';)
redirect ($url);
} else {
//Set default data (if any)
$mform->set_data($toform);
//displays the form
$mform->display();
}
$url = new moodle_url('/blocks/name_of_block/links.php', array('id' => $instance->id))
echo $OUTPUT->single_button($url, get_string('button:links', 'block_name_of_block')); // THIS IS WORKING CORRECT
Is it when you submit the form rather than the redirect?
In your form do you have:
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
and in the code above do you have:
$toform->id = $id;
$mform->set_data($toform);

Shopify API Updating Fulfillments

I am writing a private app in Shopify with PHP. I have been able to get most of the other access to the json data, however, I am having trouble with Fulfillments - specifically updating a single line-item.
I am using the api-skeleton (phpish)?
Here is my code (the process as described seems so simple):
$orderid = "1350520065";
$itemid = "2338134657";
$quantity = 1;
$arguments = array(
'fulfillment' => array(
'tracking_number' => null,
'notify_customer' => true,
'line_items' => array(array('id' => $itemid, 'quantity' => 1))
)
);
$response = $shopify('POST /admin/orders/' . $orderid . '/fulfillments.json', $arguments);
I am getting [line_items] => Required parameter missing or invalid.
Any help would be appreciated.
Skip the line items unless you are doing a partial fulfillment. If you are, then obviously you need a quantity. You forgot that it seems, hence your error of missing parameter.
Add a header 'Content-Type:application/json' to your POST. That worked for me.

BOX-API upload file form

i'm trying to upload a file in BOX_API with php and Zend framework. But i'm missing somethin. It's the first time that i use an interface like this o i've read the manual. But it is confusig for me. My question are two:
-First, why do you have to pass to the post call only the name of the file and not the whole file with the right header for file upload? File upload in a form is not like passing the name of the file through a post call;
-secondly and consequently, do i have to make a form for file upload or simply a textarea where to write the name of the file to be passed to the BOX-API?
UPDATE:
This is the code of my upload form:
$form = new Zend_Form;
$form->setAction('/imball-reagens/public/upload')
->setMethod('post');
$file = new Zend_Form_Element_File('file');
$file->setLabel('Choose a file to upload:');
$file->addValidator('alnum');
$file->setRequired(true);
$form->addElement($file);
$access_token = new Zend_Form_Element_Hidden(array('name' => 'access_token', 'value' => $result->access_token));
$form->addElement($access_token);
$refresh_token = new Zend_Form_Element_Hidden(array('name' => 'refresh_token', 'value' => $result->refresh_token));
$form->addElement($refresh_token);
$form->addElement('submit', 'upload', array('label' => 'Upload File'));
echo $form;
And this s the POST cal to the box API which comes after the form:
$access_token= $this->getRequest()->getParam('access_token');
$client = new Zend_Http_Client('https://upload.box.com/api/2.0/files/content');
$client->setMethod(Zend_Http_Client::POST);
$client->setHeaders('Authorization: Bearer '.$access_token);
$data = $_FILES["file"]["name"];
$client->setParameterPost(array(
'filename' => '#'.$data,
'parent_id' => '0'
));
$response = $client->request()->getBody();
$this->view->response= $response;
$result = json_decode($response);
The error it throws is below:
{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"172518183652dcf2a16af73"}
Tricky to debug without seeing all of the code, but in the bit you pasted it looks like you are passing $_FILES["file"]["name"] to the API - this only contains the original name of the file which was uploaded by the user - you need to pass the location to the file on the server which is sending the data to the Box API client so that it can grab it and send it to the Box server - this should be stored in $_FILES["file"]["tmp_name"].
I would recommend changing the code to this and trying again:
$access_token= $this->getRequest()->getParam('access_token');
$client = new Zend_Http_Client('https://upload.box.com/api/2.0/files/content');
$client->setMethod(Zend_Http_Client::POST);
$client->setHeaders('Authorization: Bearer '.$access_token);
$data = $_FILES["file"]["tmp_name"];
$client->setParameterPost(array(
'parent_id' => '0'
));
$client->setFileUpload($data, 'filename');
$response = $client->request()->getBody();
$this->view->response= $response;
$result = json_decode($response);

Symfony file upload - "Array" stored in database instead of the actual filename

I'm using Symfony 1.4.4 and Doctrine and I need to upload an image on the server.
I've done that hundreds of times without any problem but this time something weird happens : instead of the filename being stored in the database, I find the string "Array".
Here's what I'm doing:
In my Form:
$this->useFields(array('filename'));
$this->embedI18n(sfConfig::get('app_cultures'));
$this->widgetSchema['filename'] = new sfWidgetFormInputFileEditable(array(
'file_src' => '/uploads/flash/'.$this->getObject()->getFilename(),
'is_image' => true,
'edit_mode' => !$this->isNew(),
'template' => '<div id="">%file%</div><div id=""><h3 class="">change picture</h3>%input%</div>',
));
$this->setValidator['filename'] = new sfValidatorFile(array(
'mime_types' => 'web_images',
'path' => sfConfig::get('sf_upload_dir').'/flash',
));
In my action:
public function executeIndex( sfWebRequest $request )
{
$this->flashContents = $this->page->getFlashContents();
$flash = new FlashContent();
$this->flashForm = new FlashContentForm($flash);
$this->processFlashContentForm($request, $this->flashForm);
}
protected function processFlashContentForm($request, $form)
{
if ( $form->isSubmitted( $request ) ) {
$form->bind( $request->getParameter( $form->getName() ), $request->getFiles( $form->getName() ) );
if ( $form->isValid() ) {
$form->save();
$this->getUser()->setFlash( 'notice', $form->isNew() ? 'Added.' : 'Updated.' );
$this->redirect( '#home' );
}
}
}
Before binding my parameters, everything's fine, $request->getFiles($form->getName()) returns my files.
But afterwards, $form->getValue('filename') returns the string "Array".
Did it happen to any of you guys or do you see anything wrong with my code?
Edit: I added the fact that I'm embedding another form, which may be the problem (see Form code above).
Alright, I got it. I wasn't properly declaring my validator.
What i should've done is:
$this->setValidator('filename', new sfValidatorFile(array(
'mime_types' => 'web_images',
'path' => sfConfig::get('sf_upload_dir').'/flash',
)));
Silly mistake, I hope that will help those who have the same problem.
Alternatively you can use;
$this->validatorSchema['filename']
in place of;
$this->setValidator['filename']