Skip to content
This repository has been archived by the owner on Mar 4, 2021. It is now read-only.

Commit

Permalink
Better handling of Connect App
Browse files Browse the repository at this point in the history
Update connect app when site settings are updated and during install
so that we control the proper urls. Laid groundwork for handling
connect user declining to give OpenVBX Access.

Updates for Presence integration. Lays foundation for using Twilio
Presence to track online users. Better handles long start-up of
Client on first iframe page load.

Better sub-account handling with new PHP API library.

Minor usability tweaks.
  • Loading branch information
Gipetto committed Sep 19, 2011
1 parent 51886f1 commit 37a366a
Show file tree
Hide file tree
Showing 23 changed files with 368 additions and 107 deletions.
7 changes: 3 additions & 4 deletions INSTALL.markdown
Expand Up @@ -119,10 +119,9 @@ When creating your application use these settings:

1. **Friendly Name:** Any name that makes sense to you.
1. **Company Name & Description:** _Optional_. Anything that makes sense to you.
1. **Homepage URL:** The full url to your webroot. ie: _http://example.org_
1. **Authorize URL:** The path to OpenVBX's Authorize Callback. ie: _http://example.org/authorize/connect_
1. **Deauthorize URL:** _Not used. Leave blank_.
1. **Access Required:** Get All & Post All.
1. **Homepage URL & Authorize URL:** The full url to your webroot. ie: _http://example.org_ - these will be updated by OpenVBX during the install process.
1. **Deauthorize URL:** _Leave blank_. This will be set by OpenVBX during install.
1. **Access Required:** Select "Read all account data" & "Charge account for usage".


## Optional Settings
Expand Down
2 changes: 1 addition & 1 deletion OpenVBX/config/config.php
Expand Up @@ -46,7 +46,7 @@
| you're developing, you'll want to see the plain javascript for debugging.
|
*/
$config['use_unminimized_js'] = TRUE;
$config['use_unminimized_js'] = FALSE;

/*
|--------------------------------------------------------------------------
Expand Down
24 changes: 20 additions & 4 deletions OpenVBX/controllers/account.php
Expand Up @@ -124,10 +124,9 @@ public function edit()
$success = $user->update($this->user_id, $params);

if ($this->response_type == 'json') {
$data = array(
'error' => !$success,
'message' => (!$success ? 'an error occurred while updating the user' : 'user status updated')
);
$data = (isset($this->data) ? $this->data : array());
$data['json']['error'] = !$success;
$data['json']['message'] = (!$success ? 'an error occurred while updating the user' : 'user status updated');
$this->respond('', null, $data);
}
else {
Expand Down Expand Up @@ -204,4 +203,21 @@ public function save_voicemail()
return $data;
}

public function client_status() {
$this->load->helper('twilio');
if ($this->input->post('clientstatus')) {
$accept_incoming = ($this->input->post('online') == 1 ? true : false);
$this->data = array(
'json' => array(
'client_status' => ($accept_incoming ? 'online' : 'offline'),
'client_capability' => generate_capability_token($this->make_rest_access(), $accept_incoming)
)
);
$this->edit();
}
else {
throw new TwilioException('Invalid Request', 400);
exit;
}
}
}
12 changes: 8 additions & 4 deletions OpenVBX/controllers/iframe.php
Expand Up @@ -27,8 +27,6 @@ class Iframe extends User_Controller {

public function __construct() {
parent::__construct();
// make tokens valid for 8 hours
$this->client_token_timeout = 3600*8;
}

function index() {
Expand All @@ -49,12 +47,18 @@ function index() {
$twilio_js_file = 'twilio'.($this->config->item('use_unminimized_js') ? '' : '.min').'.js';
$data['twilio_js'] = $tjs_baseurl.'/libs/twiliojs/1.0/'.$twilio_js_file;

$data['client_capability'] = null;
if (!empty($this->application_sid))
{
$data['client_capability'] = $this->capability->generateToken($this->client_token_timeout);
$data['capability'] = $this->capability;
$user_id = intval($this->session->userdata('user_id'));
$user = VBX_user::get(array('id' => $user_id));
$data['client_capability'] = generate_capability_token($this->make_rest_access(), ($user->online == 1));
}

// internal dev haxies
if (function_exists('twilio_dev_mods')) {
$data = twilio_dev_mods($data);
}
$this->load->view('iframe', $data);
}
}
44 changes: 39 additions & 5 deletions OpenVBX/controllers/install.php
Expand Up @@ -181,10 +181,13 @@ private function get_database_params($database)
$database["char_set"] = "utf8";
$database["dbcollat"] = "utf8_general_ci";

return array('global' => array('active_group' => "default",
'active_record' => TRUE,
),
'default' => $database);
return array(
'global' => array(
'active_group' => "default",
'active_record' => TRUE,
),
'default' => $database
);
}

public function setup()
Expand Down Expand Up @@ -562,8 +565,39 @@ function validate_step3()
// check the connect app if a sid is provided
if (!empty($connect_app)) {
try {
$application = $account->connect_apps->get($connect_app);
$connect_application = $account->connect_apps->get($connect_app);
$friendly_name = $application->friendly_name;

$required_settings = array(
'HomepageUrl' => site_url(),
'AuthorizeRedirectUrl' => site_url('/auth/connect'),
'DeauthorizeCallbackUrl' => site_url('/auth/connect/deauthorize'),
'Permissions' => array(
'get-all',
'post-all'
)
);

$updated = false;
foreach ($required_settings as $key => $setting) {
$app_key = Services_Twilio::decamelize($key);
if ($connect_application->$app_key != $setting) {
$connect_application->$app_key = $setting;
$updated = true;
}
}

if ($updated) {
$connect_application->update(array(
'FriendlyName' => $connect_application->friendly_name,
'Description' => $connect_application->description,
'CompanyName' => $connect_application->company_name,
'HomepageUrl' => $required_settings['HomepageUrl'],
'AuthorizeRedirectUrl' => $required_settings['AuthorizeRedirectUrl'],
'DeauthorizeCallbackUrl' => $required_settings['DeauthorizeCallbackUrl'],
'Permissions' => implode(',', $required_settings['Permissions'])
));
}
}
catch (Exception $e) {
switch ($e->getCode()) {
Expand Down
55 changes: 49 additions & 6 deletions OpenVBX/controllers/settings/site.php
Expand Up @@ -162,9 +162,50 @@ private function update_site()
{
$app_sid = $value;
}
if ($name == 'connect_application_sid') {
$connect_app_sid = $value;
}
$this->settings->set($name, trim($value), $this->tenant->id);
}

// Connect App (if applicable)
if (!empty($connect_app_sid) && $this->tenant->id == VBX_PARENT_TENANT) {
$account = OpenVBX::getAccount();
$connect_app = $account->connect_apps->get($connect_app_sid);

$required_settings = array(
'HomepageUrl' => site_url(),
'AuthorizeRedirectUrl' => site_url('/auth/connect'),
'DeauthorizeCallbackUrl' => site_url('/auth/connect/deauthorize'),
'Permissions' => array(
'get-all',
'post-all'
)
);

$updated = false;
foreach ($required_settings as $key => $setting) {
$app_key = Services_Twilio::decamelize($key);
if ($connect_app->$app_key != $setting) {
$connect_app->$app_key = $setting;
$updated = true;
}
}

if ($updated) {
$connect_app->update(array(
'FriendlyName' => $connect_app->friendly_name,
'Description' => $connect_app->description,
'CompanyName' => $connect_app->company_name,
'HomepageUrl' => $required_settings['HomepageUrl'],
'AuthorizeRedirectUrl' => $required_settings['AuthorizeRedirectUrl'],
'DeauthorizeCallbackUrl' => $required_settings['DeauthorizeCallbackUrl'],
'Permissions' => implode(',', $required_settings['Permissions'])
));
}
}

// Client App
$update_app = false;
if (empty($app_sid) && !empty($current_app_sid))
{
Expand Down Expand Up @@ -211,7 +252,9 @@ private function update_site()

if (!empty($update_app))
{
$account = OpenVBX::getAccount();
if (empty($account)) {
$account = OpenVBX::getAccount();
}

foreach ($update_app as $app)
{
Expand All @@ -223,7 +266,7 @@ private function update_site()
$this->session->set_flashdata('error', 'Could not update Application: '.$e->getMessage());
throw new SiteException($e->getMessage());
}
}
}
}

$this->session->set_flashdata('error', 'Settings have been saved');
Expand All @@ -249,8 +292,8 @@ private function create_application_for_subaccount($tenant_id, $name, $accountSi

$application = false;
try {
$account = OpenVBX::getAccount();
$sub_account = $account->accounts->get($accountSid);
$accounts = OpenVBX::getAccounts();
$sub_account = $accounts->get($accountSid);
foreach ($sub_account->applications as $_application)
{
if ($application->friendly_name == $appName)
Expand Down Expand Up @@ -345,10 +388,10 @@ private function add_tenant()
if ($auth_type === VBX_Settings::AUTH_TYPE_SUBACCOUNT)
{
try {
$account = OpenVBX::getAccount();
$accounts = OpenVBX::getAccounts();

// default, sub-account
$sub_account = $account->accounts->create(array(
$sub_account = $accounts->create(array(
'FriendlyName' => $friendlyName
));
$tenant_sid = $sub_account->sid;
Expand Down
1 change: 0 additions & 1 deletion OpenVBX/controllers/twiml.php
Expand Up @@ -368,7 +368,6 @@ function dial()
$dial = $this->response->dial(NULL, $options);
$dial->client($to);
}

}
else
{
Expand Down
4 changes: 4 additions & 0 deletions OpenVBX/controllers/welcome.php
Expand Up @@ -49,6 +49,10 @@ public function index() {
),
'title' => 'Welcome'
);

if ($tenant_sid = $this->vbx_settings->get('twilio_sid', $this->tenant->id)) {
$data['tenant_sid'] = $tenant_sid;
}
$this->load->view('steps', $data);
}

Expand Down
37 changes: 37 additions & 0 deletions OpenVBX/helpers/twilio_helper.php
Expand Up @@ -20,6 +20,41 @@
* Contributor(s):
**/

if (!function_exists('generate_capability_token')) {
/**
* Generate a capability token for Twilio Client
*
* @param string $allow_incoming
* @return string
*/
function generate_capability_token($rest_access, $allow_incoming = true) {
$ci =& get_instance();
$capability = new Services_Twilio_Capability($ci->twilio_sid, $ci->twilio_token);

$user_id = intval($ci->session->userdata('user_id'));
$user = VBX_user::get(array('id' => $user_id));

$params = array(
'user_id' => $user->user_id,
'rest_access' => $rest_access
);

$token = null;
try {
$capability->allowClientOutgoing($ci->application_sid, $params);
if ($allow_incoming) {
$capability->allowClientIncoming($user->id);
}
$token = $capability->generateToken(VBX_Settings::CLIENT_TOKEN_TIMEOUT);
}
catch (Exception $e) {
error_log($e->getMessage());
}

return $token;
}
}

if (!function_exists('validate_rest_request')) {
/**
* Validate that an incoming rest request is from Twilio
Expand All @@ -31,7 +66,9 @@ function validate_rest_request($failure_message = 'Could not validate this reque
if (!OpenVBX::validateRequest()) {
$response = new TwimlResponse;
$response->say($failure_message);
$response->hangup();
$response->respond();
exit;
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion OpenVBX/libraries/MY_Controller.php
Expand Up @@ -83,7 +83,7 @@ public function __construct()
{
$this->session->set_userdata('loggedin', 0);
$this->session->set_flashdata('error', 'This tenant is no longer active');
return redirect(site_url('auth/logout'));
return redirect(asset_url('auth/logout'));
}

if($this->tenant === false)
Expand All @@ -100,6 +100,7 @@ public function __construct()
$this->twilio_sid = $this->settings->get('twilio_sid', $this->tenant->id);
$token_from = ($this->tenant->type == VBX_Settings::AUTH_TYPE_CONNECT ? VBX_PARENT_TENANT : $this->tenant->id);
$this->twilio_token = $this->settings->get('twilio_token', $token_from);
$this->application_sid = $this->settings->get('application_sid', $this->tenant->id);

// @deprecated, will be removed in a future release
$this->twilio_endpoint = $this->settings->get('twilio_endpoint', VBX_PARENT_TENANT);
Expand Down Expand Up @@ -214,6 +215,7 @@ protected function json_respond($json)
/* Filter out standard templates vars */
$json = $this->build_json_response($json);
$json_str = json_encode($json);
header('content-type: text/javascript');
if(!$pprint)
{
echo $json_str;
Expand Down
13 changes: 13 additions & 0 deletions OpenVBX/libraries/OpenVBX.php
Expand Up @@ -316,6 +316,14 @@ public static function getAccount($twilio_sid = false, $twilio_token = false, $a
return self::$_twilioService->account;
}

public function getAccounts() {
if (!(self::$_twilioService instanceof Services_Twilio)) {
$ci =& get_instance();
self::getAccount();
}
return self::$_twilioService->accounts;
}

/**
* Validate that the current request came from Twilio
*
Expand All @@ -330,6 +338,11 @@ public static function getAccount($twilio_sid = false, $twilio_token = false, $a
*/
public static function validateRequest($url = false, $post_vars = false)
{
$ci =& get_instance();
if ($ci->tenant->type == VBX_Settings::AUTH_TYPE_CONNECT) {
return true;
}

if (!(self::$_twilioValidator instanceof Services_Twilio_RequestValidator))
{
$ci =& get_instance();
Expand Down
10 changes: 7 additions & 3 deletions OpenVBX/libraries/Template.php
Expand Up @@ -471,7 +471,11 @@ function add_js($script, $type = 'import', $defer = FALSE)
switch ($type)
{
case 'dynamic':
$filepath = site_url().preg_replace('|^(/)|', '', $script);
$siteurl = site_url();
if (!preg_match('|.*?/$|', $siteurl)) {
$siteurl .= '/';
}
$filepath = $siteurl.preg_replace('|^(/)|', '', $script);
$js = '<script type="text/javascript" src="'.version_url($filepath).'"';
if ($defer)
{
Expand Down Expand Up @@ -546,7 +550,7 @@ function add_css($style, $type = 'link', $media = FALSE)
if (!function_exists('version_url')) {
$this->CI->load->helper('twilio');
}

switch ($type)
{
case 'dynamic':
Expand All @@ -560,7 +564,7 @@ function add_css($style, $type = 'link', $media = FALSE)
break;

case 'link':
$filepath = (preg_match('|https?://|', $style) ? $style : $filepath);
$filepath = (preg_match('|https?://|', $style) ? $style : site_url().$style);
$css = '<link type="text/css" rel="stylesheet" href="'.version_url($filepath).'"';
if ($media)
{
Expand Down

0 comments on commit 37a366a

Please sign in to comment.