Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(history): enabled for logged in user #1859

Merged
merged 1 commit into from
May 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion tests/CPClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public function testGetUserDetails () : void {
));

$data = $client->getUserDetails();
$this->assertEquals('263425', $data['id']);
$this->assertEquals('263425', $data['activeContact']['id']);
}

public function testGetUserDetailsWithError () : void {
Expand Down
31 changes: 17 additions & 14 deletions www/common.inc
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,14 @@ if (Util::getSetting('cp_auth')) {
header('Location: ' . $location);
exit();
}
echo '<pre>';
var_dump($e);
echo '</pre>';

/*
* for when we ship to prod
* throw $e;
*
*/
echo '<pre>';
var_dump($e);
echo '</pre>';
exit();
});
}
Expand Down Expand Up @@ -306,6 +305,20 @@ if (isset($_REQUEST['color'])) {
$_REQUEST['color'] = $_REQUEST['color'];
}

if ($supportsSaml && !$supportsCPAuth) {
$request_context->setUser($saml_user);
}

/**
* Load app specific middleware
*/
if ($supportsCPAuth) {
require_once __DIR__ . '/common/AttachClient.php';
require_once __DIR__ . '/common/AttachUser.php';
require_once __DIR__ . '/common/AttachSignupClient.php';
require_once __DIR__ . '/common/CheckCSRF.php';
}

// Load the test-specific data
$id = '';
if (isset($_REQUEST['test']) && preg_match('/^[a-zA-Z0-9_]+$/', @$_REQUEST['test'])) {
Expand Down Expand Up @@ -435,13 +448,3 @@ if (is_file('./settings/custom_common.inc.php')) {
include('./settings/custom_common.inc.php');
}

if ($supportsSaml && !$supportsCPAuth) {
$request_context->setUser($saml_user);
}

if ($supportsCPAuth) {
require_once __DIR__ . '/common/AttachClient.php';
require_once __DIR__ . '/common/AttachUser.php';
require_once __DIR__ . '/common/AttachSignupClient.php';
require_once __DIR__ . '/common/CheckCSRF.php';
}
12 changes: 8 additions & 4 deletions www/common/AttachUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

(function (RequestContext $request) {
global $admin;
global $owner;

$host = Util::getSetting('host');
$cp_access_token_cookie_name = Util::getCookieName(CPOauth::$cp_access_token_cookie_key);
$cp_refresh_token_cookie_name = Util::getCookieName(CPOauth::$cp_refresh_token_cookie_key);
Expand All @@ -29,10 +31,12 @@
if (!is_null($access_token)) {
try {
$data = $request->getClient()->getUserDetails();
$user->setUserId($data['id']);
$user->setEmail($data['email']);
$user->setPaid($data['isWptPaidUser']);
$user->setVerified($data['isWptAccountVerified']);
$user->setUserId($data['activeContact']['id']);
$user->setEmail($data['activeContact']['email']);
$user->setPaid($data['activeContact']['isWptPaidUser']);
$user->setVerified($data['activeContact']['isWptAccountVerified']);
$user->setOwnerId($data['levelSummary']['levelId']);
$owner = $user->getOwnerId();
} catch (UnauthorizedException $e) {
error_log($e->getMessage());
// if this fails, Refresh and retry
Expand Down
45 changes: 45 additions & 0 deletions www/js/history-loggedin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
(function(window) {
window.filterHistory = filterHistory;

function filterHistory() {
const input = document.getElementById("filter");
const filter = input.value.toUpperCase();
const table = document.getElementById("historyBody");
const rows = table.getElementsByTagName("tr");

for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (row) {
txtValue = row.textContent || row.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
row.style.display = "";
} else {
row.style.display = "none";
}
}
}
}

}(window));

((window) => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
handleDaySelector();
});
} else {
handleDaySelector();
}

function handleDaySelector () {
const daySelector = document.querySelector('select[name=days]')
daySelector.addEventListener('change', (e) => {
const days = e.target.value;
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const redirectUri = protocol + "//" + hostname + "/testlog/" + days + "/";

window.location = redirectUri;
})
}
})(window);
6 changes: 6 additions & 0 deletions www/pagestyle2.css
Original file line number Diff line number Diff line change
Expand Up @@ -2455,6 +2455,12 @@ form[name=filterLog] select {
margin-bottom: 2em;
}

form[name=filterLog] select[name=days] {
margin-bottom: 0;
padding-right: 30px;
display: block;
}

.history_filter {
margin: 1em 0;
border-top: 1px solid #eee;
Expand Down
27 changes: 20 additions & 7 deletions www/runtest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1980,6 +1980,9 @@ function LogTest(&$test, $testId, $url)
global $runcount;
global $apiKey;
global $USER_EMAIL;
global $supportsCPAuth;
global $request_context;

if (GetSetting('logging_off')) {
server_sync($apiKey, $runcount, null);
return;
Expand All @@ -2003,19 +2006,29 @@ function LogTest(&$test, $testId, $url)
// $pageLoads *= $test['navigateCount'];

$user_info = '';
if ($supportsSaml) {
$client_id = null;
$create_contact_id = null;
if ($supportsCPAuth && isset($request_context) && !is_null($request_context->getUser())) {
$user_info = $request_context->getUser()->getEmail();
$client_id = $request_context->getUser()->getOwnerId();
$create_contact_id = $request_context->getUser()->getUserId();
} elseif ($supportsSaml) {
$saml_email = GetSamlEmail();
$client_id = GetSamlAccount();
$create_contact_id = GetSamlContact();
if (isset($saml_email)) {
$user_info = $saml_email;
}
} elseif (isset($test['user']) && strlen($test['user'])) {
$user_info = $test['user'];
} elseif (isset($_COOKIE['google_email']) && strlen($_COOKIE['google_email']) && isset($_COOKIE['google_id'])) {
$user_info = $_COOKIE['google_email'];
} else {
$user_info = $USER_EMAIL;
}

$redis_server = GetSetting('redis_test_history');
$redis_server = Util::getSetting('redis_test_history');

$key = isset($test['key']) ? $test['key'] : null;
if ($key == GetServerKey()) {
$key = null;
Expand All @@ -2035,7 +2048,7 @@ function LogTest(&$test, $testId, $url)
'key' => $key,
'count' => @$pageLoads,
'priority' => @$test['priority'],
'email' => $USER_EMAIL,
'email' => $user_info,
'redis' => $redis_server ? '1' : '0'
);

Expand All @@ -2054,16 +2067,16 @@ function LogTest(&$test, $testId, $url)
'location' => @$test['locationText'],
'private' => 0,
'testUID' => @$test['uid'],
'testUser' => $USER_EMAIL,
'testUser' => $user_info,
'video' => @$video,
'label' => @$test['label'],
'owner' => @$test['owner'],
'key' => $key,
'count' => @$pageLoads,
'runs' => @$pageLoads,
'priority' => @$test['priority'],
'clientId' => GetSamlAccount(),
'createContactId' => GetSamlContact()
'clientId' => $client_id,
'createContactId' => $create_contact_id
);
if (isset($logEntry['location'])) {
$logEntry['location'] = strip_tags($logEntry['location']);
Expand Down
43 changes: 42 additions & 1 deletion www/src/CPClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use WebPageTest\Exception\UnauthorizedException;
use GuzzleHttp\Exception\ClientException as GuzzleException;
use WebPageTest\Customer;
use WebPageTest\TestRecord;

class CPClient
{
Expand Down Expand Up @@ -165,12 +166,18 @@ public function getUserDetails(): array
'email',
'isWptPaidUser',
'isWptAccountVerified'
]),
(new Query('levelSummary'))
->setSelectionSet([
'levelId',
'levelType',
'levelName',
])
]);

try {
$account_details = $this->graphql_client->runQuery($gql, true);
return $account_details->getData()['userIdentity']['activeContact'];
return $account_details->getData()['userIdentity'];
} catch (GuzzleException $e) {
if ($e->getCode() == 401) {
throw new UnauthorizedException();
Expand Down Expand Up @@ -479,4 +486,38 @@ public function resendEmailVerification()
throw new ClientException(implode(",", $e->getErrorDetails()));
}
}

public function getTestHistory(int $days = 1): array
{
$view_hours = $days * 24;
$gql = (new Query('wptTestHistory'))
->setVariables([
new Variable('viewHours', 'Int', true)
])
->setArguments([
'viewHours' => '$viewHours'
])
->setSelectionSet([
'id',
'testId',
'url',
'location',
'label',
'testStartTime',
'user',
'apiKey'
]);

$variables = [
'viewHours' => $view_hours
];

$test_history = [];
$response = $this->graphql_client->runQuery($gql, true, $variables);
$data = $response->getData()['wptTestHistory'];
foreach ($data as $record) {
$test_history[] = new TestRecord($record);
}
return $test_history;
}
}
86 changes: 86 additions & 0 deletions www/src/TestRecord.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

declare(strict_types=1);

namespace WebPageTest;

/**
* A test history object, as tracked by CP
*/
class TestRecord implements \JsonSerializable
{
private int $id;
private string $test_id;
private string $url;
private string $location;
private string $label;
private string $test_start_time;
private string $user;
private ?string $api_key;

public function __construct(array $options = [])
{
$this->id = $options['id'];
$this->test_id = $options['testId'];
$this->url = $options['url'];
$this->location = $options['location'];
$this->label = $options['label'];
$this->test_start_time = $options['testStartTime'];
$this->user = $options['user'];
$this->api_key = $options['apiKey'] ?? null;
}

public function getId(): int
{
return $this->id;
}

public function getTestId(): string
{
return $this->test_id;
}

public function getUrl(): string
{
return $this->url;
}

public function getLocation(): string
{
return $this->location;
}

public function getLabel(): string
{
return $this->label;
}

public function getStartTime(): string
{
return $this->test_start_time;
}

public function getUser(): string
{
return $this->user;
}

public function getApiKey(): ?string
{
return $this->api_key;
}

public function jsonSerialize(): array
{
return [
'id' => $this->id,
'testId' => $this->test_id,
'url' => $this->url,
'location' => $this->location,
'label' => $this->label,
'testStartTime' => $this->test_start_time,
'user' => $this->user,
'apiKey' => $this->api_key
];
}
}
Loading