MediaWiki  master
SessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Config;
27 use Language;
31 use Psr\Log\LoggerInterface;
32 use User;
33 use WebRequest;
34 
81 abstract class SessionProvider implements SessionProviderInterface {
82 
84  protected $logger;
85 
87  protected $config;
88 
90  protected $manager;
91 
93  private $hookContainer;
94 
96  private $hookRunner;
97 
99  protected $userNameUtils;
100 
104  protected $priority;
105 
109  public function __construct() {
110  $this->priority = SessionInfo::MIN_PRIORITY + 10;
111  }
112 
126  public function init(
127  LoggerInterface $logger,
128  Config $config,
132  ) {
133  $this->logger = $logger;
134  $this->config = $config;
135  $this->manager = $manager;
136  $this->hookContainer = $hookContainer;
137  $this->hookRunner = new HookRunner( $hookContainer );
138  $this->userNameUtils = $userNameUtils;
139  $this->postInitSetup();
140  }
141 
149  protected function postInitSetup() {
150  }
151 
163  public function setLogger( LoggerInterface $logger ) {
164  wfDeprecated( __METHOD__, '1.37' );
165  $this->logger = $logger;
166  }
167 
179  public function setConfig( Config $config ) {
180  wfDeprecated( __METHOD__, '1.37' );
181  $this->config = $config;
182  }
183 
190  protected function getConfig() {
191  return $this->config;
192  }
193 
205  public function setManager( SessionManager $manager ) {
206  wfDeprecated( __METHOD__, '1.37' );
207  $this->manager = $manager;
208  }
209 
214  public function getManager() {
215  return $this->manager;
216  }
217 
228  public function setHookContainer( $hookContainer ) {
229  wfDeprecated( __METHOD__, '1.37' );
230  $this->hookContainer = $hookContainer;
231  $this->hookRunner = new HookRunner( $hookContainer );
232  }
233 
239  protected function getHookContainer(): HookContainer {
240  return $this->hookContainer;
241  }
242 
251  protected function getHookRunner(): HookRunner {
252  return $this->hookRunner;
253  }
254 
277  abstract public function provideSessionInfo( WebRequest $request );
278 
293  public function newSessionInfo( $id = null ) {
294  if ( $this->canChangeUser() && $this->persistsSessionId() ) {
295  return new SessionInfo( $this->priority, [
296  'id' => $id,
297  'provider' => $this,
298  'persisted' => false,
299  'idIsSafe' => true,
300  ] );
301  }
302  return null;
303  }
304 
327  public function mergeMetadata( array $savedMetadata, array $providedMetadata ) {
328  foreach ( $providedMetadata as $k => $v ) {
329  if ( array_key_exists( $k, $savedMetadata ) && $savedMetadata[$k] !== $v ) {
330  $e = new MetadataMergeException( "Key \"$k\" changed" );
331  $e->setContext( [
332  'old_value' => $savedMetadata[$k],
333  'new_value' => $v,
334  ] );
335  throw $e;
336  }
337  }
338  return $providedMetadata;
339  }
340 
355  public function refreshSessionInfo( SessionInfo $info, WebRequest $request, &$metadata ) {
356  return true;
357  }
358 
385  abstract public function persistsSessionId();
386 
412  abstract public function canChangeUser();
413 
421  public function getRememberUserDuration() {
422  return null;
423  }
424 
436  public function sessionIdWasReset( SessionBackend $session, $oldId ) {
437  }
438 
466  abstract public function persistSession( SessionBackend $session, WebRequest $request );
467 
479  abstract public function unpersistSession( WebRequest $request );
480 
503  public function preventSessionsForUser( $username ) {
504  if ( !$this->canChangeUser() ) {
505  throw new \BadMethodCallException(
506  __METHOD__ . ' must be implemented when canChangeUser() is false'
507  );
508  }
509  }
510 
522  public function invalidateSessionsForUser( User $user ) {
523  }
524 
542  public function getVaryHeaders() {
543  return [];
544  }
545 
552  public function getVaryCookies() {
553  return [];
554  }
555 
563  public function suggestLoginUsername( WebRequest $request ) {
564  return null;
565  }
566 
578  public function getAllowedUserRights( SessionBackend $backend ) {
579  if ( $backend->getProvider() !== $this ) {
580  // Not that this should ever happen...
581  throw new \InvalidArgumentException( 'Backend\'s provider isn\'t $this' );
582  }
583 
584  return null;
585  }
586 
594  public function __toString() {
595  return static::class;
596  }
597 
614  protected function describeMessage() {
615  return wfMessage(
616  'sessionprovider-' . str_replace( '\\', '-', strtolower( static::class ) )
617  );
618  }
619 
624  public function describe( Language $lang ) {
625  $msg = $this->describeMessage();
626  $msg->inLanguage( $lang );
627  if ( $msg->isDisabled() ) {
628  $msg = wfMessage( 'sessionprovider-generic', (string)$this )->inLanguage( $lang );
629  }
630  return $msg->plain();
631  }
632 
637  public function whyNoSession() {
638  return null;
639  }
640 
647  public function safeAgainstCsrf() {
648  return false;
649  }
650 
664  final protected function hashToSessionId( $data, $key = null ) {
665  if ( !is_string( $data ) ) {
666  throw new \InvalidArgumentException(
667  '$data must be a string, ' . gettype( $data ) . ' was passed'
668  );
669  }
670  if ( $key !== null && !is_string( $key ) ) {
671  throw new \InvalidArgumentException(
672  '$key must be a string or null, ' . gettype( $key ) . ' was passed'
673  );
674  }
675 
676  $hash = \MWCryptHash::hmac( "$this\n$data", $key ?: $this->getConfig()->get( 'SecretKey' ), false );
677  if ( strlen( $hash ) < 32 ) {
678  // Should never happen, even md5 is 128 bits
679  // @codeCoverageIgnoreStart
680  throw new \UnexpectedValueException( 'Hash function returned less than 128 bits' );
681  // @codeCoverageIgnoreEnd
682  }
683  if ( strlen( $hash ) >= 40 ) {
684  $hash = \Wikimedia\base_convert( $hash, 16, 32, 32 );
685  }
686  return substr( $hash, -32 );
687  }
688 
689 }
MediaWiki\Session\SessionProvider\getAllowedUserRights
getAllowedUserRights(SessionBackend $backend)
Fetch the rights allowed the user when the specified session is active.
Definition: SessionProvider.php:578
MediaWiki\Session\SessionProvider\init
init(LoggerInterface $logger, Config $config, SessionManager $manager, HookContainer $hookContainer, UserNameUtils $userNameUtils)
Initialise with dependencies of a SessionProvider.
Definition: SessionProvider.php:126
MediaWiki\Session\SessionProvider\$userNameUtils
UserNameUtils $userNameUtils
Definition: SessionProvider.php:99
MediaWiki\Session\SessionProvider\getManager
getManager()
Get the session manager.
Definition: SessionProvider.php:214
MediaWiki\Session\SessionProvider\newSessionInfo
newSessionInfo( $id=null)
Provide session info for a new, empty session.
Definition: SessionProvider.php:293
MWCryptHash\hmac
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
Definition: MWCryptHash.php:106
MediaWiki\Session\SessionProvider\setLogger
setLogger(LoggerInterface $logger)
Sets a logger instance on the object.
Definition: SessionProvider.php:163
MediaWiki\Session\SessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: SessionProvider.php:421
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
MediaWiki\Session\SessionBackend\getProvider
getProvider()
Fetch the SessionProvider for this session.
Definition: SessionBackend.php:309
MediaWiki\Session\MetadataMergeException
Subclass of UnexpectedValueException that can be annotated with additional data for debug logging.
Definition: MetadataMergeException.php:36
MediaWiki\Session\SessionProvider\persistsSessionId
persistsSessionId()
Indicate whether self::persistSession() can save arbitrary session IDs.
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1186
MediaWiki\Session\SessionProvider\describeMessage
describeMessage()
Return a Message identifying this session type.
Definition: SessionProvider.php:614
MediaWiki\Session\SessionProvider\getHookContainer
getHookContainer()
Get the HookContainer.
Definition: SessionProvider.php:239
MediaWiki\Session\SessionProvider\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: SessionProvider.php:552
Config
Interface for configuration instances.
Definition: Config.php:30
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
MediaWiki\Session\SessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
MediaWiki\Session\SessionProvider\__construct
__construct()
Definition: SessionProvider.php:109
MediaWiki\Session\SessionProvider
A SessionProvider provides SessionInfo and support for Session.
Definition: SessionProvider.php:81
MediaWiki\Session\SessionProvider\setManager
setManager(SessionManager $manager)
Set the session manager.
Definition: SessionProvider.php:205
MediaWiki\Session\SessionProvider\unpersistSession
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
MediaWiki\Session\SessionProvider\suggestLoginUsername
suggestLoginUsername(WebRequest $request)
Get a suggested username for the login form.
Definition: SessionProvider.php:563
MediaWiki\Session
Definition: BotPasswordSessionProvider.php:24
MediaWiki\Session\SessionProvider\whyNoSession
whyNoSession()
Return a Message for why sessions might not be being persisted.For example, "check whether you're blo...
Definition: SessionProvider.php:637
MediaWiki\Session\SessionProvider\preventSessionsForUser
preventSessionsForUser( $username)
Prevent future sessions for the user.
Definition: SessionProvider.php:503
MediaWiki\Session\SessionProvider\$logger
LoggerInterface $logger
Definition: SessionProvider.php:84
MediaWiki\Session\SessionProviderInterface
This exists to make IDEs happy, so they don't see the internal-but-required-to-be-public methods on S...
Definition: SessionProviderInterface.php:36
MediaWiki\Session\SessionProvider\__toString
__toString()
Definition: SessionProvider.php:594
MediaWiki\Session\SessionProvider\postInitSetup
postInitSetup()
A provider can override this to do any necessary setup after init() is called.
Definition: SessionProvider.php:149
MediaWiki\Session\SessionProvider\refreshSessionInfo
refreshSessionInfo(SessionInfo $info, WebRequest $request, &$metadata)
Validate a loaded SessionInfo and refresh provider metadata.
Definition: SessionProvider.php:355
MediaWiki\Session\SessionProvider\invalidateSessionsForUser
invalidateSessionsForUser(User $user)
Invalidate existing sessions for a user.
Definition: SessionProvider.php:522
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:83
MediaWiki\Session\SessionProvider\mergeMetadata
mergeMetadata(array $savedMetadata, array $providedMetadata)
Merge saved session provider metadata.
Definition: SessionProvider.php:327
MediaWiki\Session\SessionProvider\$hookContainer
HookContainer $hookContainer
Definition: SessionProvider.php:93
MediaWiki\Session\SessionProvider\setConfig
setConfig(Config $config)
Set configuration.
Definition: SessionProvider.php:179
MediaWiki\Session\SessionProvider\persistSession
persistSession(SessionBackend $session, WebRequest $request)
Persist a session into a request/response.
MediaWiki\Session\SessionProvider\safeAgainstCsrf
safeAgainstCsrf()
Most session providers require protection against CSRF attacks (usually via CSRF tokens)
Definition: SessionProvider.php:647
MediaWiki\Session\SessionProvider\$config
Config $config
Definition: SessionProvider.php:87
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:43
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:37
MediaWiki\Session\SessionProvider\getConfig
getConfig()
Get the config.
Definition: SessionProvider.php:190
MediaWiki\User\UserNameUtils
UserNameUtils service.
Definition: UserNameUtils.php:42
MediaWiki\Session\SessionProvider\describe
describe(Language $lang)
Return an identifier for this session type.Language to use. string
Definition: SessionProvider.php:624
MediaWiki\Session\SessionProvider\canChangeUser
canChangeUser()
Indicate whether the user associated with the request can be changed.
MediaWiki\Session\SessionProvider\$priority
int $priority
Session priority.
Definition: SessionProvider.php:104
MediaWiki\Session\SessionProvider\setHookContainer
setHookContainer( $hookContainer)
Definition: SessionProvider.php:228
MediaWiki\Session\SessionProvider\sessionIdWasReset
sessionIdWasReset(SessionBackend $session, $oldId)
Notification that the session ID was reset.
Definition: SessionProvider.php:436
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:556
MediaWiki\Session\SessionProvider\$manager
SessionManager $manager
Definition: SessionProvider.php:90
MediaWiki\Session\SessionProvider\getVaryHeaders
getVaryHeaders()
Return the HTTP headers that need varying on.
Definition: SessionProvider.php:542
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:68
MediaWiki\Session\SessionInfo\MIN_PRIORITY
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:39
MediaWiki\Session\SessionProvider\$hookRunner
HookRunner $hookRunner
Definition: SessionProvider.php:96
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:53
MediaWiki\Session\SessionProvider\hashToSessionId
hashToSessionId( $data, $key=null)
Hash data as a session ID.
Definition: SessionProvider.php:664
MediaWiki\Session\SessionProvider\getHookRunner
getHookRunner()
Get the HookRunner.
Definition: SessionProvider.php:251