dolibarr 21.0.0-alpha
functions_openid_connect.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2022 Jeritiana Ravelojaona <jeritiana.rav@smartone.ai>
3 * Copyright (C) 2023-2024 Solution Libre SAS <contact@solution-libre.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Maximilien Rozniecki <mrozniecki@easya.solutions>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
29include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
30include_once DOL_DOCUMENT_ROOT.'/core/lib/openid_connect.lib.php';
31
41function check_user_password_openid_connect($usertotest, $passwordtotest, $entitytotest)
42{
43 global $db;
44
45 if (getDolGlobalInt('MAIN_MODULE_OPENIDCONNECT', 0) <= 0) {
46 $_SESSION["dol_loginmesg"] = "OpenID Connect is disabled";
47 dol_syslog("functions_openid_connect::check_user_password_openid_connect Module disabled");
48 return false;
49 }
50
51 // Force master entity in transversal mode
52 $entity = $entitytotest;
53 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
54 $entity = 1;
55 }
56
57 dol_syslog("functions_openid_connect::check_user_password_openid_connect usertotest=".$usertotest." passwordtotest=".preg_replace('/./', '*', $passwordtotest)." entitytotest=".$entitytotest);
58
59 // Step 1 is done by user: request an authorization code
60
61 if (GETPOSTISSET('username')) {
62 // OIDC does not require credentials here: pass on to next auth handler
63 $_SESSION["dol_loginmesg"] = "Not an OpenID Connect flow";
64 dol_syslog("functions_openid_connect::check_user_password_openid_connect::not an OIDC flow");
65 return false;
66 } elseif (!GETPOSTISSET('state')) {
67 // No state received
68 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (no state received)";
69 dol_syslog("functions_openid_connect::check_user_password_openid_connect::no state received", LOG_ERR);
70 return false;
71 } elseif (!GETPOSTISSET('code')) {
72 // No code received
73 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (no code received)";
74 dol_syslog("functions_openid_connect::check_user_password_openid_connect::no code received", LOG_ERR);
75 return false;
76 }
77
78 $auth_code = GETPOST('code', 'aZ09');
79 $state = GETPOST('state', 'aZ09');
80 dol_syslog('functions_openid_connect::check_user_password_openid_connect code='.$auth_code.' state='.$state);
81
82 if ($state !== openid_connect_get_state()) {
83 // State does not match
84 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (state does not match)";
85 dol_syslog("functions_openid_connect::check_user_password_openid_connect::state does not match", LOG_ERR);
86 return false;
87 }
88
89 // Step 2: turn the authorization code into an access token, using client_secret
90 $auth_param = [
91 'grant_type' => 'authorization_code',
92 'client_id' => getDolGlobalString('MAIN_AUTHENTICATION_OIDC_CLIENT_ID'),
93 'client_secret' => getDolGlobalString('MAIN_AUTHENTICATION_OIDC_CLIENT_SECRET'),
94 'code' => $auth_code,
95 'redirect_uri' => openid_connect_get_redirect_url()
96 ];
97
98 $token_response = getURLContent(getDolGlobalString('MAIN_AUTHENTICATION_OIDC_TOKEN_URL'), 'POST', http_build_query($auth_param), 1, array(), array('https'), 2);
99 $token_content = json_decode($token_response['content']);
100 dol_syslog("functions_openid_connect::check_user_password_openid_connect /token=".print_r($token_response, true), LOG_DEBUG);
101
102 if ($token_response['curl_error_no']) {
103 // Token request error
104 $_SESSION["dol_loginmesg"] = "Network error: ".$token_response['curl_error_msg']." (".$token_response['curl_error_no'].")";
105 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$_SESSION["dol_loginmesg"], LOG_ERR);
106 return false;
107 } elseif ($token_response['http_code'] >= 400 && $token_response['http_code'] < 500) {
108 // HTTP Error
109 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (".$token_response['content'].")";
110 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$token_response['content'], LOG_ERR);
111 return false;
112 } elseif ($token_content->error) {
113 // Got token response but content is an error
114 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (".$token_content->error_description.")";
115 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$token_content->error_description, LOG_ERR);
116 return false;
117 } elseif (!property_exists($token_content, 'access_token')) {
118 // Other token request error
119 $_SESSION["dol_loginmesg"] = "Token request error (".$token_response['http_code'].")";
120 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$_SESSION["dol_loginmesg"], LOG_ERR);
121 return false;
122 }
123
124 // Step 3: retrieve user info using token
125 $userinfo_headers = array('Authorization: Bearer '.$token_content->access_token);
126 $userinfo_response = getURLContent(getDolGlobalString('MAIN_AUTHENTICATION_OIDC_USERINFO_URL'), 'GET', '', 1, $userinfo_headers, array('https'), 2);
127 $userinfo_content = json_decode($userinfo_response['content']);
128
129 dol_syslog("functions_openid_connect::check_user_password_openid_connect /userinfo=".print_r($userinfo_response, true), LOG_DEBUG);
130
131 // Get the user attribute (claim) matching the Dolibarr login
132 $login_claim = 'email'; // default
133 if (getDolGlobalString('MAIN_AUTHENTICATION_OIDC_LOGIN_CLAIM')) {
134 $login_claim = getDolGlobalString('MAIN_AUTHENTICATION_OIDC_LOGIN_CLAIM');
135 }
136
137 if ($userinfo_response['curl_error_no']) {
138 // User info request error
139 $_SESSION["dol_loginmesg"] = "Network error: ".$userinfo_response['curl_error_msg']." (".$userinfo_response['curl_error_no'].")";
140 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$_SESSION["dol_loginmesg"], LOG_ERR);
141 return false;
142 } elseif ($userinfo_response['http_code'] >= 400 && $userinfo_response['http_code'] < 500) {
143 // HTTP Error
144 $_SESSION["dol_loginmesg"] = "OpenID Connect user info error: " . $userinfo_response['content'];
145 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$userinfo_response['content'], LOG_ERR);
146 return false;
147 } elseif ($userinfo_content->error) {
148 // Got user info response but content is an error
149 $_SESSION["dol_loginmesg"] = "Error in OAuth 2.0 flow (".$userinfo_content->error_description.")";
150 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$userinfo_content->error_description, LOG_ERR);
151 return false;
152 } elseif (!property_exists($userinfo_content, $login_claim)) {
153 // Other user info request error
154 $_SESSION["dol_loginmesg"] = "Userinfo request error (".$userinfo_response['http_code'].")";
155 dol_syslog("functions_openid_connect::check_user_password_openid_connect::".$_SESSION["dol_loginmesg"], LOG_ERR);
156 return false;
157 }
158
159 // Success: retrieve claim to return to Dolibarr as login
160 $sql = 'SELECT login, entity, datestartvalidity, dateendvalidity';
161 $sql .= ' FROM '.MAIN_DB_PREFIX.'user';
162 $sql .= " WHERE login = '".$db->escape($userinfo_content->$login_claim)."'";
163 $sql .= ' AND entity IN (0,'.(array_key_exists('dol_entity', $_SESSION) ? ((int) $_SESSION["dol_entity"]) : 1).')';
164
165 dol_syslog("functions_openid::check_user_password_openid", LOG_DEBUG);
166
167 $resql = $db->query($sql);
168 if (!$resql) {
169 dol_syslog("functions_openid_connect::check_user_password_openid_connect::Error with sql query (".$db->error().")");
170 return false;
171 }
172 $obj = $db->fetch_object($resql);
173 if (!$obj) {
174 dol_syslog("functions_openid_connect::check_user_password_openid_connect::Error no result from the query");
175 return false;
176 }
177
178 $_SESSION['OPENID_CONNECT'] = true;
179
180 // Note: Test on date validity is done later natively with isNotIntoValidityDateRange() by core after calling checkLoginPassEntity() that call this method
181 dol_syslog("functions_openid_connect::check_user_password_openid_connect END");
182 return $obj->login;
183}
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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).