Skip to content

Commit

Permalink
use controller style for register managed server
Browse files Browse the repository at this point in the history
  • Loading branch information
sualko committed Jul 26, 2017
1 parent 0f96a7b commit faf8370
Show file tree
Hide file tree
Showing 10 changed files with 458 additions and 117 deletions.
111 changes: 0 additions & 111 deletions ajax/registerManagedServer.php

This file was deleted.

22 changes: 22 additions & 0 deletions appinfo/application.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace OCA\OJSXC\AppInfo;

use OCA\OJSXC\Controller\ManagedServerController;
use OCA\OJSXC\Controller\SettingsController;
use OCA\OJSXC\Controller\ExternalApiController;
use OCA\OJSXC\Middleware\ExternalApiMiddleware;
Expand All @@ -19,6 +20,7 @@
use OCA\OJSXC\StanzaHandlers\Presence;
use OCA\OJSXC\StanzaLogger;
use OCA\OJSXC\RawRequest;
use OCA\OJSXC\DataRetriever;
use OCP\AppFramework\App;
use OCA\OJSXC\ILock;
use OCA\OJSXC\DbLock;
Expand Down Expand Up @@ -89,6 +91,19 @@ public function __construct(array $urlParams=array()){
);
});

$container->registerService('ManagedServerController', function(IContainer $c) {
return new ManagedServerController(
$c->query('AppName'),
$c->query('Request'),
$c->query('URLGenerator'),
\OC::$server->getConfig(),
\OC::$server->getUserSession(),
$c->query('Logger'),
$c->query('DataRetriever'),
'https://xmpp.jsxc.ch/registration'
);
});

/**
* Middleware
*/
Expand Down Expand Up @@ -231,6 +246,13 @@ public function __construct(array $urlParams=array()){
return new RawRequest();
});

/**
* Data retriever
*/
$container->registerService('DataRetriever', function($c) {
return new DataRetriever();
});

}

/**
Expand Down
4 changes: 4 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@
$application->registerRoutes($this, array(
'routes' => array(
array('name' => 'http_bind#index', 'url' => '/http-bind', 'verb' => 'POST'),

array('name' => 'settings#index', 'url' => '/settings', 'verb' => 'POST'),
array('name' => 'settings#setAdmin', 'url' => '/settings/admin', 'verb' => 'POST'),
array('name' => 'settings#setUser', 'url' => '/settings/user', 'verb' => 'POST'),
array('name' => 'settings#getIceServers', 'url' => '/settings/iceServers', 'verb' => 'GET'),
array('name' => 'settings#getUsers', 'url' => '/settings/users', 'verb' => 'GET'),

array('name' => 'externalApi#index', 'url' => '/ajax/externalApi.php', 'verb' => 'POST'),
array('name' => 'externalApi#check_password', 'url' => '/api/v2/checkPassword', 'verb' => 'POST'),
array('name' => 'externalApi#is_user', 'url' => '/api/v2/isUser', 'verb' => 'POST'),
array('name' => 'externalApi#shared_roster', 'url' => '/api/v2/sharedRoster', 'verb' => 'POST'),

array('name' => 'managedServer#register', 'url' => '/managedServer/register', 'verb' => 'POST')
)
));
?>
17 changes: 15 additions & 2 deletions js/settings/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ $(document).ready(function() {

$.ajax({
method: 'POST',
url: OC.filePath('ojsxc', 'ajax', 'registerManagedServer.php'),
url: OC.generateUrl('apps/ojsxc/managedServer/register'),
data: {
promotionCode: promotionCode
}
Expand All @@ -260,7 +260,20 @@ $(document).ready(function() {
var errorMsg = (responseJSON && responseJSON.data) ? responseJSON.data.msg : 'unknown error';

msgEl.addClass('jsxc_fail');
msgEl.text('Sorry we couldn\'t complete your registration: ' + errorMsg);
msgEl.append($('<span>').text('Sorry we couldn\'t complete your registration.'));
msgEl.append($('<br>'));
msgEl.append($('<span>').text(errorMsg));
});
});

$('.ojsxc-refresh-registration').click(function(ev){
ev.preventDefault();

var msgEl = $(this).parents('.msg');

msgEl.removeClass('jsxc_success');
msgEl.empty();

$('.ojsxc-managed-registration').show();
});
});
120 changes: 120 additions & 0 deletions lib/Controller/ManagedServerController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

namespace OCA\OJSXC\Controller;

use OCP\AppFramework\Controller;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\IURLGenerator;
use OCP\ILogger;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http;
use OCA\OJSXC\Exceptions\Exception;
use OCA\OJSXC\IDataRetriever;

class ManagedServerController extends Controller
{
private $urlGenerator;
private $config;
private $userSession;
private $logger;
private $dataRetriever;
private $registrationUrl;

public function __construct($appName,
IRequest $request,
IURLGenerator $urlGenerator,
IConfig $config,
IUserSession $userSession,
ILogger $logger,
IDataRetriever $dataRetriever,
$registrationUrl) {
parent::__construct($appName, $request);

$this->urlGenerator = $urlGenerator;
$this->config = $config;
$this->userSession = $userSession;
$this->logger = $logger;
$this->dataRetriever = $dataRetriever;
$this->registrationUrl = $registrationUrl;
}

public function register($promotionCode = null) {
$promotionCode = (preg_match('/^[0-9a-z]+$/i', $promotionCode)) ? $promotionCode : null;
$registrationResult = false;

try {
$registrationResult = $this->doRegistration($promotionCode);
} catch (\Exception $exception) {
$this->logger->warning('RMS: Abort with message: '.$exception->getMessage());

return new JSONResponse(array(
'result' => 'error',
'data' => array(
'msg' => $exception->getMessage()
)
), Http::STATUS_INTERNAL_SERVER_ERROR);
}

if ($registrationResult) {
return array(
'result' => 'success',
'data' => array()
);
}
}

private function doRegistration($promotionCode) {
$apiUrl = $this->urlGenerator->linkToRouteAbsolute('ojsxc.externalApi.index');
$apiSecret = $this->config->getAppValue('ojsxc', 'apiSecret');
$userId = $this->userSession->getUser()->getUID();

$data = array(
'apiUrl' => $apiUrl,
'apiSecret' => $apiSecret,
'apiVersion' => 1,
'userId' => $userId,
'promotionCode' => $promotionCode
);

$response = $this->dataRetriever->fetchUrl($this->registrationUrl, $data);

if ($response['body'] === false) {
throw new Exception('Couldn\'t reach the registration server');
}

$responseJSON = json_decode($response['body']);

if ($responseJSON === null) {
throw new Exception('Couldn\'t parse the response. Response code: '.$response['headers']['response_code']);
}

if ($response['headers']['response_code'] !== 200) {
$this->logger->info('RMS: Response code: '.$response['headers']['response_code']);

throw new Exception(htmlspecialchars($responseJSON->message));
}

if (!preg_match('#^https://#', $responseJSON->boshUrl) ||
!preg_match('#/http-bind/?$#', $responseJSON->boshUrl) ||
preg_match('/\?|#/', $responseJSON->boshUrl)) {
throw new Exception('Got a bad bosh URL');
}

if (!preg_match('/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i', $responseJSON->domain) ||
!preg_match('/^.{1,253}$/', $responseJSON->domain) ||
!preg_match('/^[^\.]{1,63}(\.[^\.]{1,63})*$/', $responseJSON->domain)) {
throw new Exception('Got a bad domain');
}

$this->config->setAppValue('ojsxc', 'serverType', 'managed');
$this->config->setAppValue('ojsxc', 'boshUrl', $responseJSON->boshUrl);
$this->config->setAppValue('ojsxc', 'xmppDomain', $responseJSON->domain);
$this->config->setAppValue('ojsxc', 'timeLimitedToken', 'true');
$this->config->setAppValue('ojsxc', 'managedServer', 'registered');
$this->config->setAppValue('ojsxc', 'externalServices', implode('|', $responseJSON->externalServices));

return true;
}
}
47 changes: 47 additions & 0 deletions lib/DataRetriever.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace OCA\OJSXC;

class DataRetriever implements IDataRetriever {
public function fetchUrl($url, $data = array()) {
$context = stream_context_create(array('http' =>
array(
'method' => 'POST',
'ignore_errors' => '1',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
));

$body = file_get_contents($url, false, $context);
$headers = [];

if ($body !== false) {
$headers = $this->parseHeaders($http_response_header);
}

return [
'body' => $body,
'headers' => $headers
];
}

private function parseHeaders($headers)
{
$head = array();

foreach ($headers as $k=>$v) {
$t = explode(':', $v, 2);
if (isset($t[1])) {
$head[ trim($t[0]) ] = trim($t[1]);
} else {
$head[] = $v;
if (preg_match('#HTTP/[0-9\.]+\s+([0-9]+)#', $v, $out)) {
$head['reponse_code'] = intval($out[1]);
}
}
}

return $head;
}
}
7 changes: 7 additions & 0 deletions lib/IDataRetriever.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace OCA\OJSXC;

interface IDataRetriever {
public function fetchUrl($url, $data);
}
3 changes: 1 addition & 2 deletions lib/Settings/Admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ public function getForm()

$serverType = $this->config->getAppValue('ojsxc', 'serverType');

$apiUrl = \OC::$server->getURLGenerator()->linkTo('ojsxc', 'ajax/externalApi.php');
$apiUrl = \OC::$server->getURLGenerator()->getAbsoluteURL($apiUrl);
$apiUrl = \OC::$server->getURLGenerator()->linkToRouteAbsolute('ojsxc.externalApi.index');

$parameters = [
'serverType' => (!empty($serverType))? $serverType : 'internal',
Expand Down
Loading

0 comments on commit faf8370

Please sign in to comment.