MediaWiki  1.28.0
LocalPasswordPrimaryAuthenticationProvider.php
Go to the documentation of this file.
1 <?php
22 namespace MediaWiki\Auth;
23 
24 use User;
25 
33 {
34 
36  protected $loginOnly = false;
37 
44  public function __construct( $params = [] ) {
45  parent::__construct( $params );
46  $this->loginOnly = !empty( $params['loginOnly'] );
47  }
48 
49  protected function getPasswordResetData( $username, $row ) {
50  $now = wfTimestamp();
51  $expiration = wfTimestampOrNull( TS_UNIX, $row->user_password_expires );
52  if ( $expiration === null || $expiration >= $now ) {
53  return null;
54  }
55 
56  $grace = $this->config->get( 'PasswordExpireGrace' );
57  if ( $expiration + $grace < $now ) {
58  $data = [
59  'hard' => true,
60  'msg' => \Status::newFatal( 'resetpass-expired' )->getMessage(),
61  ];
62  } else {
63  $data = [
64  'hard' => false,
65  'msg' => \Status::newFatal( 'resetpass-expired-soft' )->getMessage(),
66  ];
67  }
68 
69  return (object)$data;
70  }
71 
72  public function beginPrimaryAuthentication( array $reqs ) {
74  if ( !$req ) {
76  }
77 
78  if ( $req->username === null || $req->password === null ) {
80  }
81 
82  $username = User::getCanonicalName( $req->username, 'usable' );
83  if ( $username === false ) {
85  }
86 
87  $fields = [
88  'user_id', 'user_password', 'user_password_expires',
89  ];
90 
91  $dbr = wfGetDB( DB_REPLICA );
92  $row = $dbr->selectRow(
93  'user',
94  $fields,
95  [ 'user_name' => $username ],
96  __METHOD__
97  );
98  if ( !$row ) {
100  }
101 
102  $oldRow = clone $row;
103  // Check for *really* old password hashes that don't even have a type
104  // The old hash format was just an md5 hex hash, with no type information
105  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
106  if ( $this->config->get( 'PasswordSalt' ) ) {
107  $row->user_password = ":A:{$row->user_id}:{$row->user_password}";
108  } else {
109  $row->user_password = ":A:{$row->user_password}";
110  }
111  }
112 
113  $status = $this->checkPasswordValidity( $username, $req->password );
114  if ( !$status->isOK() ) {
115  // Fatal, can't log in
116  return AuthenticationResponse::newFail( $status->getMessage() );
117  }
118 
119  $pwhash = $this->getPassword( $row->user_password );
120  if ( !$pwhash->equals( $req->password ) ) {
121  if ( $this->config->get( 'LegacyEncoding' ) ) {
122  // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
123  // Check for this with iconv
124  $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
125  if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
126  return $this->failResponse( $req );
127  }
128  } else {
129  return $this->failResponse( $req );
130  }
131  }
132 
133  // @codeCoverageIgnoreStart
134  if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
135  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
136  \DeferredUpdates::addCallableUpdate( function () use ( $pwhash, $oldRow ) {
137  $dbw = wfGetDB( DB_MASTER );
138  $dbw->update(
139  'user',
140  [ 'user_password' => $pwhash->toString() ],
141  [
142  'user_id' => $oldRow->user_id,
143  'user_password' => $oldRow->user_password
144  ],
145  __METHOD__
146  );
147  } );
148  }
149  // @codeCoverageIgnoreEnd
150 
151  $this->setPasswordResetFlag( $username, $status, $row );
152 
154  }
155 
156  public function testUserCanAuthenticate( $username ) {
158  if ( $username === false ) {
159  return false;
160  }
161 
162  $dbr = wfGetDB( DB_REPLICA );
163  $row = $dbr->selectRow(
164  'user',
165  [ 'user_password' ],
166  [ 'user_name' => $username ],
167  __METHOD__
168  );
169  if ( !$row ) {
170  return false;
171  }
172 
173  // Check for *really* old password hashes that don't even have a type
174  // The old hash format was just an md5 hex hash, with no type information
175  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
176  return true;
177  }
178 
179  return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
180  }
181 
182  public function testUserExists( $username, $flags = User::READ_NORMAL ) {
184  if ( $username === false ) {
185  return false;
186  }
187 
189  return (bool)wfGetDB( $db )->selectField(
190  [ 'user' ],
191  [ 'user_id' ],
192  [ 'user_name' => $username ],
193  __METHOD__,
194  $options
195  );
196  }
197 
199  AuthenticationRequest $req, $checkData = true
200  ) {
201  // We only want to blank the password if something else will accept the
202  // new authentication data, so return 'ignore' here.
203  if ( $this->loginOnly ) {
204  return \StatusValue::newGood( 'ignored' );
205  }
206 
207  if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
208  if ( !$checkData ) {
209  return \StatusValue::newGood();
210  }
211 
212  $username = User::getCanonicalName( $req->username, 'usable' );
213  if ( $username !== false ) {
214  $row = wfGetDB( DB_MASTER )->selectRow(
215  'user',
216  [ 'user_id' ],
217  [ 'user_name' => $username ],
218  __METHOD__
219  );
220  if ( $row ) {
221  $sv = \StatusValue::newGood();
222  if ( $req->password !== null ) {
223  if ( $req->password !== $req->retype ) {
224  $sv->fatal( 'badretype' );
225  } else {
226  $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
227  }
228  }
229  return $sv;
230  }
231  }
232  }
233 
234  return \StatusValue::newGood( 'ignored' );
235  }
236 
238  $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
239  if ( $username === false ) {
240  return;
241  }
242 
243  $pwhash = null;
244 
245  if ( $this->loginOnly ) {
246  $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
247  $expiry = null;
248  // @codeCoverageIgnoreStart
249  } elseif ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
250  // @codeCoverageIgnoreEnd
251  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
252  $expiry = $this->getNewPasswordExpiry( $username );
253  }
254 
255  if ( $pwhash ) {
256  $dbw = wfGetDB( DB_MASTER );
257  $dbw->update(
258  'user',
259  [
260  'user_password' => $pwhash->toString(),
261  'user_password_expires' => $dbw->timestampOrNull( $expiry ),
262  ],
263  [ 'user_name' => $username ],
264  __METHOD__
265  );
266  }
267  }
268 
269  public function accountCreationType() {
270  return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
271  }
272 
273  public function testForAccountCreation( $user, $creator, array $reqs ) {
275 
277  if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
278  if ( $req->password !== $req->retype ) {
279  $ret->fatal( 'badretype' );
280  } else {
281  $ret->merge(
282  $this->checkPasswordValidity( $user->getName(), $req->password )
283  );
284  }
285  }
286  return $ret;
287  }
288 
289  public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
290  if ( $this->accountCreationType() === self::TYPE_NONE ) {
291  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
292  }
293 
295  if ( $req ) {
296  if ( $req->username !== null && $req->password !== null ) {
297  // Nothing we can do besides claim it, because the user isn't in
298  // the DB yet
299  if ( $req->username !== $user->getName() ) {
300  $req = clone( $req );
301  $req->username = $user->getName();
302  }
304  $ret->createRequest = $req;
305  return $ret;
306  }
307  }
309  }
310 
311  public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
312  if ( $this->accountCreationType() === self::TYPE_NONE ) {
313  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
314  }
315 
316  // Now that the user is in the DB, set the password on it.
317  $this->providerChangeAuthenticationData( $res->createRequest );
318 
319  return null;
320  }
321 }
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1936
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getCanonicalName($name, $validate= 'valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid...
Definition: User.php:1046
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
setPasswordResetFlag($username, Status $status, $data=null)
Check if the password should be reset.
A primary authentication provider that uses the password field in the 'user' table.
testForAccountCreation($user, $creator, array $reqs)
Determine whether an account creation may begin.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
This is a value object to hold authentication response data.
const DB_MASTER
Definition: defines.php:23
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: defines.php:6
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
testUserCanAuthenticate($username)
Test whether the named user can authenticate with this provider.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1046
$res
Definition: database.txt:21
$params
Basic framework for a primary authentication provider that uses passwords.
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
static getDBOptions($bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
finishAccountCreation($user, $creator, AuthenticationResponse $res)
Post-creation callback.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:1007
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:802
providerChangeAuthenticationData(AuthenticationRequest $req)
Change or remove authentication data (e.g.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static getRequestByClass(array $reqs, $class, $allowSubclasses=false)
Select a request by class name.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
beginPrimaryAccountCreation($user, $creator, array $reqs)
Start an account creation flow.
static addCallableUpdate($callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
getNewPasswordExpiry($username)
Get expiration date for a new password, if any.
const DB_REPLICA
Definition: defines.php:22
failResponse(PasswordAuthenticationRequest $req)
Return the appropriate response for failure.
wfTimestampOrNull($outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
testUserExists($username, $flags=User::READ_NORMAL)
Test whether the named user exists.
This is a value object for authentication requests.