[!!!][TASK] Deprecate GeneralUtility::devLog()
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Authentication / AuthenticationService.php
1 <?php
2 namespace TYPO3\CMS\Core\Authentication;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Database\Connection;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21
22 /**
23 * Authentication services class
24 */
25 class AuthenticationService extends AbstractAuthenticationService
26 {
27 /**
28 * Process the submitted credentials.
29 * In this case hash the clear text password if it has been submitted.
30 *
31 * @param array $loginData Credentials that are submitted and potentially modified by other services
32 * @param string $passwordTransmissionStrategy Keyword of how the password has been hashed or encrypted before submission
33 * @return bool
34 */
35 public function processLoginData(array &$loginData, $passwordTransmissionStrategy)
36 {
37 $isProcessed = false;
38 if ($passwordTransmissionStrategy === 'normal') {
39 $loginData['uident_text'] = $loginData['uident'];
40 $isProcessed = true;
41 }
42 return $isProcessed;
43 }
44
45 /**
46 * Find a user (eg. look up the user record in database when a login is sent)
47 *
48 * @return mixed User array or FALSE
49 */
50 public function getUser()
51 {
52 if ($this->login['status'] !== 'login') {
53 return false;
54 }
55 if ((string)$this->login['uident_text'] === '') {
56 // Failed Login attempt (no password given)
57 $this->writelog(255, 3, 3, 2, 'Login-attempt from %s (%s) for username \'%s\' with an empty password!', [
58 $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']
59 ]);
60 $this->logger->warning(sprintf('Login-attempt from %s (%s), for username \'%s\' with an empty password!', $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']));
61 return false;
62 }
63
64 $user = $this->fetchUserRecord($this->login['uname']);
65 if (!is_array($user)) {
66 // Failed login attempt (no username found)
67 $this->writelog(255, 3, 3, 2, 'Login-attempt from %s (%s), username \'%s\' not found!!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']]);
68 $this->logger->info('Login-attempt from username \'' . $this->login['uname'] . '\' not found!', [
69 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
70 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
71 ]);
72 } else {
73 if ($this->writeDevLog) {
74 $this->logger->debug('User found', [
75 $this->db_user['userid_column'] => $user[$this->db_user['userid_column']],
76 $this->db_user['username_column'] => $user[$this->db_user['username_column']]
77 ]);
78 }
79 }
80 return $user;
81 }
82
83 /**
84 * Authenticate a user (Check various conditions for the user that might invalidate its authentication, eg. password match, domain, IP, etc.)
85 *
86 * @param array $user Data of user.
87 * @return int >= 200: User authenticated successfully.
88 * No more checking is needed by other auth services.
89 * >= 100: User not authenticated; this service is not responsible.
90 * Other auth services will be asked.
91 * > 0: User authenticated successfully.
92 * Other auth services will still be asked.
93 * <= 0: Authentication failed, no more checking needed
94 * by other auth services.
95 */
96 public function authUser(array $user)
97 {
98 $OK = 100;
99 // This authentication service can only work correctly, if a non empty username along with a non empty password is provided.
100 // Otherwise a different service is allowed to check for other login credentials
101 if ((string)$this->login['uident_text'] !== '' && (string)$this->login['uname'] !== '') {
102 // Checking password match for user:
103 $OK = $this->compareUident($user, $this->login);
104 if (!$OK) {
105 // Failed login attempt (wrong password) - write that to the log!
106 if ($this->writeAttemptLog) {
107 $this->writelog(255, 3, 3, 1, 'Login-attempt from %s (%s), username \'%s\', password not accepted!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']]);
108 $this->logger->info('Login-attempt username \'' . $this->login['uname'] . '\', password not accepted!', [
109 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
110 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
111 ]);
112 }
113 if ($this->writeDevLog) {
114 $this->logger->debug('Password not accepted: ' . $this->login['uident']);
115 }
116 }
117 // Checking the domain (lockToDomain)
118 if ($OK && $user['lockToDomain'] && $user['lockToDomain'] !== $this->authInfo['HTTP_HOST']) {
119 // Lock domain didn't match, so error:
120 if ($this->writeAttemptLog) {
121 $this->writelog(255, 3, 3, 1, 'Login-attempt from %s (%s), username \'%s\', locked domain \'%s\' did not match \'%s\'!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $user[$this->db_user['username_column']], $user['lockToDomain'], $this->authInfo['HTTP_HOST']]);
122 $this->logger->info('Login-attempt from username \'' . $user[$this->db_user['username_column']] . '\', locked domain did not match!', [
123 'HTTP_HOST' => $this->authInfo['HTTP_HOST'],
124 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
125 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
126 'lockToDomain' => $user['lockToDomain'],
127 ]);
128 }
129 $OK = 0;
130 }
131 }
132 return $OK;
133 }
134
135 /**
136 * Find usergroup records, currently only for frontend
137 *
138 * @param array $user Data of user.
139 * @param array $knownGroups Group data array of already known groups. This is handy if you want select other related groups. Keys in this array are unique IDs of those groups.
140 * @return mixed Groups array, keys = uid which must be unique
141 */
142 public function getGroups($user, $knownGroups)
143 {
144 /*
145 * Attention: $knownGroups is not used within this method, but other services can use it.
146 * This parameter should not be removed!
147 * The FrontendUserAuthentication call getGroups and handover the previous detected groups.
148 */
149 $groupDataArr = [];
150 if ($this->mode === 'getGroupsFE') {
151 $groups = [];
152 if (is_array($user) && $user[$this->db_user['usergroup_column']]) {
153 $groupList = $user[$this->db_user['usergroup_column']];
154 $groups = [];
155 $this->getSubGroups($groupList, '', $groups);
156 }
157 // ADD group-numbers if the IPmask matches.
158 if (is_array($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'])) {
159 foreach ($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'] as $IPel) {
160 if ($this->authInfo['REMOTE_ADDR'] && $IPel[0] && GeneralUtility::cmpIP($this->authInfo['REMOTE_ADDR'], $IPel[0])) {
161 $groups[] = (int)$IPel[1];
162 }
163 }
164 }
165 $groups = array_unique($groups);
166 if (!empty($groups)) {
167 if ($this->writeDevLog) {
168 $this->logger->debug('Get usergroups with id: ' . implode(',', $groups));
169 }
170 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
171 ->getQueryBuilderForTable($this->db_groups['table']);
172 if (!empty($this->authInfo['showHiddenRecords'])) {
173 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
174 }
175
176 $res = $queryBuilder->select('*')
177 ->from($this->db_groups['table'])
178 ->where(
179 $queryBuilder->expr()->in(
180 'uid',
181 $queryBuilder->createNamedParameter($groups, Connection::PARAM_INT_ARRAY)
182 ),
183 $queryBuilder->expr()->orX(
184 $queryBuilder->expr()->eq(
185 'lockToDomain',
186 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
187 ),
188 $queryBuilder->expr()->isNull('lockToDomain'),
189 $queryBuilder->expr()->eq(
190 'lockToDomain',
191 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
192 )
193 )
194 )
195 ->execute();
196
197 while ($row = $res->fetch()) {
198 $groupDataArr[$row['uid']] = $row;
199 }
200 } else {
201 if ($this->writeDevLog) {
202 $this->logger->debug('No usergroups found.');
203 }
204 }
205 }
206 return $groupDataArr;
207 }
208
209 /**
210 * Fetches subgroups of groups. Function is called recursively for each subgroup.
211 * Function was previously copied from
212 * \TYPO3\CMS\Core\Authentication\BackendUserAuthentication->fetchGroups and has been slightly modified.
213 *
214 * @param string $grList Commalist of fe_groups uid numbers
215 * @param string $idList List of already processed fe_groups-uids so the function will not fall into an eternal recursion.
216 * @param array $groups
217 * @return array
218 * @access private
219 */
220 public function getSubGroups($grList, $idList = '', &$groups)
221 {
222 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
223 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_groups');
224 if (!empty($this->authInfo['showHiddenRecords'])) {
225 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
226 }
227
228 $res = $queryBuilder
229 ->select('uid', 'subgroup')
230 ->from($this->db_groups['table'])
231 ->where(
232 $queryBuilder->expr()->in(
233 'uid',
234 $queryBuilder->createNamedParameter(
235 GeneralUtility::intExplode(',', $grList, true),
236 Connection::PARAM_INT_ARRAY
237 )
238 ),
239 $queryBuilder->expr()->orX(
240 $queryBuilder->expr()->eq(
241 'lockToDomain',
242 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
243 ),
244 $queryBuilder->expr()->isNull('lockToDomain'),
245 $queryBuilder->expr()->eq(
246 'lockToDomain',
247 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
248 )
249 )
250 )
251 ->execute();
252
253 // Internal group record storage
254 $groupRows = [];
255 // The groups array is filled
256 while ($row = $res->fetch()) {
257 if (!in_array($row['uid'], $groups)) {
258 $groups[] = $row['uid'];
259 }
260 $groupRows[$row['uid']] = $row;
261 }
262 // Traversing records in the correct order
263 $include_staticArr = GeneralUtility::intExplode(',', $grList);
264 // traversing list
265 foreach ($include_staticArr as $uid) {
266 // Get row:
267 $row = $groupRows[$uid];
268 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
269 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
270 // Include sub groups
271 if (trim($row['subgroup'])) {
272 // Make integer list
273 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
274 // Call recursively, pass along list of already processed groups so they are not processed again.
275 $this->getSubGroups($theList, $idList . ',' . $uid, $groups);
276 }
277 }
278 }
279 }
280 }