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