1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
auth.php
См. документацию.
1<?php
8
9namespace Bitrix\Rest\APAuth;
10
11use Bitrix\Main\Authentication\ApplicationManager;
12use Bitrix\Main\Authentication\ApplicationPasswordTable;
13use Bitrix\Main\Context;
14use Bitrix\Main\Localization\Loc;
15use Bitrix\Main\Type\DateTime;
16use Bitrix\Main\UserTable;
17use Bitrix\Rest\Engine\Access;
18use Bitrix\Rest\Engine\Access\HoldEntity;
19use Bitrix\Rest\Preset\IntegrationTable;
20
21class Auth
22{
23 const AUTH_TYPE = 'apauth';
24
25 protected static $authQueryParams = array(
26 'UID' => 'aplogin', 'PASSWORD' => 'ap',
27 );
28
29 protected static $integrationScope = array('crm', 'telephony', 'imopenlines');
30
31 protected static $scopeCache = array();
32
33 private const TEMPORARY_FORBIDDEN_INTEGRATION = ['export-email-new-contact', 'contact-add'];
34
35 public static function onRestCheckAuth(array $query, $scope, &$res)
36 {
37 $auth = array();
38 foreach(static::$authQueryParams as $key)
39 {
40 if (array_key_exists($key, $query))
41 {
43 }
44 else
45 {
46 return null;
47 }
48 }
49
50 if (!defined('REST_APAUTH_ALLOW_HTTP') && !Context::getCurrent()->getRequest()->isHttps())
51 {
52 $res = array('error' => 'INVALID_REQUEST', 'error_description' => 'Https required.');
53 return false;
54 }
55
56 $tokenInfo = static::check($auth, $scope);
57
58 if (is_array($tokenInfo))
59 {
60 $error = array_key_exists('error', $tokenInfo);
61
62 if (!$error && HoldEntity::is(HoldEntity::TYPE_WEBHOOK, $auth[static::$authQueryParams['PASSWORD']]))
63 {
64 $tokenInfo = [
65 'error' => 'OVERLOAD_LIMIT',
66 'error_description' => 'REST API is blocked due to overload.'
67 ];
68 $error = true;
69 }
70
71 if (
72 !$error
73 && (
74 !Access::isAvailableAPAuthByPasswordId((int)$tokenInfo['password_id'])
75 || (
76 Access::needCheckCount()
77 && !Access::isAvailableCount(Access::ENTITY_TYPE_WEBHOOK, $tokenInfo['password_id'])
78 )
79 )
80 )
81 {
82 $tokenInfo = [
83 'error' => 'ACCESS_DENIED',
84 'error_description' => 'REST is available only by subscription.'
85 ];
86 $error = true;
87 }
88
89 if (!$error && $tokenInfo['user_id'] > 0)
90 {
91 $tokenInfo['scope'] = implode(',', static::getPasswordScope($tokenInfo['password_id']));
92
93 global $USER;
94 if ($USER instanceof \CUser && $USER->isAuthorized())
95 {
96 if ((int)$USER->GetID() !== (int)$tokenInfo['user_id'])
97 {
98 $tokenInfo = [
99 'error' => 'authorization_error',
100 'error_description' => Loc::getMessage('REST_AP_AUTH_ERROR_LOGOUT_BEFORE'),
101 ];
102 $error = true;
103 }
104 }
105 elseif (!\CRestUtil::makeAuth($tokenInfo))
106 {
107 $tokenInfo = array('error' => 'authorization_error', 'error_description' => 'Unable to authorize user');
108 $error = true;
109 }
110 else
111 {
112 PasswordTable::update($tokenInfo['password_id'], array(
113 'DATE_LOGIN' => new DateTime(),
114 'LAST_IP' => Context::getCurrent()->getRequest()->getRemoteAddress(),
115 ));
116
117 unset($tokenInfo['application_id']);
118 }
119 }
120
121 $res = $tokenInfo;
122
123 $res['parameters_clear'] = static::$authQueryParams;
124 $res['auth_type'] = static::AUTH_TYPE;
125
126 return !$error;
127 }
128
129 return false;
130 }
131
132 protected static function check($auth, $scope)
133 {
134 $result = array('error' => 'INVALID_CREDENTIALS', 'error_description' => 'Invalid request credentials');
135
136 $uid = $auth[static::$authQueryParams['UID']];
137
138 if(strval(intval($uid)) === $uid)
139 {
140 $userInfo = array('ID' => intval($uid));
141 }
142 else
143 {
144 $dbRes = UserTable::getList(array(
145 'filter' => array(
146 '=LOGIN' => $uid,
147 '=ACTIVE' => 'Y',
148 ),
149 'select' => array('ID'),
150 ));
151 $userInfo = $dbRes->fetch();
152 }
153
154 if($userInfo)
155 {
157 'filter' => array(
158 '=USER_ID' => $userInfo['ID'],
159 '=PASSWORD' => $auth[static::$authQueryParams['PASSWORD']],
160 '=ACTIVE' => PasswordTable::ACTIVE,
161 ),
162 'select' => array('ID')
163 ));
164 $passwordInfo = $dbRes->fetch();
165
166 if(!$passwordInfo)
167 {
168 $passwordInfo = static::checkOldPassword($userInfo['ID'], $auth[static::$authQueryParams['PASSWORD']]);
169 }
170
171 if($passwordInfo)
172 {
173 if (static::checkPermission($passwordInfo["ID"], $scope) === true)
174 {
175 $forbiddenIntegration = IntegrationTable::query()
176 ->setSelect(['ID'])
177 ->where('PASSWORD_ID', $passwordInfo["ID"])
178 ->whereIn('ELEMENT_CODE', static::TEMPORARY_FORBIDDEN_INTEGRATION)
179 ->setCacheTtl(86400)
180 ->exec()
181 ->fetch()
182 ;
183
184 if (!empty($forbiddenIntegration))
185 {
186 $result = array(
187 'error' => 'QUERY_LIMIT_EXCEEDED',
188 'error_description' => 'Rate limit exceeded. Too many requests in a given amount of time.'
189 );
190 }
191 else
192 {
193 $result = array(
194 'user_id' => $userInfo["ID"],
195 'password_id' => $passwordInfo["ID"],
196 );
197 }
198 }
199 else
200 {
201 $result = array('error' => 'insufficient_scope', 'error_description' => 'The request requires higher privileges than provided by the webhook token');
202 }
203 }
204 }
205
206 return $result;
207 }
208
209 protected static function checkOldPassword($userId, $password)
210 {
211 $appPassword = ApplicationPasswordTable::findPassword($userId, $password);
212 if($appPassword !== false)
213 {
214 if($appPassword["APPLICATION_ID"] === Application::ID)
215 {
216 $appManager = ApplicationManager::getInstance();
217 if($appManager->checkScope($appPassword["APPLICATION_ID"]) === true)
218 {
219 return static::convertOldPassword($appPassword, $password);
220 }
221 }
222 }
223
224 return false;
225 }
226
227 protected static function convertOldPassword($appPassword, $password)
228 {
229 $dbRes = ApplicationPasswordTable::getById($appPassword['ID']);
230 $oldPassword = $dbRes->fetch();
231 if($oldPassword)
232 {
233 ApplicationPasswordTable::delete($appPassword['ID']);
235 'USER_ID' => $oldPassword['USER_ID'],
236 'PASSWORD' => $password,
237 'ACTIVE' => PasswordTable::ACTIVE,
238 'TITLE' => $oldPassword['SYSCOMMENT'],
239 'COMMENT' => $oldPassword['COMMENT'],
240 'DATE_CREATE' => $oldPassword['DATE_CREATE'],
241 'DATE_LOGIN' => $oldPassword['DATE_LOGIN'],
242 'LAST_IP' => $oldPassword['LAST_IP'],
243 ));
244 if($result->isSuccess())
245 {
246 $passwordId = $result->getId();
247
248 foreach(static::$integrationScope as $scope)
249 {
251 'PASSWORD_ID' => $passwordId,
252 'PERM' => $scope,
253 ));
254 }
255
256 return array(
257 'ID' => $passwordId,
258 );
259 }
260 }
261
262 return false;
263 }
264
265 protected static function checkPermission($passwordId, $scope)
266 {
267 if($scope === \CRestUtil::GLOBAL_SCOPE)
268 {
269 return true;
270 }
271
272 $scopeList = static::getPasswordScope($passwordId);
273 $scopeList = \Bitrix\Rest\Engine\RestManager::fillAlternativeScope($scope, $scopeList);
274 return in_array($scope, $scopeList);
275 }
276
277 protected static function getPasswordScope($passwordId): array
278 {
279 if (!array_key_exists($passwordId, static::$scopeCache))
280 {
281 static::$scopeCache[$passwordId] = [];
282
284 ->setSelect(['PERM'])
285 ->where('PASSWORD_ID', $passwordId)
286 ->setCacheTtl(86400)
287 ->exec();
288 while ($perm = $dbRes->fetch())
289 {
290 static::$scopeCache[$passwordId][] = $perm['PERM'];
291 }
292 }
293
294 return static::$scopeCache[$passwordId];
295 }
296}
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static getList(array $parameters=array())
Определения datamanager.php:431
static add(array $data)
Определения datamanager.php:877
static update($primary, array $data)
Определения datamanager.php:1256
Определения auth.php:22
static $scopeCache
Определения auth.php:31
static checkOldPassword($userId, $password)
Определения auth.php:209
static check($auth, $scope)
Определения auth.php:132
static $authQueryParams
Определения auth.php:25
static getPasswordScope($passwordId)
Определения auth.php:277
const AUTH_TYPE
Определения auth.php:23
static $integrationScope
Определения auth.php:29
static convertOldPassword($appPassword, $password)
Определения auth.php:227
static checkPermission($passwordId, $scope)
Определения auth.php:265
static onRestCheckAuth(array $query, $scope, &$res)
Определения auth.php:35
static fillAlternativeScope($scope, $scopeList)
Определения restmanager.php:90
Определения user.php:6037
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$perm
Определения options.php:169
$result
Определения get_property_values.php:14
$query
Определения get_search.php:11
$auth
Определения get_user.php:29
$uid
Определения hot_keys_act.php:8
global $USER
Определения csv_new_run.php:40
$password
Определения mysql_to_pgsql.php:34
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
$error
Определения subscription_card_product.php:20
$dbRes
Определения yandex_detail.php:168