[TASK] Add LoginType enumeration
[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'] !== LoginType::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 ###IP### (%s) for username \'%s\' with an empty password!', [
58 $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 ###IP### (%s), username \'%s\' not found!!', [$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 $this->logger->debug('User found', [
74 $this->db_user['userid_column'] => $user[$this->db_user['userid_column']],
75 $this->db_user['username_column'] => $user[$this->db_user['username_column']]
76 ]);
77 }
78 return $user;
79 }
80
81 /**
82 * Authenticate a user (Check various conditions for the user that might invalidate its authentication, eg. password match, domain, IP, etc.)
83 *
84 * @param array $user Data of user.
85 * @return int >= 200: User authenticated successfully.
86 * No more checking is needed by other auth services.
87 * >= 100: User not authenticated; this service is not responsible.
88 * Other auth services will be asked.
89 * > 0: User authenticated successfully.
90 * Other auth services will still be asked.
91 * <= 0: Authentication failed, no more checking needed
92 * by other auth services.
93 */
94 public function authUser(array $user)
95 {
96 $OK = 100;
97 // This authentication service can only work correctly, if a non empty username along with a non empty password is provided.
98 // Otherwise a different service is allowed to check for other login credentials
99 if ((string)$this->login['uident_text'] !== '' && (string)$this->login['uname'] !== '') {
100 // Checking password match for user:
101 $OK = $this->compareUident($user, $this->login);
102 if (!$OK) {
103 // Failed login attempt (wrong password) - write that to the log!
104 if ($this->writeAttemptLog) {
105 $this->writelog(255, 3, 3, 1, 'Login-attempt from ###IP### (%s), username \'%s\', password not accepted!', [$this->authInfo['REMOTE_HOST'], $this->login['uname']]);
106 $this->logger->info('Login-attempt username \'' . $this->login['uname'] . '\', password not accepted!', [
107 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
108 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
109 ]);
110 }
111 $this->logger->debug('Password not accepted: ' . $this->login['uident']);
112 }
113 // Checking the domain (lockToDomain)
114 if ($OK && $user['lockToDomain'] && $user['lockToDomain'] !== $this->authInfo['HTTP_HOST']) {
115 // Lock domain didn't match, so error:
116 if ($this->writeAttemptLog) {
117 $this->writelog(255, 3, 3, 1, 'Login-attempt from ###IP### (%s), username \'%s\', locked domain \'%s\' did not match \'%s\'!', [$this->authInfo['REMOTE_HOST'], $user[$this->db_user['username_column']], $user['lockToDomain'], $this->authInfo['HTTP_HOST']]);
118 $this->logger->info('Login-attempt from username \'' . $user[$this->db_user['username_column']] . '\', locked domain did not match!', [
119 'HTTP_HOST' => $this->authInfo['HTTP_HOST'],
120 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
121 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
122 'lockToDomain' => $user['lockToDomain'],
123 ]);
124 }
125 $OK = 0;
126 }
127 }
128 return $OK;
129 }
130
131 /**
132 * Find usergroup records, currently only for frontend
133 *
134 * @param array $user Data of user.
135 * @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.
136 * @return mixed Groups array, keys = uid which must be unique
137 */
138 public function getGroups($user, $knownGroups)
139 {
140 /*
141 * Attention: $knownGroups is not used within this method, but other services can use it.
142 * This parameter should not be removed!
143 * The FrontendUserAuthentication call getGroups and handover the previous detected groups.
144 */
145 $groupDataArr = [];
146 if ($this->mode === 'getGroupsFE') {
147 $groups = [];
148 if ($user[$this->db_user['usergroup_column']] ?? false) {
149 $groupList = $user[$this->db_user['usergroup_column']];
150 $groups = [];
151 $this->getSubGroups($groupList, '', $groups);
152 }
153 // ADD group-numbers if the IPmask matches.
154 foreach ($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'] ?? [] as $IPel) {
155 if ($this->authInfo['REMOTE_ADDR'] && $IPel[0] && GeneralUtility::cmpIP($this->authInfo['REMOTE_ADDR'], $IPel[0])) {
156 $groups[] = (int)$IPel[1];
157 }
158 }
159 $groups = array_unique($groups);
160 if (!empty($groups)) {
161 $this->logger->debug('Get usergroups with id: ' . implode(',', $groups));
162 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
163 ->getQueryBuilderForTable($this->db_groups['table']);
164 if (!empty($this->authInfo['showHiddenRecords'])) {
165 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
166 }
167
168 $res = $queryBuilder->select('*')
169 ->from($this->db_groups['table'])
170 ->where(
171 $queryBuilder->expr()->in(
172 'uid',
173 $queryBuilder->createNamedParameter($groups, Connection::PARAM_INT_ARRAY)
174 ),
175 $queryBuilder->expr()->orX(
176 $queryBuilder->expr()->eq(
177 'lockToDomain',
178 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
179 ),
180 $queryBuilder->expr()->isNull('lockToDomain'),
181 $queryBuilder->expr()->eq(
182 'lockToDomain',
183 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
184 )
185 )
186 )
187 ->execute();
188
189 while ($row = $res->fetch()) {
190 $groupDataArr[$row['uid']] = $row;
191 }
192 } else {
193 $this->logger->debug('No usergroups found.');
194 }
195 }
196 return $groupDataArr;
197 }
198
199 /**
200 * Fetches subgroups of groups. Function is called recursively for each subgroup.
201 * Function was previously copied from
202 * \TYPO3\CMS\Core\Authentication\BackendUserAuthentication->fetchGroups and has been slightly modified.
203 *
204 * @param string $grList Commalist of fe_groups uid numbers
205 * @param string $idList List of already processed fe_groups-uids so the function will not fall into an eternal recursion.
206 * @param array $groups
207 * @return array
208 * @access private
209 */
210 public function getSubGroups($grList, $idList = '', &$groups)
211 {
212 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
213 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_groups');
214 if (!empty($this->authInfo['showHiddenRecords'])) {
215 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
216 }
217
218 $res = $queryBuilder
219 ->select('uid', 'subgroup')
220 ->from($this->db_groups['table'])
221 ->where(
222 $queryBuilder->expr()->in(
223 'uid',
224 $queryBuilder->createNamedParameter(
225 GeneralUtility::intExplode(',', $grList, true),
226 Connection::PARAM_INT_ARRAY
227 )
228 ),
229 $queryBuilder->expr()->orX(
230 $queryBuilder->expr()->eq(
231 'lockToDomain',
232 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
233 ),
234 $queryBuilder->expr()->isNull('lockToDomain'),
235 $queryBuilder->expr()->eq(
236 'lockToDomain',
237 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
238 )
239 )
240 )
241 ->execute();
242
243 // Internal group record storage
244 $groupRows = [];
245 // The groups array is filled
246 while ($row = $res->fetch()) {
247 if (!in_array($row['uid'], $groups)) {
248 $groups[] = $row['uid'];
249 }
250 $groupRows[$row['uid']] = $row;
251 }
252 // Traversing records in the correct order
253 $include_staticArr = GeneralUtility::intExplode(',', $grList);
254 // traversing list
255 foreach ($include_staticArr as $uid) {
256 // Get row:
257 $row = $groupRows[$uid];
258 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
259 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
260 // Include sub groups
261 if (trim($row['subgroup'])) {
262 // Make integer list
263 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
264 // Call recursively, pass along list of already processed groups so they are not processed again.
265 $this->getSubGroups($theList, $idList . ',' . $uid, $groups);
266 }
267 }
268 }
269 }
270 }