dolibarr  19.0.0-dev
functions_openid_connect.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2022 Jeritiana Ravelojaona <jeritiana.rav@smartone.ai>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16  */
17 
26 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
27 
37 function check_user_password_openid_connect($usertotest, $passwordtotest, $entitytotest)
38 {
39  global $db, $conf, $langs;
40 
41  // Force master entity in transversal mode
42  $entity = $entitytotest;
43  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
44  $entity = 1;
45  }
46 
47  $login = '';
48 
49  dol_syslog("functions_openid_connect::check_user_password_openid_connect usertotest=".$usertotest." passwordtotest=".preg_replace('/./', '*', $passwordtotest)." entitytotest=".$entitytotest);
50 
51  // Step 1 is done by user: request an authorization code
52 
53  if (GETPOSTISSET('username')) {
54  // OIDC does not require credentials here: pass on to next auth handler
55  $_SESSION["dol_loginmesg"] = "Not an OpenID Connect flow";
56  dol_syslog("functions_openid_connect::check_user_password_openid_connect not an OIDC flow");
57  } elseif (GETPOSTISSET('code')) {
58  $auth_code = GETPOST('code', 'aZ09');
59  dol_syslog("functions_openid_connect::check_user_password_openid_connect code=".$auth_code);
60 
61  // Step 2: turn the authorization code into an access token, using client_secret
62  $auth_param = [
63  'grant_type' => 'authorization_code',
64  'client_id' => $conf->global->MAIN_AUTHENTICATION_OIDC_CLIENT_ID,
65  'client_secret' => $conf->global->MAIN_AUTHENTICATION_OIDC_CLIENT_SECRET,
66  'code' => $auth_code,
67  'redirect_uri' => $conf->global->MAIN_AUTHENTICATION_OIDC_REDIRECT_URL
68  ];
69 
70  $token_response = getURLContent($conf->global->MAIN_AUTHENTICATION_OIDC_TOKEN_URL, 'POST', http_build_query($auth_param));
71  $token_content = json_decode($token_response['content']);
72  dol_syslog("functions_openid_connect::check_user_password_openid_connect /token=".print_r($token_response, true), LOG_DEBUG);
73 
74  if (property_exists($token_content, 'access_token')) {
75  // Step 3: retrieve user info using token
76  $userinfo_headers = array('Authorization: Bearer '.$token_content->access_token);
77  $userinfo_response = getURLContent($conf->global->MAIN_AUTHENTICATION_OIDC_USERINFO_URL, 'GET', '', 1, $userinfo_headers);
78  $userinfo_content = json_decode($userinfo_response['content']);
79 
80  dol_syslog("functions_openid_connect::check_user_password_openid_connect /userinfo=".print_r($userinfo_response, true), LOG_DEBUG);
81 
82  // Get the user attribute (claim) matching the Dolibarr login
83  $login_claim = 'email'; // default
84  if (!empty($conf->global->MAIN_AUTHENTICATION_OIDC_LOGIN_CLAIM)) {
85  $login_claim = $conf->global->MAIN_AUTHENTICATION_OIDC_LOGIN_CLAIM;
86  }
87 
88  if (property_exists($userinfo_content, $login_claim)) {
89  // Success: retrieve claim to return to Dolibarr as login
90  $sql = 'SELECT login, entity, datestartvalidity, dateendvalidity';
91  $sql .= ' FROM '.MAIN_DB_PREFIX.'user';
92  $sql .= " WHERE login = '".$db->escape($userinfo_content->$login_claim)."'";
93  $sql .= ' AND entity IN (0,'.(array_key_exists('dol_entity', $_SESSION) ? ((int) $_SESSION["dol_entity"]) : 1).')';
94 
95  dol_syslog("functions_openid::check_user_password_openid", LOG_DEBUG);
96 
97  $resql = $db->query($sql);
98  if ($resql) {
99  $obj = $db->fetch_object($resql);
100  if ($obj) {
101  // Note: Test on validity is done later natively with isNotIntoValidityDateRange() by core after calling checkLoginPassEntity() that call this method
102  /* $now = dol_now();
103  if ($obj->datestartvalidity && $db->jdate($obj->datestartvalidity) > $now) {
104  // Load translation files required by the page
105  $langs->loadLangs(array('main', 'errors'));
106  $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLoginDateValidity");
107  return '--bad-login-validity--';
108  }
109  if ($obj->dateendvalidity && $db->jdate($obj->dateendvalidity) < dol_get_first_hour($now)) {
110  // Load translation files required by the page
111  $langs->loadLangs(array('main', 'errors'));
112  $_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLoginDateValidity");
113  return '--bad-login-validity--';
114  } */
115  $login = $obj->login;
116  }
117  }
118  } elseif ($userinfo_content->error) {
119  // Got user info response but content is an error
120  $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (".$userinfo_content->error_description.")";
121  } elseif ($userinfo_response['http_code'] == 200) {
122  // Claim does not exist
123  $_SESSION["dol_loginmesg"] = "OpenID Connect claim not found: ".$login_claim;
124  } elseif ($userinfo_response['curl_error_no']) {
125  // User info request error
126  $_SESSION["dol_loginmesg"] = "Network error: ".$userinfo_response['curl_error_msg']." (".$userinfo_response['curl_error_no'].")";
127  } else {
128  // Other user info request error
129  $_SESSION["dol_loginmesg"] = "Userinfo request error (".$userinfo_response['http_code'].")";
130  }
131  } elseif ($token_content->error) {
132  // Got token response but content is an error
133  $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (".$token_content->error_description.")";
134  } elseif ($token_response['curl_error_no']) {
135  // Token request error
136  $_SESSION["dol_loginmesg"] = "Network error: ".$token_response['curl_error_msg']." (".$token_response['curl_error_no'].")";
137  } else {
138  // Other token request error
139  $_SESSION["dol_loginmesg"] = "Token request error (".$token_response['http_code'].")";
140  }
141  } else {
142  // No code received
143  $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (no code received)";
144  }
145 
146  dol_syslog("functions_openid_connect::check_user_password_openid_connect END");
147 
148  return !empty($login) ? $login : false;
149 }
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
check_user_password_openid_connect($usertotest, $passwordtotest, $entitytotest)
Check validity of user/password/entity If test is ko, reason must be filled into $_SESSION["dol_login...
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
Definition: geturl.lib.php:41