Some authenticated users can't access secure content or use the restricted API - drupal

I'm in desperate need for help on this.
I'm the developer of a site (rockalingua.com) that offers subscriptions to a Learning Management system. We have developed the LMS creating several drupal modules.
It's working quite well so far but we are getting reports from some schools that some students (authenticated users) can't access some content (They get messages stating that they don't have permission to see that content)
This seems to be random, but when this happens the site acts as if they where not logged in. If the log-in again they can access the content usually (they report they sometimes have to restart the browser for that to happen)
The pages that have this problem use a REST API created by us for tracking the students progress.
Searching the logs I realized that some time after a class starts using the system a lot of warning and notice messages are dumped to the messages log reporting unauthenticated users trying to use the API from the same IPs and urls seconds or minutes before, authenticated users where accessing it without any problem.
I've examined all the code involved several times and can't find anything wrong with it, specially when it seems to happen randomly.
I know most schools have a proxy that use a cache. But don't know much about proxies or whether they could be affecting this issue.
If so, what could be do to avoid school proxies caching dynamic pages?
UPDATE:
I include the typical response headers we are sending on the typical affected requests, and some relevant code:
Accept-Ranges: bytes
Age: 0
Cache-Control: no-cache, must-revalidate
Content-Encoding: gzip
Content-Language: en
Content-Length: 4590
Content-Type: text/html; charset=utf-8
Date: Fri, 26 Jan 2018 08:53:52 GMT
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Server: Apache
Vary: Accept-Encoding
Via: 1.1 varnish
X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Powered-By: PHP/5.4.45
X-UA-Compatible: IE=Edge,chrome=1
X-Varnish: 1592956310
And here you have the code for a typical AJAX request that I have seem to behave as described sometimes:
// ...
if($form_state['data']['is_student']) {
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Go back'),
'#attributes' => [
'class' => [$form_state['data']['activity_type']],
],
'#ajax' => [
'callback' => 'activity_modal_form_submit_callback'
],
];
} else {
}
return $form;
}
/* Ajax callback to update the activity item after closing its modal */
function activity_modal_form_submit_callback($form, &$form_state) {
ctools_include('modal');
ctools_include('ajax');
global $user;
$activities_retriever = new student_task_activities($user->uid, $form_state['data']['task_id']);
$activity = $activities_retriever->lms_student_task_activity($form_state['data']['activity_id']);
$activity_data = array(
//'activity_name' => $activity['title'],
'times' => $activities_retriever->lms_student_task_activity_repetitions_assigned($activity['activity_id']),
'task_activity_entity_id' => $activity['activity_entity'],
'type' => $activity['activity_type'],
'title' => $activity['activity_title'],
'status' => $activity['status'],
'progress' => $activity['progress'],
'is_correctness_supported' => $activity['is_game_supported'],
'percent_right' => $activity['percent_right'],
'is_student' => $form_state['data']['is_student'],
);
$item_updated = render_activity_item(
$form_state['data']['activity_id'],
$activity_data,
$form_state['data']['task_id'],
$form_state['data']['is_student'],
$form_state['data']['due_date'], false);
$commands[] = ctools_modal_command_dismiss();
if($activity_data['type'] == 'video' || $activity['activity_type'] == 'song') {
$commands[] = ajax_command_replace('#activity_' . $form_state['data']['activity_id'], $item_updated);
}
print ajax_render($commands);
drupal_exit();
}
As it calls student_task_activities needs the uid on the constructor to retrieve the activity data and in the described situations it receives a 0, the activity array is empty and when trying to render the activity item a notice is dumped to the log warning about the missing information. There is where it says the uid is 0 and that's how I realized the user id was lost somewhere in the process.

Related

How to send POST to MongoDB Atlas using HTTPie?

I'm attempting to test my REST API by making a POST request to a MongoDB cloud Atlas DB server. I know Postman is available, but I wanted to use something different like Httpie. I already checked this question but I'm still stuck.
How to send a POST request using HTTPie?
I'm trying to get text='john smith'
when I use
`http -f POST :5000/api/posts text='john smith'`
I get this response.
`HTTP/1.1 201 Created
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Tue, 19 Feb 2019 20:33:36 GMT
X-Powered-By: Express`
But when I use...
http -f GET :5000/api/posts
I get back ...
`[
{
"_id": "5c6c6820c2f6eb15ea9e8e08",
"createdAt": "2019-02-19T20:33:36.468Z",
"text": null
}
]`
This is my Nodejs API for the post
router.post('/', async(req, res) => {
const posts = await loadPostCollection();
await posts.insertOne({
text: req.body.text,
createdAt: new Date()
});
res.status(201).send();
});

Paypal recurring payment profile API

I'm trying to create a recurring payment profile using paypal API in Wordpress. After taking the required information from the user I'm making a request using the following url.
https://api-3t.sandbox.paypal.com/USER=xylon-facilitator_api1.sjinnovation.com&PWD=9GDLFHDX3TQYWX4F&SIGNATURE=AO0B8EcgGN1ir1vqHVNLJ4fmaGxoAbfv5uwkwVkBxkD8vVif33kMJlD0&METHOD=CreateRecurringPaymentsProfile&CREDITCARDTYPE=Visa&ACCT=4311196648584326&EXPDATE=122019&FIRSTNAME=Xylon&LASTNAME=Gracias&PROFILESTARTDATE=2014-12-29T12:14:38Z&BILLINGPERIOD=Month&BILLINGFREQUENCY=1&AMT=20
But for the response i get following data
Array ( [headers] => Array ( [date] => Mon, 29 Dec 2014 12:14:39 GMT [server] => Apache [content-length] => 445 [connection] => close [content-type] => text/html; charset=iso-8859-1 ) [body] =>
Not Found
The requested URL /cgi-bin/ppapi was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Apache Server at api-3t.sandbox.paypal.com Port 443
[response] => Array ( [code] => 404 [message] => Not Found ) [cookies] => Array ( ) [filename] => )
I'm using following link for reference
https://developer.paypal.com/docs/classic/paypal-payments-pro/integration-guide/WPRecurringPayments/
I'm Using direct payement method
Look at the API reference documentation here: https://developer.paypal.com/docs/classic/api/#merchant
... and then some of the many examples out on the web. As a 404 usually indicates, you have an incorrect URL (you probably meant to post to https://api-3t.sandbox.paypal.com/nvp if you are using the signature authentication and NVP; you omitted the path "nvp") and there are further issues after that with your variable handling.

Symfony 2 AppCache behaving differently when under heavy load

I am experiencing a strange problem with symfony 2. I have an app which has a count down timer on it (counting down hours minutes and days).
This minute by minute timer works perfectly 90% of the time, but when under heavy load, the timer got stuck and wouldn't change (presumably because it was serving a cached version):
We have been unable to replicate the error using a load testing script, it seems to only happen when there are lots of actual users on the site.
Our cache options are setup as follows:
class AppCache extends HttpCache
{
protected function getOptions()
{
return array(
'debug' => true,
'default_ttl' => 1 * 60 * 60,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
}
The response that is being sporadically cached has the following header:
HTTP/1.1 200 OK
Date: Fri, 17 May 2013 09:36:55 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze15
P3P: CP="CURa CUR NID ADM ADMa DEV DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"
Cache-Control: private
X-Symfony-Cache: GET /my-app/show: miss
Vary: Accept-Encoding
Content-Encoding: gzip
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
Our Front Controller script file is as follows:
<?php header('P3P: CP="CURa CUR NID ADM ADMa DEV DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\ClassLoader\ApcClassLoader;
$loader = require_once __DIR__.'/app/bootstrap.php.cache';
require_once __DIR__.'/app/AppKernel.php';
require_once __DIR__.'/app/AppCache.php';
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
We haven't explicitly set any http caching on this action, or set anything to be cached apart from the fact that we are using the AppCache to wrap our kernel. Doing this definitely makes a massive difference to the performance of our site, as when we take it off, the load goes up very quickly during load testing.

Reading WordPress header.php/footer.php to a text string

I am attempting to read the results of the executed header.php/footer.php files as a string of html. Here's the scenario:
There are pages in the site that are developed in a .net environment but they want to share common headers/footers across the entire domain. They wish to have WordPress be the repository for this code and any time there is an update have a PHP cURL call to a .net web service and feed it the new HTML for the header/footers.
I tried calling get_header() but that does not return a string (as I anticipated) so then I tried this test solution in functions.php:
function write_header() {
$header_content = file_get_contents(get_bloginfo('wpurl').'/index.php' );
$fp = fopen('c:\header.txt', 'a+');
fwrite($fp, $header_content);//just testing the output, this will be a cURL call eventually.
fclose($fp);
}
add_action( 'wp_update_nav_menu', 'write_header' );
It seems to be a very heavy handed method of getting the HTML since I'll have to do a lot of string manipulation to parse out the pieces I want. Is there a simpler way of doing this that I'm missing?
If get_header() outputs the header for you, try just wrapping it with an ob_start() and ob_get_contents() to extract the header to a string. You can then discard the output with ob_end_clean(). See the PHP output buffering documentation.
ob_start();
get_header();
$header_as_string = ob_get_contents();
ob_end_clean();
There's a couple ways you can approach this problem (both are a bit of kludge, but what isnt...). The first would be to create a template in your theme's directory that will include only the header and footer calls -- the body of the template can contain a delimiter string like an html comment, e.g. <!-- SPLIT HERE -->.
Request the page through CURL into an output buffer, capturing the resulting response, which you can split into it's component parts using the above delimiter. That will give you your header and footer, complete with the fully rendered tags in the header for css,js, etc. It's not pretty, but it does the job.
The second approach would be an adaptation of the first, which, rather than you doing the splitting, have your .net team take care of it on their end if possible.
UPDATE
Okay, so there's actually a third option, which I completely forgot about, and that's to use one of WP's features: wp_remote_get() http://codex.wordpress.org/Function_API/wp_remote_get
Retrieves a URL using the HTTP GET method, returning results in an array. Results include HTTP headers and content.
This is what you should get back (excerpted from the API docs):
Array
(
[headers] => Array
(
[date] => Thu, 30 Sep 2010 15:16:36 GMT
[server] => Apache
[x-powered-by] => PHP/5.3.3
[x-server] => 10.90.6.243
[expires] => Thu, 30 Sep 2010 03:16:36 GMT
[cache-control] => Array
(
[0] => no-store, no-cache, must-revalidate
[1] => post-check=0, pre-check=0
)
[vary] => Accept-Encoding
[content-length] => 1641
[connection] => close
[content-type] => application/php
)
[body] => <html>This is a website!</html>
[response] => Array
(
[code] => 200
[message] => OK
)
[cookies] => Array
(
)
)
All you'd have to do is pass the URL to a page that's using the template I mentioned above, then handle response from wp_remote_get(); extract the html content form [body] and do your string splitting. Pretty much what you want.
Further reading: wp_remote_retrieve_body() http://codex.wordpress.org/Function_API/wp_remote_retrieve_body

Why this json Symfony output outputs the headers

This is my first day to have fun with Symfony and drupal 8, so please excuse me if my question is very obvious.
With drupal 7:
drupal_json_output(array('products' => array_values($products)));
exit;
the json output is clean:
{"products":["item_1","item_2",....]}
With drupal 8:
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
print new JsonResponse(array('products' => array_values($products)));
exit;
It outputs with the headers:
HTTP/1.0 200 OK
Cache-Control: no-cache
Content-Type: application/json
Date: Wed, 18 Jul 2012 07:53:26 GMT
{"products":["item_1","item_2",....]}
How do you get rid of those headers?
I am stuck to read the reference here.
Any hint is very much appreciated.
You can get only the "content" of a response by calling $response->getContent().
In your case you could do
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
$response = new JsonResponse(array('products' => array_values($products)));
print $response->getContent();
exit;
However, be aware that this would be a bad practice because you would lose the response headers in the process, and wouldn't tell for example, what the content-type of you response is (in this case: "application/json") etc ...
I do not know how to do this properly with drupal, any tips is appreciated.

Resources