MediaWiki  1.27.4
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  $dbw = wfGetDB( DB_MASTER );
92  $row = $dbw->selectRow(
93  'user',
94  $fields,
95  [ 'user_name' => $username ],
96  __METHOD__
97  );
98  if ( !$row ) {
99  // Do not reveal whether its bad username or
100  // bad password to prevent username enumeration
101  // on private wikis. (T134100)
102  return $this->failResponse( $req );
103  }
104 
105  // Check for *really* old password hashes that don't even have a type
106  // The old hash format was just an md5 hex hash, with no type information
107  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
108  if ( $this->config->get( 'PasswordSalt' ) ) {
109  $row->user_password = ":A:{$row->user_id}:{$row->user_password}";
110  } else {
111  $row->user_password = ":A:{$row->user_password}";
112  }
113  }
114 
115  $status = $this->checkPasswordValidity( $username, $req->password );
116  if ( !$status->isOk() ) {
117  // Fatal, can't log in
118  return AuthenticationResponse::newFail( $status->getMessage() );
119  }
120 
121  $pwhash = $this->getPassword( $row->user_password );
122  if ( !$pwhash->equals( $req->password ) ) {
123  if ( $this->config->get( 'LegacyEncoding' ) ) {
124  // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
125  // Check for this with iconv
126  $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $req->password );
127  if ( $cp1252Password === $req->password || !$pwhash->equals( $cp1252Password ) ) {
128  return $this->failResponse( $req );
129  }
130  } else {
131  return $this->failResponse( $req );
132  }
133  }
134 
135  // @codeCoverageIgnoreStart
136  if ( $this->getPasswordFactory()->needsUpdate( $pwhash ) ) {
137  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
138  $dbw->update(
139  'user',
140  [ 'user_password' => $pwhash->toString() ],
141  [ 'user_id' => $row->user_id ],
142  __METHOD__
143  );
144  }
145  // @codeCoverageIgnoreEnd
146 
147  $this->setPasswordResetFlag( $username, $status, $row );
148 
150  }
151 
152  public function testUserCanAuthenticate( $username ) {
154  if ( $username === false ) {
155  return false;
156  }
157 
158  $dbw = wfGetDB( DB_MASTER );
159  $row = $dbw->selectRow(
160  'user',
161  [ 'user_password' ],
162  [ 'user_name' => $username ],
163  __METHOD__
164  );
165  if ( !$row ) {
166  return false;
167  }
168 
169  // Check for *really* old password hashes that don't even have a type
170  // The old hash format was just an md5 hex hash, with no type information
171  if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
172  return true;
173  }
174 
175  return !$this->getPassword( $row->user_password ) instanceof \InvalidPassword;
176  }
177 
180  if ( $username === false ) {
181  return false;
182  }
183 
185  return (bool)wfGetDB( $db )->selectField(
186  [ 'user' ],
187  [ 'user_id' ],
188  [ 'user_name' => $username ],
189  __METHOD__,
190  $options
191  );
192  }
193 
195  AuthenticationRequest $req, $checkData = true
196  ) {
197  // We only want to blank the password if something else will accept the
198  // new authentication data, so return 'ignore' here.
199  if ( $this->loginOnly ) {
200  return \StatusValue::newGood( 'ignored' );
201  }
202 
203  if ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
204  if ( !$checkData ) {
205  return \StatusValue::newGood();
206  }
207 
208  $username = User::getCanonicalName( $req->username, 'usable' );
209  if ( $username !== false ) {
210  $row = wfGetDB( DB_MASTER )->selectRow(
211  'user',
212  [ 'user_id' ],
213  [ 'user_name' => $username ],
214  __METHOD__
215  );
216  if ( $row ) {
217  $sv = \StatusValue::newGood();
218  if ( $req->password !== null ) {
219  if ( $req->password !== $req->retype ) {
220  $sv->fatal( 'badretype' );
221  } else {
222  $sv->merge( $this->checkPasswordValidity( $username, $req->password ) );
223  }
224  }
225  return $sv;
226  }
227  }
228  }
229 
230  return \StatusValue::newGood( 'ignored' );
231  }
232 
234  $username = $req->username !== null ? User::getCanonicalName( $req->username, 'usable' ) : false;
235  if ( $username === false ) {
236  return;
237  }
238 
239  $pwhash = null;
240 
241  if ( $this->loginOnly ) {
242  $pwhash = $this->getPasswordFactory()->newFromCiphertext( null );
243  $expiry = null;
244  // @codeCoverageIgnoreStart
245  } elseif ( get_class( $req ) === PasswordAuthenticationRequest::class ) {
246  // @codeCoverageIgnoreEnd
247  $pwhash = $this->getPasswordFactory()->newFromPlaintext( $req->password );
248  $expiry = $this->getNewPasswordExpiry( $username );
249  }
250 
251  if ( $pwhash ) {
252  $dbw = wfGetDB( DB_MASTER );
253  $dbw->update(
254  'user',
255  [
256  'user_password' => $pwhash->toString(),
257  'user_password_expires' => $dbw->timestampOrNull( $expiry ),
258  ],
259  [ 'user_name' => $username ],
260  __METHOD__
261  );
262  }
263  }
264 
265  public function accountCreationType() {
266  return $this->loginOnly ? self::TYPE_NONE : self::TYPE_CREATE;
267  }
268 
269  public function testForAccountCreation( $user, $creator, array $reqs ) {
271 
273  if ( !$this->loginOnly && $req && $req->username !== null && $req->password !== null ) {
274  if ( $req->password !== $req->retype ) {
275  $ret->fatal( 'badretype' );
276  } else {
277  $ret->merge(
278  $this->checkPasswordValidity( $user->getName(), $req->password )
279  );
280  }
281  }
282  return $ret;
283  }
284 
285  public function beginPrimaryAccountCreation( $user, $creator, array $reqs ) {
286  if ( $this->accountCreationType() === self::TYPE_NONE ) {
287  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
288  }
289 
291  if ( $req ) {
292  if ( $req->username !== null && $req->password !== null ) {
293  // Nothing we can do besides claim it, because the user isn't in
294  // the DB yet
295  if ( $req->username !== $user->getName() ) {
296  $req = clone( $req );
297  $req->username = $user->getName();
298  }
300  $ret->createRequest = $req;
301  return $ret;
302  }
303  }
305  }
306 
307  public function finishAccountCreation( $user, $creator, AuthenticationResponse $res ) {
308  if ( $this->accountCreationType() === self::TYPE_NONE ) {
309  throw new \BadMethodCallException( 'Shouldn\'t call this when accountCreationType() is NONE' );
310  }
311 
312  // Now that the user is in the DB, set the password on it.
313  $this->providerChangeAuthenticationData( $res->createRequest );
314 
315  return null;
316  }
317 }
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.
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:1050
providerAllowsAuthenticationDataChange(AuthenticationRequest $req, $checkData=true)
Validate a change of authentication data (e.g.
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:1802
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:2552
This is a value object to hold authentication response data.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
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:1008
$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 and options 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:246
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:969
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:766
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:1008
beginPrimaryAccountCreation($user, $creator, array $reqs)
Start an account creation flow.
const DB_MASTER
Definition: Defines.php:48
getNewPasswordExpiry($username)
Get expiration date for a new password, if any.
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
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.