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. */
51 const PRIMARY_REQUIRED
= 2;
53 /** @var string|null The AuthManager::ACTION_* constant this request was
54 * created to be used for. The *_CONTINUE constants are not used here, the
55 * corresponding "begin" constant is used instead.
57 public $action = null;
59 /** @var int For login, continue, and link actions, one of self::OPTIONAL,
60 * self::REQUIRED, or self::PRIMARY_REQUIRED */
61 public $required = self
::REQUIRED
;
63 /** @var string|null Return-to URL, in case of redirect */
64 public $returnToUrl = null;
66 /** @var string|null Username. See AuthenticationProvider::getAuthenticationRequests()
67 * for details of what this means and how it behaves. */
68 public $username = null;
71 * Supply a unique key for deduplication
73 * When the AuthenticationRequests instances returned by the providers are
74 * merged, the value returned here is used for keeping only one copy of
77 * Subclasses should override this if multiple distinct instances would
78 * make sense, i.e. the request class has internal state of some sort.
80 * This value might be exposed to the user in web forms so it should not
81 * contain private information.
85 public function getUniqueId() {
86 return get_called_class();
90 * Fetch input field info
92 * The field info is an associative array mapping field names to info
93 * arrays. The info arrays have the following keys:
94 * - type: (string) Type of input. Types and equivalent HTML widgets are:
95 * - string: <input type="text">
96 * - password: <input type="password">
98 * - checkbox: <input type="checkbox">
99 * - multiselect: More a grid of checkboxes than <select multi>
100 * - button: <input type="submit"> (uses 'label' as button text)
101 * - hidden: Not visible to the user, but needs to be preserved for the next request
102 * - null: No widget, just display the 'label' message.
103 * - options: (array) Maps option values to Messages for the
104 * 'select' and 'multiselect' types.
105 * - value: (string) Value (for 'null' and 'hidden') or default value (for other types).
106 * - label: (Message) Text suitable for a label in an HTML form
107 * - help: (Message) Text suitable as a description of what the field is
108 * - optional: (bool) If set and truthy, the field may be left empty
109 * - sensitive: (bool) If set and truthy, the field is considered sensitive. Code using the
110 * request should avoid exposing the value of the field.
112 * All AuthenticationRequests are populated from the same data, so most of the time you'll
113 * want to prefix fields names with something unique to the extension/provider (although
114 * in some cases sharing the field with other requests is the right thing to do, e.g. for
115 * a 'password' field).
117 * @return array As above
119 abstract public function getFieldInfo();
122 * Returns metadata about this request.
124 * This is mainly for the benefit of API clients which need more detailed render hints
125 * than what's available through getFieldInfo(). Semantics are unspecified and left to the
126 * individual subclasses, but the contents of the array should be primitive types so that they
127 * can be transformed into JSON or similar formats.
129 * @return array A (possibly nested) array with primitive types
131 public function getMetadata() {
136 * Initialize form submitted form data.
138 * The default behavior is to to check for each key of self::getFieldInfo()
139 * in the submitted data, and copy the value - after type-appropriate transformations -
140 * to $this->$key. Most subclasses won't need to override this; if you do override it,
141 * make sure to always return false if self::getFieldInfo() returns an empty array.
143 * @param array $data Submitted data as an associative array (keys will correspond
145 * @return bool Whether the request data was successfully loaded
147 public function loadFromSubmission( array $data ) {
148 $fields = array_filter( $this->getFieldInfo(), function ( $info ) {
149 return $info['type'] !== 'null';
155 foreach ( $fields as $field => $info ) {
156 // Checkboxes and buttons are special. Depending on the method used
157 // to populate $data, they might be unset meaning false or they
158 // might be boolean. Further, image buttons might submit the
159 // coordinates of the click rather than the expected value.
160 if ( $info['type'] === 'checkbox' ||
$info['type'] === 'button' ) {
161 $this->$field = isset( $data[$field] ) && $data[$field] !== false
162 ||
isset( $data["{$field}_x"] ) && $data["{$field}_x"] !== false;
163 if ( !$this->$field && empty( $info['optional'] ) ) {
169 // Multiselect are too, slightly
170 if ( !isset( $data[$field] ) && $info['type'] === 'multiselect' ) {
174 if ( !isset( $data[$field] ) ) {
177 if ( $data[$field] === '' ||
$data[$field] === [] ) {
178 if ( empty( $info['optional'] ) ) {
182 switch ( $info['type'] ) {
184 if ( !isset( $info['options'][$data[$field]] ) ) {
190 $data[$field] = (array)$data[$field];
191 $allowed = array_keys( $info['options'] );
192 if ( array_diff( $data[$field], $allowed ) !== [] ) {
199 $this->$field = $data[$field];
206 * Describe the credentials represented by this request
208 * This is used on requests returned by
209 * AuthenticationProvider::getAuthenticationRequests() for ACTION_LINK
210 * and ACTION_REMOVE and for requests returned in
211 * AuthenticationResponse::$linkRequest to create useful user interfaces.
213 * @return Message[] with the following keys:
214 * - provider: A Message identifying the service that provides
215 * the credentials, e.g. the name of the third party authentication
217 * - account: A Message identifying the credentials themselves,
218 * e.g. the email address used with the third party authentication
221 public function describeCredentials() {
223 'provider' => new \
RawMessage( '$1', [ get_called_class() ] ),
224 'account' => new \
RawMessage( '$1', [ $this->getUniqueId() ] ),
229 * Update a set of requests with form submit data, discarding ones that fail
230 * @param AuthenticationRequest[] $reqs
232 * @return AuthenticationRequest[]
234 public static function loadRequestsFromSubmission( array $reqs, array $data ) {
235 return array_values( array_filter( $reqs, function ( $req ) use ( $data ) {
236 return $req->loadFromSubmission( $data );
241 * Select a request by class name.
242 * @param AuthenticationRequest[] $reqs
243 * @param string $class Class name
244 * @param bool $allowSubclasses If true, also returns any request that's a subclass of the given
246 * @return AuthenticationRequest|null Returns null if there is not exactly
247 * one matching request.
249 public static function getRequestByClass( array $reqs, $class, $allowSubclasses = false ) {
250 $requests = array_filter( $reqs, function ( $req ) use ( $class, $allowSubclasses ) {
251 if ( $allowSubclasses ) {
252 return is_a( $req, $class, false );
254 return get_class( $req ) === $class;
257 return count( $requests ) === 1 ?
reset( $requests ) : null;
261 * Get the username from the set of requests
263 * Only considers requests that have a "username" field.
265 * @param AuthenticationRequest[] $reqs
266 * @return string|null
267 * @throws \UnexpectedValueException If multiple different usernames are present.
269 public static function getUsernameFromRequests( array $reqs ) {
272 foreach ( $reqs as $req ) {
273 $info = $req->getFieldInfo();
274 if ( $info && array_key_exists( 'username', $info ) && $req->username
!== null ) {
275 if ( $username === null ) {
276 $username = $req->username
;
277 $otherClass = get_class( $req );
278 } elseif ( $username !== $req->username
) {
279 $requestClass = get_class( $req );
280 throw new \
UnexpectedValueException( "Conflicting username fields: \"{$req->username}\" from "
281 . "$requestClass::\$username vs. \"$username\" from $otherClass::\$username" );
289 * Merge the output of multiple AuthenticationRequest::getFieldInfo() calls.
290 * @param AuthenticationRequest[] $reqs
292 * @throws \UnexpectedValueException If fields cannot be merged
294 public static function mergeFieldInfo( array $reqs ) {
297 // fields that are required by some primary providers but not others are not actually required
298 $primaryRequests = array_filter( $reqs, function ( $req ) {
299 return $req->required
=== AuthenticationRequest
::PRIMARY_REQUIRED
;
301 $sharedRequiredPrimaryFields = array_reduce( $primaryRequests, function ( $shared, $req ) {
302 $required = array_keys( array_filter( $req->getFieldInfo(), function ( $options ) {
303 return empty( $options['optional'] );
305 if ( $shared === null ) {
308 return array_intersect( $shared, $required );
312 foreach ( $reqs as $req ) {
313 $info = $req->getFieldInfo();
318 foreach ( $info as $name => $options ) {
320 // If the request isn't required, its fields aren't required either.
321 $req->required
=== self
::OPTIONAL
322 // If there is a primary not requiring this field, no matter how many others do,
323 // authentication can proceed without it.
324 ||
$req->required
=== self
::PRIMARY_REQUIRED
325 && !in_array( $name, $sharedRequiredPrimaryFields, true )
327 $options['optional'] = true;
329 $options['optional'] = !empty( $options['optional'] );
332 $options['sensitive'] = !empty( $options['sensitive'] );
334 if ( !array_key_exists( $name, $merged ) ) {
335 $merged[$name] = $options;
336 } elseif ( $merged[$name]['type'] !== $options['type'] ) {
337 throw new \
UnexpectedValueException( "Field type conflict for \"$name\", " .
338 "\"{$merged[$name]['type']}\" vs \"{$options['type']}\""
341 if ( isset( $options['options'] ) ) {
342 if ( isset( $merged[$name]['options'] ) ) {
343 $merged[$name]['options'] +
= $options['options'];
345 // @codeCoverageIgnoreStart
346 $merged[$name]['options'] = $options['options'];
347 // @codeCoverageIgnoreEnd
351 $merged[$name]['optional'] = $merged[$name]['optional'] && $options['optional'];
352 $merged[$name]['sensitive'] = $merged[$name]['sensitive'] ||
$options['sensitive'];
354 // No way to merge 'value', 'image', 'help', or 'label', so just use
355 // the value from the first request.
364 * Implementing this mainly for use from the unit tests.
366 * @return AuthenticationRequest
368 public static function __set_state( $data ) {
370 foreach ( $data as $k => $v ) {