| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259 |
- <?php
- class PluginSinglesignonProvider extends CommonDBTM {
- // From CommonDBTM
- public $dohistory = true;
- static $rightname = 'config';
- /**
- * @var array
- */
- static $default = null;
- /**
- *
- * @var string
- */
- protected $_code = null;
- /**
- *
- * @var null|string
- */
- protected $_token = null;
- /**
- *
- * @var null|array
- */
- protected $_resource_owner = null;
- public static function canCreate() {
- return static::canUpdate();
- }
- public static function canDelete() {
- return static::canUpdate();
- }
- public static function canPurge() {
- return static::canUpdate();
- }
- public static function canView() {
- return static::canUpdate();
- }
- // Should return the localized name of the type
- static function getTypeName($nb = 0) {
- return __sso('Single Sign-on Provider');
- }
- /**
- * @see CommonGLPI::getMenuName()
- * */
- static function getMenuName() {
- return __sso('Single Sign-on');
- }
- function defineTabs($options = []) {
- $ong = [];
- $this->addDefaultFormTab($ong);
- $this->addStandardTab(__CLASS__, $ong, $options);
- $this->addStandardTab('Log', $ong, $options);
- return $ong;
- }
- function post_getEmpty() {
- $this->fields["type"] = 'generic';
- $this->fields["is_active"] = 1;
- }
- function showForm($ID, $options = []) {
- global $CFG_GLPI;
- $this->initForm($ID, $options);
- $this->showFormHeader($options);
- if (empty($this->fields["type"])) {
- $this->fields["type"] = 'generic';
- }
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __('Name') . "</td>";
- echo "<td>";
- Html::autocompletionTextField($this, "name");
- echo "</td>";
- echo "<td>" . __('Comments') . "</td>";
- echo "<td>";
- echo "<textarea name='comment' >" . $this->fields["comment"] . "</textarea>";
- echo "</td></tr>";
- $on_change = 'var _value = this.options[this.selectedIndex].value; $(".sso_url").toggle(_value == "generic");';
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __sso('SSO Type') . "</td><td>";
- self::dropdownType('type', ['value' => $this->fields["type"], 'on_change' => $on_change]);
- echo "<td>" . __('Active') . "</td>";
- echo "<td>";
- Dropdown::showYesNo("is_active", $this->fields["is_active"]);
- echo "</td></tr>\n";
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __sso('Client ID') . "</td>";
- echo "<td><input type='text' style='width:96%' name='client_id' value='" . $this->fields["client_id"] . "'></td>";
- echo "<td>" . __sso('Client Secret') . "</td>";
- echo "<td><input type='text' style='width:96%' name='client_secret' value='" . $this->fields["client_secret"] . "'></td>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __sso('Scope') . "</td>";
- echo "<td><input type='text' style='width:96%' name='scope' value='" . $this->fields["scope"] . "'></td>";
- echo "<td>" . __sso('Extra Options') . "</td>";
- echo "<td><input type='text' style='width:96%' name='extra_options' value='" . $this->fields["extra_options"] . "'></td>";
- echo "</tr>\n";
- $url_style = "";
- if ($this->fields["type"] != 'generic') {
- $url_style = 'style="display: none;"';
- }
- echo "<tr class='tab_bg_1 sso_url' $url_style>";
- echo "<td>" . __sso('Authorize URL') . "</td>";
- echo "<td colspan='3'><input type='text' style='width:96%' name='url_authorize' value='" . $this->fields["url_authorize"] . "'></td>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1 sso_url' $url_style>";
- echo "<td>" . __sso('Access Token URL') . "</td>";
- echo "<td colspan='3'><input type='text' style='width:96%' name='url_access_token' value='" . $this->fields["url_access_token"] . "'></td>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1 sso_url' $url_style>";
- echo "<td>" . __sso('Resource Owner Details URL') . "</td>";
- echo "<td colspan='3'><input type='text' style='width:96%' name='url_resource_owner_details' value='" . $this->fields["url_resource_owner_details"] . "'></td>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1'>";
- echo "<th colspan='4'>" . __('Personalization') . "</th>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __('Background color') . "</td>";
- echo "<td>";
- Html::showColorField(
- 'bgcolor',
- [
- 'value' => $this->fields['bgcolor'],
- ]
- );
- echo " ";
- echo Html::getCheckbox([
- 'title' => __('Clear'),
- 'name' => '_blank_bgcolor',
- 'checked' => empty($this->fields['bgcolor']),
- ]);
- echo " " . __('Clear');
- echo "</td>";
- echo "<td>" . __('Color') . "</td>";
- echo "<td>";
- Html::showColorField(
- 'color',
- [
- 'value' => $this->fields['color'],
- ]
- );
- echo " ";
- echo Html::getCheckbox([
- 'title' => __('Clear'),
- 'name' => '_blank_color',
- 'checked' => empty($this->fields['color']),
- ]);
- echo " " . __('Clear');
- echo "</td>";
- echo "</tr>\n";
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __('Picture') . "</td>";
- echo "<td colspan='3'>";
- if (!empty($this->fields['picture'])) {
- echo Html::image(static::getPictureUrl($this->fields['picture']), [
- 'style' => '
- max-width: 100px;
- max-height: 100px;
- background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
- background-size: 10px 10px;
- background-position: 0 0, 0 5px, 5px -5px, -5px 0px;',
- 'class' => 'picture_square'
- ]);
- echo " ";
- echo Html::getCheckbox([
- 'title' => __('Clear'),
- 'name' => '_blank_picture'
- ]);
- echo " " . __('Clear');
- } else {
- echo Html::file([
- 'name' => 'picture',
- 'onlyimages' => true,
- ]);
- }
- echo "</td>";
- echo "</tr>\n";
- echo '<script type="text/javascript">
- $("[name=bgcolor]").on("change", function (e) {
- $("[name=_blank_bgcolor]").prop("checked", false).attr("checked", false);
- });
- $("[name=color]").on("change", function (e) {
- $("[name=_blank_color]").prop("checked", false).attr("checked", false);
- });
- </script>';
- if ($ID) {
- echo "<tr class='tab_bg_1'>";
- echo "<th colspan='4'>" . __('Test') . "</th>";
- echo "</tr>\n";
- $url = self::getCallbackUrl($ID);
- $fullUrl = $this->getBaseURL() . $url;
- echo "<tr class='tab_bg_1'>";
- echo "<td>" . __sso('Callback URL') . "</td>";
- echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
- echo "</tr>\n";
- $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
- }
- $this->showFormButtons($options);
- if ($ID) {
- echo '<script type="text/javascript">
- $("[name=test_singlesignon]").on("click", function (e) {
- e.preventDefault();
- var url = $("#singlesignon_callbackurl").attr("data-url") + "/test/1";
- var left = ($(window).width()/2)-(600/2);
- var top = ($(window).height()/2)-(800/2);
- var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
- if (window.focus) {
- newWindow.focus();
- }
- });
- </script>';
- }
- return true;
- }
- function prepareInputForAdd($input) {
- return $this->prepareInput($input);
- }
- function prepareInputForUpdate($input) {
- return $this->prepareInput($input);
- }
- function cleanDBonPurge() {
- static::deletePicture($this->fields['picture']);
- }
- /**
- * Prepares input (for update and add)
- *
- * @param array $input Input data
- *
- * @return array
- */
- private function prepareInput($input) {
- $error_detected = [];
- $type = '';
- //check for requirements
- if (isset($input['type'])) {
- $type = $input['type'];
- }
- if (!isset($input['name']) || empty($input['name'])) {
- $error_detected[] = __sso('A Name is required');
- }
- if (empty($type)) {
- $error_detected[] = __('An item type is required');
- } else if (!isset(static::getTypes()[$type])) {
- $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
- }
- if (!isset($input['client_id']) || empty($input['client_id'])) {
- $error_detected[] = __sso('A Client ID is required');
- }
- if (!isset($input['client_secret']) || empty($input['client_secret'])) {
- $error_detected[] = __sso('A Client Secret is required');
- }
- if ($type === 'generic') {
- if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
- $error_detected[] = __sso('An Authorize URL is required');
- } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
- $error_detected[] = __sso('The Authorize URL is invalid');
- }
- if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
- $error_detected[] = __sso('An Access Token URL is required');
- } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
- $error_detected[] = __sso('The Access Token URL is invalid');
- }
- if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
- $error_detected[] = __sso('A Resource Owner Details URL is required');
- } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
- $error_detected[] = __sso('The Resource Owner Details URL is invalid');
- }
- }
- if (count($error_detected)) {
- foreach ($error_detected as $error) {
- Session::addMessageAfterRedirect(
- $error,
- true,
- ERROR
- );
- }
- return false;
- }
- if (
- isset($input["_blank_bgcolor"])
- && $input["_blank_bgcolor"]
- ) {
- $input['bgcolor'] = '';
- }
- if (
- isset($input["_blank_color"])
- && $input["_blank_color"]
- ) {
- $input['color'] = '';
- }
- if (
- isset($input["_blank_picture"])
- && $input["_blank_picture"]
- ) {
- $input['picture'] = '';
- if (array_key_exists('picture', $this->fields)) {
- static::deletePicture($this->fields['picture']);
- }
- }
- if (isset($input["_picture"])) {
- $picture = array_shift($input["_picture"]);
- if ($dest = static::savePicture(GLPI_TMP_DIR . '/' . $picture)) {
- $input['picture'] = $dest;
- } else {
- Session::addMessageAfterRedirect(__('Unable to save picture file.'), true, ERROR);
- }
- if (array_key_exists('picture', $this->fields)) {
- static::deletePicture($this->fields['picture']);
- }
- }
- return $input;
- }
- function getSearchOptions() {
- // For GLPI <= 9.2
- $options = [];
- foreach ($this->rawSearchOptions() as $opt) {
- if (!isset($opt['id'])) {
- continue;
- }
- $optid = $opt['id'];
- unset($opt['id']);
- if (isset($options[$optid])) {
- $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " .
- get_class($this) . " searchOptions!";
- Toolbox::logDebug($message);
- }
- foreach ($opt as $k => $v) {
- $options[$optid][$k] = $v;
- }
- }
- return $options;
- }
- function rawSearchOptions() {
- $tab = [];
- $tab[] = [
- 'id' => 'common',
- 'name' => __('Characteristics'),
- ];
- $tab[] = [
- 'id' => 1,
- 'table' => $this->getTable(),
- 'field' => 'name',
- 'name' => __('Name'),
- 'datatype' => 'itemlink',
- ];
- $tab[] = [
- 'id' => 2,
- 'table' => $this->getTable(),
- 'field' => 'type',
- 'name' => __('Type'),
- 'searchtype' => 'equals',
- 'datatype' => 'specific',
- ];
- $tab[] = [
- 'id' => 3,
- 'table' => $this->getTable(),
- 'field' => 'client_id',
- 'name' => __sso('Client ID'),
- 'datatype' => 'text',
- ];
- $tab[] = [
- 'id' => 4,
- 'table' => $this->getTable(),
- 'field' => 'client_secret',
- 'name' => __sso('Client Secret'),
- 'datatype' => 'text',
- ];
- $tab[] = [
- 'id' => 5,
- 'table' => $this->getTable(),
- 'field' => 'scope',
- 'name' => __sso('Scope'),
- 'datatype' => 'text',
- ];
- $tab[] = [
- 'id' => 6,
- 'table' => $this->getTable(),
- 'field' => 'extra_options',
- 'name' => __sso('Extra Options'),
- 'datatype' => 'specific',
- ];
- $tab[] = [
- 'id' => 7,
- 'table' => $this->getTable(),
- 'field' => 'url_authorize',
- 'name' => __sso('Authorize URL'),
- 'datatype' => 'weblink',
- ];
- $tab[] = [
- 'id' => 8,
- 'table' => $this->getTable(),
- 'field' => 'url_access_token',
- 'name' => __sso('Access Token URL'),
- 'datatype' => 'weblink',
- ];
- $tab[] = [
- 'id' => 9,
- 'table' => $this->getTable(),
- 'field' => 'url_resource_owner_details',
- 'name' => __sso('Resource Owner Details URL'),
- 'datatype' => 'weblink',
- ];
- $tab[] = [
- 'id' => 10,
- 'table' => $this->getTable(),
- 'field' => 'is_active',
- 'name' => __('Active'),
- 'searchtype' => 'equals',
- 'datatype' => 'bool',
- ];
- $tab[] = [
- 'id' => 30,
- 'table' => $this->getTable(),
- 'field' => 'id',
- 'name' => __('ID'),
- 'datatype' => 'itemlink',
- ];
- return $tab;
- }
- static function getSpecificValueToDisplay($field, $values, array $options = []) {
- if (!is_array($values)) {
- $values = [$field => $values];
- }
- switch ($field) {
- case 'type':
- return self::getTicketTypeName($values[$field]);
- case 'extra_options':
- return '<pre>' . $values[$field] . '</pre>';
- }
- return '';
- }
- static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
- if (!is_array($values)) {
- $values = [$field => $values];
- }
- $options['display'] = false;
- switch ($field) {
- case 'type':
- $options['value'] = $values[$field];
- return self::dropdownType($name, $options);
- }
- return parent::getSpecificValueToSelect($field, $name, $values, $options);
- }
- /**
- * Get ticket types
- *
- * @return array of types
- * */
- static function getTypes() {
- $options['generic'] = __sso('Generic');
- $options['facebook'] = __sso('Facebook');
- $options['github'] = __sso('GitHub');
- $options['google'] = __sso('Google');
- $options['instagram'] = __sso('Instagram');
- $options['linkedin'] = __sso('LinkdeIn');
- return $options;
- }
- /**
- * Get ticket type Name
- *
- * @param $value type ID
- * */
- static function getTicketTypeName($value) {
- $tab = static::getTypes();
- // Return $value if not defined
- return (isset($tab[$value]) ? $tab[$value] : $value);
- }
- /**
- * Dropdown of ticket type
- *
- * @param $name select name
- * @param $options array of options:
- * - value : integer / preselected value (default 0)
- * - toadd : array / array of specific values to add at the begining
- * - on_change : string / value to transmit to "onChange"
- * - display : boolean / display or get string (default true)
- *
- * @return string id of the select
- * */
- static function dropdownType($name, $options = []) {
- $params['value'] = 0;
- $params['toadd'] = [];
- $params['on_change'] = '';
- $params['display'] = true;
- if (is_array($options) && count($options)) {
- foreach ($options as $key => $val) {
- $params[$key] = $val;
- }
- }
- $items = [];
- if (count($params['toadd']) > 0) {
- $items = $params['toadd'];
- }
- $items += self::getTypes();
- return Dropdown::showFromArray($name, $items, $params);
- }
- /**
- * Get an history entry message
- *
- * @param $data Array from glpi_logs table
- *
- * @since GLPI version 0.84
- *
- * @return string
- * */
- static function getHistoryEntry($data) {
- switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
- case 0:
- return __('History from plugin example', 'example');
- }
- return '';
- }
- //////////////////////////////
- ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
- /**
- * @since version 0.85
- *
- * @see CommonDBTM::getSpecificMassiveActions()
- * */
- function getSpecificMassiveActions($checkitem = null) {
- $actions = parent::getSpecificMassiveActions($checkitem);
- $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
- $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
- return $actions;
- }
- /**
- * @since version 0.85
- *
- * @see CommonDBTM::showMassiveActionsSubForm()
- * */
- static function showMassiveActionsSubForm(MassiveAction $ma) {
- switch ($ma->getAction()) {
- case 'DoIt':
- echo " <input type='hidden' name='toto' value='1'>" .
- Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
- " " . __('Write in item history', 'example');
- return true;
- case 'do_nothing':
- echo " " . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
- " " . __('but do nothing :)', 'example');
- return true;
- }
- return parent::showMassiveActionsSubForm($ma);
- }
- /**
- * @since version 0.85
- *
- * @see CommonDBTM::processMassiveActionsForOneItemtype()
- * */
- static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
- global $DB;
- switch ($ma->getAction()) {
- case 'DoIt':
- if ($item->getType() == 'Computer') {
- Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
- Session::addMessageAfterRedirect(__('Write in item history', 'example'));
- $changes = [0, 'old value', 'new value'];
- foreach ($ids as $id) {
- if ($item->getFromDB($id)) {
- Session::addMessageAfterRedirect("- " . $item->getField("name"));
- Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
- $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
- } else {
- // Example of ko count
- $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
- }
- }
- } else {
- // When nothing is possible ...
- $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
- }
- return;
- case 'do_nothing':
- if ($item->getType() == 'PluginExampleExample') {
- Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
- Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
- foreach ($ids as $id) {
- if ($item->getFromDB($id)) {
- Session::addMessageAfterRedirect("- " . $item->getField("name"));
- $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
- } else {
- // Example for noright / Maybe do it with can function is better
- $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
- }
- }
- } else {
- $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
- }
- return;
- }
- parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
- }
- static function getIcon() {
- return "fas fa-user-lock";
- }
- public static function getDefault($type, $key, $default = null) {
- if (static::$default === null) {
- $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
- static::$default = json_decode($content, true);
- }
- if (isset(static::$default[$type]) && static::$default[$type][$key]) {
- return static::$default[$type][$key];
- }
- return $default;
- }
- public function getClientType() {
- $value = "generic";
- if (isset($this->fields['type']) && !empty($this->fields['type'])) {
- $value = $this->fields['type'];
- }
- return $value;
- }
- public function getClientId() {
- $value = "";
- if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
- $value = $this->fields['client_id'];
- }
- return $value;
- }
- public function getClientSecret() {
- $value = "";
- if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
- $value = $this->fields['client_secret'];
- }
- return $value;
- }
- public function getScope() {
- $type = $this->getClientType();
- $value = static::getDefault($type, "scope");
- $fields = $this->fields;
- if (!isset($fields['scope']) || empty($fields['scope'])) {
- $fields['scope'] = $value;
- }
- $fields = Plugin::doHookFunction("sso:scope", $fields);
- return $fields['scope'];
- }
- public function getAuthorizeUrl() {
- $type = $this->getClientType();
- $value = static::getDefault($type, "url_authorize");
- $fields = $this->fields;
- if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
- $fields['url_authorize'] = $value;
- }
- $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
- return $fields['url_authorize'];
- }
- public function getAccessTokenUrl() {
- $type = $this->getClientType();
- $value = static::getDefault($type, "url_access_token");
- $fields = $this->fields;
- if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
- $fields['url_access_token'] = $value;
- }
- $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
- return $fields['url_access_token'];
- }
- public function getResourceOwnerDetailsUrl($access_token) {
- $type = $this->getClientType();
- $value = static::getDefault($type, "url_resource_owner_details", "");
- $fields = $this->fields;
- $fields['access_token'] = $access_token;
- if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
- $fields['url_resource_owner_details'] = $value;
- }
- $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
- $url = $fields['url_resource_owner_details'];
- $url = str_replace("<access_token>", $access_token, $url);
- $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
- return $url;
- }
- /**
- * Get current URL without query string
- * @return string
- */
- private function getBaseURL() {
- $baseURL = "";
- if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
- $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
- } else if (isset($_SERVER["HTTPS"])) {
- $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
- } else {
- $baseURL = "http://";
- }
- if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
- $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
- } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
- $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
- } else {
- $baseURL .= $_SERVER["SERVER_NAME"];
- }
- $port = $_SERVER["SERVER_PORT"];
- if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
- $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
- }
- if ($port != "80" && $port != "443") {
- $baseURL .= ":" . $_SERVER["SERVER_PORT"];
- }
- return $baseURL;
- }
- /**
- * Get current URL without query string
- * @return string
- */
- private function getCurrentURL() {
- $currentURL = $this->getBaseURL();
- // $currentURL .= $_SERVER["REQUEST_URI"];
- // Ignore Query String
- if (isset($_SERVER["SCRIPT_NAME"])) {
- $currentURL .= $_SERVER["SCRIPT_NAME"];
- }
- if (isset($_SERVER["PATH_INFO"])) {
- $currentURL .= $_SERVER["PATH_INFO"];
- }
- return $currentURL;
- }
- /**
- *
- * @return boolean|string
- */
- public function checkAuthorization() {
- if (isset($_GET['error'])) {
- $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
- Html::displayErrorAndDie(__($error_description), true);
- }
- if (!isset($_GET['code'])) {
- $params = [
- 'client_id' => $this->getClientId(),
- 'scope' => $this->getScope(),
- 'state' => Session::getNewCSRFToken(),
- 'response_type' => 'code',
- 'approval_prompt' => 'auto',
- 'redirect_uri' => $this->getCurrentURL(),
- ];
- $params = Plugin::doHookFunction("sso:authorize_params", $params);
- $url = $this->getAuthorizeUrl();
- $glue = strstr($url, '?') === false ? '?' : '&';
- $url .= $glue . http_build_query($params);
- header('Location: ' . $url);
- exit;
- }
- // Check given state against previously stored one to mitigate CSRF attack
- $state = isset($_GET['state']) ? $_GET['state'] : '';
- Session::checkCSRF([
- '_glpi_csrf_token' => $state,
- ]);
- $this->_code = $_GET['code'];
- return $_GET['code'];
- }
- /**
- *
- * @return boolean|string
- */
- public function getAccessToken() {
- if ($this->_token !== null) {
- return $this->_token;
- }
- if ($this->_code === null) {
- return false;
- }
- $params = [
- 'client_id' => $this->getClientId(),
- 'client_secret' => $this->getClientSecret(),
- 'redirect_uri' => $this->getCurrentURL(),
- 'grant_type' => 'authorization_code',
- 'code' => $this->_code,
- ];
- $params = Plugin::doHookFunction("sso:access_token_params", $params);
- $url = $this->getAccessTokenUrl();
- $content = Toolbox::callCurl($url, [
- CURLOPT_HTTPHEADER => [
- "Accept: application/json",
- ],
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => http_build_query($params),
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_SSL_VERIFYPEER => false,
- ]);
- try {
- $data = json_decode($content, true);
- if (!isset($data['access_token'])) {
- return false;
- }
- $this->_token = $data['access_token'];
- } catch (\Exception $ex) {
- return false;
- }
- return $this->_token;
- }
- /**
- *
- * @return boolean|array
- */
- public function getResourceOwner() {
- if ($this->_resource_owner !== null) {
- return $this->_resource_owner;
- }
- $token = $this->getAccessToken();
- if (!$token) {
- return false;
- }
- $url = $this->getResourceOwnerDetailsUrl($token);
- $headers = [
- "Accept:application/json",
- "Authorization:Bearer $token",
- ];
- $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
- $content = Toolbox::callCurl($url, [
- CURLOPT_HTTPHEADER => $headers,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_SSL_VERIFYPEER => false,
- ]);
- try {
- $data = json_decode($content, true);
- $this->_resource_owner = $data;
- } catch (\Exception $ex) {
- return false;
- }
- if ($this->getClientType() === "linkedin") {
- $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
- $content = Toolbox::callCurl($email_url, [
- CURLOPT_HTTPHEADER => $headers,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_SSL_VERIFYPEER => false,
- ]);
- try {
- $data = json_decode($content, true);
- $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
- } catch (\Exception $ex) {
- return false;
- }
- }
- return $this->_resource_owner;
- }
- public function findUser() {
- $resource_array = $this->getResourceOwner();
- if (!$resource_array) {
- return false;
- }
- $user = new User();
- //First: check linked user
- $id = Plugin::doHookFunction("sso:find_user", $resource_array);
- if (is_numeric($id) && $user->getFromDB($id)) {
- return $user;
- }
- $email = false;
- $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
- foreach ($email_fields as $field) {
- if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
- $email = $resource_array[$field];
- break;
- }
- }
- $default_condition = '';
- if (version_compare(GLPI_VERSION, '9.3', '>=')) {
- $default_condition = [];
- }
- if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
- return $user;
- }
- $login = false;
- $login_fields = ['login', 'username', 'id'];
- foreach ($login_fields as $field) {
- if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
- $login = $resource_array[$field];
- break;
- }
- }
- if ($login && $user->getFromDBbyName($login)) {
- return $user;
- }
- return false;
- }
- public function login() {
- $user = $this->findUser();
- if (!$user) {
- return false;
- }
- //Create fake auth
- $auth = new Auth();
- $auth->user = $user;
- $auth->auth_succeded = true;
- $auth->extauth = 1;
- $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
- $auth->user->fields['authtype'] = Auth::DB_GLPI;
- Session::init($auth);
- return $auth->auth_succeded;
- }
- public function linkUser($user_id) {
- /** @var User */
- $user = User::getById($user_id);
- if (!$user) {
- return;
- }
- $resource_array = $this->getResourceOwner();
- if (!$resource_array) {
- return false;
- }
- $link = new PluginSinglesignonProvider_User();
- return $link->add([
- 'plugin_singlesignon_providers_id' => $this->fields['id'],
- 'users_id' => $user_id,
- 'remote_id' => $resource_array['id'],
- ]);
- }
- /**
- * Generate a URL to callback
- * Some providers don't accept query string, it convert to PATH
- * @global array $CFG_GLPI
- * @param integer $id
- * @param array $query
- * @return string
- */
- public static function getCallbackUrl($id, $query = []) {
- global $CFG_GLPI;
- $url = $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/callback.php';
- $url .= "/provider/$id";
- if (!empty($query)) {
- $url .= "/q/" . base64_encode(http_build_query($query));
- }
- return $url;
- }
- public static function getCallbackParameters($name = null) {
- $data = [];
- if (isset($_SERVER['PATH_INFO'])) {
- $path_info = trim($_SERVER['PATH_INFO'], '/');
- $parts = explode('/', $path_info);
- $key = null;
- foreach ($parts as $part) {
- if ($key === null) {
- $key = $part;
- } else {
- if ($key === "provider" || $key === "test") {
- $part = intval($part);
- } else {
- $tmp = base64_decode($part);
- parse_str($tmp, $part);
- }
- if ($key === $name) {
- return $part;
- }
- $data[$key] = $part;
- $key = null;
- }
- }
- }
- if (!isset($data[$name])) {
- return null;
- }
- return $data;
- }
- static public function startsWith($haystack, $needle) {
- $length = strlen($needle);
- return (substr($haystack, 0, $length) === $needle);
- }
- static function getPictureUrl($path) {
- global $CFG_GLPI;
- $path = Html::cleanInputText($path); // prevent xss
- if (empty($path)) {
- return null;
- }
- return $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/picture.send.php?path=' . $path;
- }
- static public function savePicture($src, $uniq_prefix = null) {
- if (function_exists('Document::isImage') && !Document::isImage($src)) {
- return false;
- }
- $filename = uniqid($uniq_prefix);
- $ext = pathinfo($src, PATHINFO_EXTENSION);
- $subdirectory = substr($filename, -2); // subdirectory based on last 2 hex digit
- $basePath = GLPI_PLUGIN_DOC_DIR . "/singlesignon";
- $i = 0;
- do {
- // Iterate on possible suffix while dest exists.
- // This case will almost never exists as dest is based on an unique id.
- $dest = $basePath
- . '/' . $subdirectory
- . '/' . $filename . ($i > 0 ? '_' . $i : '') . '.' . $ext;
- $i++;
- } while (file_exists($dest));
- if (!is_dir($basePath . '/' . $subdirectory) && !mkdir($basePath . '/' . $subdirectory)) {
- return false;
- }
- if (!rename($src, $dest)) {
- return false;
- }
- return substr($dest, strlen($basePath . '/')); // Return dest relative to GLPI_PICTURE_DIR
- }
- public static function deletePicture($path) {
- $basePath = GLPI_PLUGIN_DOC_DIR . "/singlesignon";
- $fullpath = $basePath . '/' . $path;
- if (!file_exists($fullpath)) {
- return false;
- }
- $fullpath = realpath($fullpath);
- if (!static::startsWith($fullpath, realpath($basePath))) {
- return false;
- }
- return @unlink($fullpath);
- }
- public static function renderButton($url, $data, $class = 'oauth-login') {
- $btn = '<span><a href="' . $url . '" class="singlesignon vsubmit ' . $class . '"';
- $style = '';
- if ((isset($data['bgcolor']) && $data['bgcolor'])) {
- $style .= 'background-color: ' . $data['bgcolor'] . ';';
- }
- if ((isset($data['color']) && $data['color'])) {
- $style .= 'color: ' . $data['color'] . ';';
- }
- if ($style) {
- $btn .= ' style="' . $style . '"';
- }
- $btn .= '>';
- if (isset($data['picture']) && $data['picture']) {
- $btn .= Html::image(
- static::getPictureUrl($data['picture']),
- [
- 'style' => 'max-height: 20px;',
- ]
- );
- $btn .= ' ';
- }
- $btn .= sprintf(__sso('Login with %s'), $data['name']);
- $btn .= '</a></span>';
- return $btn;
- }
- }
|