Skip to content

Commit

Permalink
Ajaxify Cors section in Personal settings
Browse files Browse the repository at this point in the history
  • Loading branch information
VicDeo committed Jun 19, 2020
1 parent ab72fd5 commit 03eab90
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 127 deletions.
7 changes: 7 additions & 0 deletions changelog/unreleased/37560
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Bugfix: Show error message at Settings Personal CORS

Skipping a protocol at Settings Personal CORS silently refused to add the domain.
Proper error message added.


https://github.com/owncloud/core/pull/37560
3 changes: 2 additions & 1 deletion settings/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ public function __construct(array $urlParams=[]) {
$c->query('UserSession'),
$c->query('Logger'),
$c->query('URLGenerator'),
$c->query('Config')
$c->query('Config'),
$c->query('L10N')
);
});

Expand Down
82 changes: 42 additions & 40 deletions settings/Controller/CorsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IL10N;
use OCP\ILogger;
use OCP\IRequest;
use OCP\IURLGenerator;
Expand Down Expand Up @@ -49,6 +50,9 @@ class CorsController extends Controller {
/** @var string */
private $AppName;

/** @var IL10N */
private $l10n;

/**
* CorsController constructor.
*
Expand All @@ -63,27 +67,16 @@ public function __construct($AppName, IRequest $request,
IUserSession $userSession,
ILogger $logger,
IURLGenerator $urlGenerator,
IConfig $config) {
IConfig $config,
IL10N $l10n) {
parent::__construct($AppName, $request);

$this->AppName = $AppName;
$this->config = $config;
$this->userId = $userSession->getUser()->getUID();
$this->logger = $logger;
$this->urlGenerator = $urlGenerator;
}

/**
* Returns a redirect response
* @return RedirectResponse
*/
private function getRedirectResponse() {
return new RedirectResponse(
$this->urlGenerator->linkToRouteAbsolute(
'settings.SettingsPage.getPersonal',
['sectionid' => 'security']
) . '#cors'
);
$this->l10n = $l10n;
}

/**
Expand All @@ -107,28 +100,37 @@ public function getDomains() {
* @NoSubadminRequired
*
* @param string $domain The domain to whitelist
* @return RedirectResponse Redirection to the settings page.
* @return JSONResponse
*/
public function addDomain($domain) {
if (!isset($domain) || !self::isValidUrl($domain)) {
return $this->getRedirectResponse();
if ($this->isValidUrl($domain)) {
$userId = $this->userId;
$domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true);
$domains = \array_filter($domains);
\array_push($domains, $domain);

// In case same domain is added
$domains = \array_unique($domains);

// Store as comma separated string
$domainsString = \json_encode($domains);

$this->config->setUserValue($userId, 'core', 'domains', $domainsString);
$this->logger->debug("The domain {$domain} has been white-listed.", ['app' => $this->appName]);
return new JSONResponse([ 'domains' => $domains]);
} else {
$cleanDomain = \strip_tags($domain);

if (
\strpos($domain, 'http://') !== 0
&& \strpos($domain, 'https://') !== 0
) {
$errorMsg = $this->l10n->t("Protocol is missing in '%s'", [$cleanDomain]);
} else {
$errorMsg = $this->l10n->t("'%s' is not a valid domain", [$cleanDomain]);
}
return new JSONResponse([ 'message' => $errorMsg ]);
}

$userId = $this->userId;
$domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true);
$domains = \array_filter($domains);
\array_push($domains, $domain);

// In case same domain is added
$domains = \array_unique($domains);

// Store as comma separated string
$domainsString = \json_encode($domains);

$this->config->setUserValue($userId, 'core', 'domains', $domainsString);
$this->logger->debug("The domain {$domain} has been white-listed.", ['app' => $this->appName]);

return $this->getRedirectResponse();
}

/**
Expand All @@ -138,29 +140,29 @@ public function addDomain($domain) {
* @NoSubadminRequired
*
* @param string $domain Domain to remove
* @return RedirectResponse Redirection to the settings page.
* @return JSONResponse Redirection to the settings page.
*/
public function removeDomain($id) {
public function removeDomain($domain) {
$userId = $this->userId;
$decodedDomain = \urldecode($domain);
$domains = \json_decode($this->config->getUserValue($userId, 'core', 'domains', '[]'), true);
if (isset($domains[$id])) {
unset($domains[$id]);
if (($key = \array_search($decodedDomain, $domains)) !== false) {
unset($domains[$key]);
if (\count($domains)) {
$this->config->setUserValue($userId, 'core', 'domains', \json_encode($domains));
} else {
$this->config->deleteUserValue($userId, 'core', 'domains');
}
}

return $this->getRedirectResponse();
return new JSONResponse([ 'domains' => $domains ]);
}

/**
* Checks whether a URL is valid
* @param string $url URL to check
* @return boolean whether URL is valid
*/
private static function isValidUrl($url) {
private function isValidUrl($url) {
return (\filter_var($url, FILTER_VALIDATE_URL) !== false);
}
}
70 changes: 52 additions & 18 deletions settings/js/panels/cors.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,67 @@
var PersonalCors = {
renderRow: function(domain){
var row = $('<tr />').appendTo('#cors .grid tbody');
$('<td />').appendTo(row).text(domain);
var col = $('<td />').appendTo(row);
$('<input type="button" class="button icon-delete removeDomainButton" />')
.data('value', domain)
.data('confirm', t('settings', 'Are you sure you want to remove this domain?'))
.appendTo(col)
},
render: function (data) {
$("#cors .grid tbody tr").remove();
for (var p in data) {
PersonalCors.renderRow(data[p]);
}
var numDomains = $("#cors .grid tbody tr").length;
if (numDomains === 0) {
$("#noDomains").show();
$("#cors .grid").hide();
} else {
$("#noDomains").hide();
$("#cors .grid").show();
}
}
};

$(document).ready(function () {
$('.removeDomainButton').on('click', function () {
var id = $(this).attr('data-id');
var confirmText = $(this).attr('data-confirm');
var token = OC.requestToken;
$('#cors').on('click', '.removeDomainButton', function () {
var confirmText = $(this).data('confirm');
var $el = $(this);

OC.dialogs.confirm(
t('settings', confirmText), t('settings','CORS'),
confirmText, t('settings','CORS'),
function (result) {
if (result) {
var value = encodeURIComponent($el.data('value'));
$.ajax({
type: 'DELETE',
url: OC.generateUrl('/settings/domains/{id}', {id: id}),
data: {
requesttoken: token
}
}).success(function() {
var numDomains = $("#cors .grid tbody tr").length;
if ($el.closest('tr').length === 1 && numDomains === 1) {
// Means only one domain row remains and that is to be deleted
// Show the No domains text
$("#noDomains").text("No Domains.");
// Remove the domain listing table
$("#cors .grid").remove();
url: OC.generateUrl('/settings/domains/{domain}', {domain: value}),
data: {}
}).success(function(response) {
if (response.domains) {
PersonalCors.render(response.domains)
}
$el.closest('tr').remove();
});
}
}, true
);
});
$('#corsAddNewDomain').on('click', function() {
$('#corsAddNewDomain').attr('disabled', true);
$.post(
OC.generateUrl('/settings/domains'),
{ domain : $('#domain').val()},
function(response) {
if (response.message) {
OC.Notification.showTemporary(response.message);
}
if (response.domains) {
PersonalCors.render(response.domains)
}
$('#domain').val('');
$('#corsAddNewDomain').attr('disabled', false);
}
)
});
});
2 changes: 1 addition & 1 deletion settings/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
['name' => 'Users#changeMail', 'url' => '/settings/mailaddress/change/{token}/{userId}', 'verb' => 'GET'],
['name' => 'Cors#getDomains', 'url' => '/settings/domains', 'verb' => 'GET'],
['name' => 'Cors#addDomain', 'url' => '/settings/domains', 'verb' => 'POST'],
['name' => 'Cors#removeDomain', 'url' => '/settings/domains/{id}', 'verb' => 'DELETE'],
['name' => 'Cors#removeDomain', 'url' => '/settings/domains/{domain}', 'verb' => 'DELETE'],
['name' => 'LegalSettings#setImprintUrl', 'url' => '/settings/admin/legal/imprint', 'verb' => 'POST'],
['name' => 'LegalSettings#setPrivacyPolicyUrl', 'url' => '/settings/admin/legal/privacypolicy', 'verb' => 'POST'],
['name' => 'ChangePassword#changePassword', 'url' => '/users/changepassword', 'verb' => 'POST'],
Expand Down
60 changes: 25 additions & 35 deletions settings/templates/panels/personal/cors.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,42 +24,32 @@
<h2 class="app-name">CORS</h2>
<span class="app-name">Cross-Origin Resource Sharing</span>

<h3><?php p($l->t('White-listed Domains')); ?></h3>
<p id="noDomains">
<?php if (empty($_['domains'])) {
p($l->t('No Domains.'));
} ?>
</p>
<h3><?php p($l->t('White-listed Domains')); ?></h3>
<p id="noDomains" <?php if (!empty($_['domains'])) { ?>class="hidden"<?php } ?>>
<?php p($l->t('No Domains.')); ?>
</p>

<?php if (!empty($_['domains'])) {
?>
<table class="grid">
<thead>
<tr>
<th id="headerName" scope="col"><?php p($l->t('Domain')); ?></th>
<th id="headerRemove">&nbsp;</th>
</tr>
</thead>
<tbody>
<?php foreach ($_['domains'] as $id => $domain) {
?>
<tr>
<td><?php p($domain); ?></td>
<td>
<input data-id="<?php p($id); ?>" type="button" class="button icon-delete removeDomainButton" data-confirm="<?php p($l->t('Are you sure you want to remove this domain?')); ?>" value="">
</td>
</tr>
<?php
} ?>
</tbody>
</table>
<?php
} ?>
<table class="grid">
<thead>
<tr>
<th id="headerName" scope="col"><?php p($l->t('Domain')); ?></th>
<th id="headerRemove">&nbsp;</th>
</tr>
</thead>
<tbody>
<?php foreach ($_['domains'] as $id => $domain) { ?>
<tr>
<td><?php p($domain); ?></td>
<td>
<input data-value="<?php p($domain) ?>" type="button" class="button icon-delete removeDomainButton" data-confirm="<?php p($l->t('Are you sure you want to remove this domain?')); ?>" value="">
</td>
</tr>
<?php } ?>
</tbody>
</table>

<h3><?php p($l->t('Add Domain')); ?></h3>
<form action="<?php p($_['urlGenerator']->linkToRoute('settings.Cors.addDomain')); ?>" method="post">
<h3><?php p($l->t('Add Domain')); ?></h3>
<input id="domain" name="domain" type="text" placeholder="<?php p($l->t('Domain')); ?>">
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
<input type="submit" class="button" value="<?php p($l->t('Add')); ?>">
</form>
<input id="corsAddNewDomain" type="submit" class="button" value="<?php p($l->t('Add')); ?>">
</form>
</div>
Loading

0 comments on commit 03eab90

Please sign in to comment.