3 * Authentication request value object
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Auth
;
29 * This is a value object for authentication requests.
31 * An AuthenticationRequest represents a set of form fields that are needed on
32 * and provided from a login, account creation, password change or similar form.
37 abstract class AuthenticationRequest
{
39 /** Indicates that the request is not required for authentication to proceed. */
42 /** Indicates that the request is required for authentication to proceed.
43 * This will only be used for UI purposes; it is the authentication providers'
44 * responsibility to verify that all required requests are present.
48 /** Indicates that the request is required by a primary authentication
49 * provider. Since the user can choose which primary to authenticate with,
50 * the request might or might not end up being actually required.
52 const PRIMARY_REQUIRED
= 2;
54 /** @var string|null The AuthManager::ACTION_* constant this request was
55 * created to be used for. The *_CONTINUE constants are not used here, the
56 * corresponding "begin" constant is used instead.
58 public $action = null;
60 /** @var int For login, continue, and link actions, one of self::OPTIONAL,
61 * self::REQUIRED, or self::PRIMARY_REQUIRED
63 public $required = self
::REQUIRED
;
65 /** @var string|null Return-to URL, in case of redirect */
66 public $returnToUrl = null;
68 /** @var string|null Username. See AuthenticationProvider::getAuthenticationRequests()
69 * for details of what this means and how it behaves.
71 public $username = null;
74 * Supply a unique key for deduplication
76 * When the AuthenticationRequests instances returned by the providers are
77 * merged, the value returned here is used for keeping only one copy of
80 * Subclasses should override this if multiple distinct instances would
81 * make sense, i.e. the request class has internal state of some sort.
83 * This value might be exposed to the user in web forms so it should not
84 * contain private information.
88 public function getUniqueId() {
89 return get_called_class();
93 * Fetch input field info
95 * The field info is an associative array mapping field names to info
96 * arrays. The info arrays have the following keys:
97 * - type: (string) Type of input. Types and equivalent HTML widgets are:
98 * - string: <input type="text">
99 * - password: <input type="password">
101 * - checkbox: <input type="checkbox">
102 * - multiselect: More a grid of checkboxes than <select multi>
103 * - button: <input type="submit"> (uses 'label' as button text)
104 * - hidden: Not visible to the user, but needs to be preserved for the next request
105 * - null: No widget, just display the 'label' message.
106 * - options: (array) Maps option values to Messages for the
107 * 'select' and 'multiselect' types.
108 * - value: (string) Value (for 'null' and 'hidden') or default value (for other types).
109 * - label: (Message) Text suitable for a label in an HTML form
110 * - help: (Message) Text suitable as a description of what the field is
111 * - optional: (bool) If set and truthy, the field may be left empty
112 * - sensitive: (bool) If set and truthy, the field is considered sensitive. Code using the
113 * request should avoid exposing the value of the field.
114 * - skippable: (bool) If set and truthy, the client is free to hide this
115 * field from the user to streamline the workflow. If all fields are
116 * skippable (except possibly a single button), no user interaction is
119 * All AuthenticationRequests are populated from the same data, so most of the time you'll
120 * want to prefix fields names with something unique to the extension/provider (although
121 * in some cases sharing the field with other requests is the right thing to do, e.g. for
122 * a 'password' field).
124 * @return array As above
126 abstract public function getFieldInfo();
129 * Returns metadata about this request.
131 * This is mainly for the benefit of API clients which need more detailed render hints
132 * than what's available through getFieldInfo(). Semantics are unspecified and left to the
133 * individual subclasses, but the contents of the array should be primitive types so that they
134 * can be transformed into JSON or similar formats.
136 * @return array A (possibly nested) array with primitive types
138 public function getMetadata() {
143 * Initialize form submitted form data.
145 * The default behavior is to to check for each key of self::getFieldInfo()
146 * in the submitted data, and copy the value - after type-appropriate transformations -
147 * to $this->$key. Most subclasses won't need to override this; if you do override it,
148 * make sure to always return false if self::getFieldInfo() returns an empty array.
150 * @param array $data Submitted data as an associative array (keys will correspond
152 * @return bool Whether the request data was successfully loaded
154 public function loadFromSubmission( array $data ) {
155 $fields = array_filter( $this->getFieldInfo(), function ( $info ) {
156 return $info['type'] !== 'null';
162 foreach ( $fields as $field => $info ) {
163 // Checkboxes and buttons are special. Depending on the method used
164 // to populate $data, they might be unset meaning false or they
165 // might be boolean. Further, image buttons might submit the
166 // coordinates of the click rather than the expected value.
167 if ( $info['type'] === 'checkbox' ||
$info['type'] === 'button' ) {
168 $this->$field = isset( $data[$field] ) && $data[$field] !== false
169 ||
isset( $data["{$field}_x"] ) && $data["{$field}_x"] !== false;
170 if ( !$this->$field && empty( $info['optional'] ) ) {
176 // Multiselect are too, slightly
177 if ( !isset( $data[$field] ) && $info['type'] === 'multiselect' ) {
181 if ( !isset( $data[$field] ) ) {
184 if ( $data[$field] === '' ||
$data[$field] === [] ) {
185 if ( empty( $info['optional'] ) ) {
189 switch ( $info['type'] ) {
191 if ( !isset( $info['options'][$data[$field]] ) ) {
197 $data[$field] = (array)$data[$field];
198 $allowed = array_keys( $info['options'] );
199 if ( array_diff( $data[$field], $allowed ) !== [] ) {
206 $this->$field = $data[$field];
213 * Describe the credentials represented by this request
215 * This is used on requests returned by
216 * AuthenticationProvider::getAuthenticationRequests() for ACTION_LINK
217 * and ACTION_REMOVE and for requests returned in
218 * AuthenticationResponse::$linkRequest to create useful user interfaces.
220 * @return Message[] with the following keys:
221 * - provider: A Message identifying the service that provides
222 * the credentials, e.g. the name of the third party authentication
224 * - account: A Message identifying the credentials themselves,
225 * e.g. the email address used with the third party authentication
228 public function describeCredentials() {
230 'provider' => new \
RawMessage( '$1', [ get_called_class() ] ),
231 'account' => new \
RawMessage( '$1', [ $this->getUniqueId() ] ),
236 * Update a set of requests with form submit data, discarding ones that fail
237 * @param AuthenticationRequest[] $reqs
239 * @return AuthenticationRequest[]
241 public static function loadRequestsFromSubmission( array $reqs, array $data ) {
242 return array_values( array_filter( $reqs, function ( $req ) use ( $data ) {
243 return $req->loadFromSubmission( $data );
248 * Select a request by class name.
249 * @param AuthenticationRequest[] $reqs
250 * @param string $class Class name
251 * @param bool $allowSubclasses If true, also returns any request that's a subclass of the given
253 * @return AuthenticationRequest|null Returns null if there is not exactly
254 * one matching request.
256 public static function getRequestByClass( array $reqs, $class, $allowSubclasses = false ) {
257 $requests = array_filter( $reqs, function ( $req ) use ( $class, $allowSubclasses ) {
258 if ( $allowSubclasses ) {
259 return is_a( $req, $class, false );
261 return get_class( $req ) === $class;
264 return count( $requests ) === 1 ?
reset( $requests ) : null;
268 * Get the username from the set of requests
270 * Only considers requests that have a "username" field.
272 * @param AuthenticationRequest[] $reqs
273 * @return string|null
274 * @throws \UnexpectedValueException If multiple different usernames are present.
276 public static function getUsernameFromRequests( array $reqs ) {
279 foreach ( $reqs as $req ) {
280 $info = $req->getFieldInfo();
281 if ( $info && array_key_exists( 'username', $info ) && $req->username
!== null ) {
282 if ( $username === null ) {
283 $username = $req->username
;
284 $otherClass = get_class( $req );
285 } elseif ( $username !== $req->username
) {
286 $requestClass = get_class( $req );
287 throw new \
UnexpectedValueException( "Conflicting username fields: \"{$req->username}\" from "
288 . "$requestClass::\$username vs. \"$username\" from $otherClass::\$username" );
296 * Merge the output of multiple AuthenticationRequest::getFieldInfo() calls.
297 * @param AuthenticationRequest[] $reqs
299 * @throws \UnexpectedValueException If fields cannot be merged
301 public static function mergeFieldInfo( array $reqs ) {
304 // fields that are required by some primary providers but not others are not actually required
305 $primaryRequests = array_filter( $reqs, function ( $req ) {
306 return $req->required
=== AuthenticationRequest
::PRIMARY_REQUIRED
;
308 $sharedRequiredPrimaryFields = array_reduce( $primaryRequests, function ( $shared, $req ) {
309 $required = array_keys( array_filter( $req->getFieldInfo(), function ( $options ) {
310 return empty( $options['optional'] );
312 if ( $shared === null ) {
315 return array_intersect( $shared, $required );
319 foreach ( $reqs as $req ) {
320 $info = $req->getFieldInfo();
325 foreach ( $info as $name => $options ) {
327 // If the request isn't required, its fields aren't required either.
328 $req->required
=== self
::OPTIONAL
329 // If there is a primary not requiring this field, no matter how many others do,
330 // authentication can proceed without it.
331 ||
$req->required
=== self
::PRIMARY_REQUIRED
332 && !in_array( $name, $sharedRequiredPrimaryFields, true )
334 $options['optional'] = true;
336 $options['optional'] = !empty( $options['optional'] );
339 $options['sensitive'] = !empty( $options['sensitive'] );
341 if ( !array_key_exists( $name, $merged ) ) {
342 $merged[$name] = $options;
343 } elseif ( $merged[$name]['type'] !== $options['type'] ) {
344 throw new \
UnexpectedValueException( "Field type conflict for \"$name\", " .
345 "\"{$merged[$name]['type']}\" vs \"{$options['type']}\""
348 if ( isset( $options['options'] ) ) {
349 if ( isset( $merged[$name]['options'] ) ) {
350 $merged[$name]['options'] +
= $options['options'];
352 // @codeCoverageIgnoreStart
353 $merged[$name]['options'] = $options['options'];
354 // @codeCoverageIgnoreEnd
358 $merged[$name]['optional'] = $merged[$name]['optional'] && $options['optional'];
359 $merged[$name]['sensitive'] = $merged[$name]['sensitive'] ||
$options['sensitive'];
361 // No way to merge 'value', 'image', 'help', or 'label', so just use
362 // the value from the first request.
371 * Implementing this mainly for use from the unit tests.
373 * @return AuthenticationRequest
375 public static function __set_state( $data ) {
376 // @phan-suppress-next-line PhanTypeInstantiateAbstract
378 foreach ( $data as $k => $v ) {