Files
2018-12-15 20:56:39 +08:00

110 lines
3.6 KiB
PHP

<?php
if (!defined('ABSPATH'))
{
exit;
}
class GTMA_SSO
{
protected $token = '';
protected $portalURL = '';
function __construct()
{
add_action('admin_menu', array($this, 'gtma_menu'));
if (is_user_logged_in())
{
add_action('template_redirect', array($this, 'gtma_redirect'));
}
}
function gtma_menu()
{
add_options_page(__('GoToMyAccount SSO'), __('GoToMyAccounts SSO', 'gtma_sso'), 'manage_options', "gtma_sso", array($this, "render_settings"), "dashicons-palmtree", 40);
}
function render_settings()
{
$page = (!empty($_GET['page'])) ? esc_attr($_GET['page']) : '';
$action = (!empty($_GET['action'])) ? esc_attr($_GET['action']) : '';
$id = (!empty($_GET['id'])) ? esc_attr($_GET['id']) : '';
if ($page == 'gtma_sso' && $action == 'delete' && $id != '')
{
$gtma_redirects = get_option('gtma_sso_redirects', array());
unset($gtma_redirects[$id]);
update_option('gtma_sso_redirects', $gtma_redirects);
}
if (isset($_POST['gmta_sso_submit']) && $page == 'gtma_sso')
{
update_option('gtma_portal_url', sanitize_text_field($_POST['gtma_portal_url']));
update_option('gtma_sso_password', sanitize_text_field($_POST['gtma_sso_password']));
$redirect = $_POST['redirect'];
$gtma_redirects = get_option('gtma_sso_redirects', array());
$gtma_redirects[$redirect['page']] = $redirect['address'];
update_option('gtma_sso_redirects', $gtma_redirects);
}
include(GTMA_SSO_INC . "gtma-settings.php");
}
function get_token()
{
$token = '';
$portalURL = get_option('gtma_portal_url', '');
$sso_password = get_option('gtma_sso_password', '');
$user = wp_get_current_user();
$email = $user->user_email;
if ($portalURL != '' && $sso_password != '')
{
try
{
$url = "https://appapi.gotomyaccounts.com/v1/SSO/?email=" . urlencode($email) . "&portal_hostname=" . urlencode($portalURL);
$args = array(
'method' => 'GET',
'timeout' => 60,
'sslverify' => false,
'headers' => array( "Authorization" => $sso_password ),
'body' => array(),
'cookies' => false
);
$response = wp_safe_remote_get($url, $args);
if (!is_wp_error($response))
{
$result = $response['response'];
if ($result['code'] == 200 && $result['message'] == 'OK')
{
$token = $response['body'];
} else
{
$token = '';
}
} else
{
$token = '';
}
} catch (Exception $exc)
{
$token = '';
}
}
return $token;
}
function gtma_redirect()
{
$gtma_redirects = get_option('gtma_sso_redirects', array());
$ids = array_keys($gtma_redirects);
$token = $this->get_token();
$portalURL = get_option('gtma_portal_url', '');
$id = get_the_ID();
if ((in_array($id, $ids)) && !empty($token) && !empty($portalURL))
{
$link = "https://" . $portalURL . "/sso?token=" . urlencode($token) . "&page=" . $gtma_redirects[$id];
wp_redirect($link);
exit;
}
}
}