MediaWiki  master
SessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Config;
27 use Language;
30 use Psr\Log\LoggerAwareInterface;
31 use Psr\Log\LoggerInterface;
32 use User;
33 use WebRequest;
34 
81 abstract class SessionProvider implements SessionProviderInterface, LoggerAwareInterface {
82 
84  protected $logger;
85 
87  protected $config;
88 
90  protected $manager;
91 
93  private $hookContainer;
94 
96  private $hookRunner;
97 
101  protected $priority;
102 
110  public function __construct() {
111  $this->priority = SessionInfo::MIN_PRIORITY + 10;
112  }
113 
114  public function setLogger( LoggerInterface $logger ) {
115  $this->logger = $logger;
116  }
117 
122  public function setConfig( Config $config ) {
123  $this->config = $config;
124  }
125 
130  public function setManager( SessionManager $manager ) {
131  $this->manager = $manager;
132  }
133 
138  public function getManager() {
139  return $this->manager;
140  }
141 
147  public function setHookContainer( $hookContainer ) {
148  $this->hookContainer = $hookContainer;
149  $this->hookRunner = new HookRunner( $hookContainer );
150  }
151 
157  protected function getHookContainer() : HookContainer {
158  return $this->hookContainer;
159  }
160 
169  protected function getHookRunner() : HookRunner {
170  return $this->hookRunner;
171  }
172 
195  abstract public function provideSessionInfo( WebRequest $request );
196 
211  public function newSessionInfo( $id = null ) {
212  if ( $this->canChangeUser() && $this->persistsSessionId() ) {
213  return new SessionInfo( $this->priority, [
214  'id' => $id,
215  'provider' => $this,
216  'persisted' => false,
217  'idIsSafe' => true,
218  ] );
219  }
220  return null;
221  }
222 
245  public function mergeMetadata( array $savedMetadata, array $providedMetadata ) {
246  foreach ( $providedMetadata as $k => $v ) {
247  if ( array_key_exists( $k, $savedMetadata ) && $savedMetadata[$k] !== $v ) {
248  $e = new MetadataMergeException( "Key \"$k\" changed" );
249  $e->setContext( [
250  'old_value' => $savedMetadata[$k],
251  'new_value' => $v,
252  ] );
253  throw $e;
254  }
255  }
256  return $providedMetadata;
257  }
258 
273  public function refreshSessionInfo( SessionInfo $info, WebRequest $request, &$metadata ) {
274  return true;
275  }
276 
303  abstract public function persistsSessionId();
304 
330  abstract public function canChangeUser();
331 
339  public function getRememberUserDuration() {
340  return null;
341  }
342 
354  public function sessionIdWasReset( SessionBackend $session, $oldId ) {
355  }
356 
384  abstract public function persistSession( SessionBackend $session, WebRequest $request );
385 
397  abstract public function unpersistSession( WebRequest $request );
398 
421  public function preventSessionsForUser( $username ) {
422  if ( !$this->canChangeUser() ) {
423  throw new \BadMethodCallException(
424  __METHOD__ . ' must be implemented when canChangeUser() is false'
425  );
426  }
427  }
428 
440  public function invalidateSessionsForUser( User $user ) {
441  }
442 
460  public function getVaryHeaders() {
461  return [];
462  }
463 
470  public function getVaryCookies() {
471  return [];
472  }
473 
481  public function suggestLoginUsername( WebRequest $request ) {
482  return null;
483  }
484 
496  public function getAllowedUserRights( SessionBackend $backend ) {
497  if ( $backend->getProvider() !== $this ) {
498  // Not that this should ever happen...
499  throw new \InvalidArgumentException( 'Backend\'s provider isn\'t $this' );
500  }
501 
502  return null;
503  }
504 
512  public function __toString() {
513  return static::class;
514  }
515 
532  protected function describeMessage() {
533  return wfMessage(
534  'sessionprovider-' . str_replace( '\\', '-', strtolower( static::class ) )
535  );
536  }
537 
542  public function describe( Language $lang ) {
543  $msg = $this->describeMessage();
544  $msg->inLanguage( $lang );
545  if ( $msg->isDisabled() ) {
546  $msg = wfMessage( 'sessionprovider-generic', (string)$this )->inLanguage( $lang );
547  }
548  return $msg->plain();
549  }
550 
555  public function whyNoSession() {
556  return null;
557  }
558 
565  public function safeAgainstCsrf() {
566  return false;
567  }
568 
582  final protected function hashToSessionId( $data, $key = null ) {
583  if ( !is_string( $data ) ) {
584  throw new \InvalidArgumentException(
585  '$data must be a string, ' . gettype( $data ) . ' was passed'
586  );
587  }
588  if ( $key !== null && !is_string( $key ) ) {
589  throw new \InvalidArgumentException(
590  '$key must be a string or null, ' . gettype( $key ) . ' was passed'
591  );
592  }
593 
594  $hash = \MWCryptHash::hmac( "$this\n$data", $key ?: $this->config->get( 'SecretKey' ), false );
595  if ( strlen( $hash ) < 32 ) {
596  // Should never happen, even md5 is 128 bits
597  // @codeCoverageIgnoreStart
598  throw new \UnexpectedValueException( 'Hash function returned less than 128 bits' );
599  // @codeCoverageIgnoreEnd
600  }
601  if ( strlen( $hash ) >= 40 ) {
602  $hash = \Wikimedia\base_convert( $hash, 16, 32, 32 );
603  }
604  return substr( $hash, -32 );
605  }
606 
607 }
MediaWiki\Session\SessionProvider\getAllowedUserRights
getAllowedUserRights(SessionBackend $backend)
Fetch the rights allowed the user when the specified session is active.
Definition: SessionProvider.php:496
MediaWiki\Session\SessionProvider\getManager
getManager()
Get the session manager.
Definition: SessionProvider.php:138
MediaWiki\Session\SessionProvider\newSessionInfo
newSessionInfo( $id=null)
Provide session info for a new, empty session.
Definition: SessionProvider.php:211
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)
Definition: SessionProvider.php:114
MediaWiki\Session\SessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: SessionProvider.php:339
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
MediaWiki\Session\SessionBackend\getProvider
getProvider()
Fetch the SessionProvider for this session.
Definition: SessionBackend.php:308
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:1220
MediaWiki\Session\SessionProvider\describeMessage
describeMessage()
Return a Message identifying this session type.
Definition: SessionProvider.php:532
MediaWiki\Session\SessionProvider\getHookContainer
getHookContainer()
Get the HookContainer.
Definition: SessionProvider.php:157
MediaWiki\Session\SessionProvider\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: SessionProvider.php:470
Config
Interface for configuration instances.
Definition: Config.php:30
MediaWiki\Session\SessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
MediaWiki\Session\SessionProvider\__construct
__construct()
Stable to call.
Definition: SessionProvider.php:110
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:130
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 Stable to override.
Definition: SessionProvider.php:481
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:555
MediaWiki\Session\SessionProvider\preventSessionsForUser
preventSessionsForUser( $username)
Prevent future sessions for the user.
Definition: SessionProvider.php:421
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:512
MediaWiki\Session\SessionProvider\refreshSessionInfo
refreshSessionInfo(SessionInfo $info, WebRequest $request, &$metadata)
Validate a loaded SessionInfo and refresh provider metadata.
Definition: SessionProvider.php:273
MediaWiki\Session\SessionProvider\invalidateSessionsForUser
invalidateSessionsForUser(User $user)
Invalidate existing sessions for a user.
Definition: SessionProvider.php:440
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:53
MediaWiki\Session\SessionProvider\mergeMetadata
mergeMetadata(array $savedMetadata, array $providedMetadata)
Merge saved session provider metadata.
Definition: SessionProvider.php:245
MediaWiki\Session\SessionProvider\$hookContainer
HookContainer $hookContainer
Definition: SessionProvider.php:93
MediaWiki\Session\SessionProvider\setConfig
setConfig(Config $config)
Set configuration.
Definition: SessionProvider.php:122
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:565
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:42
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:37
MediaWiki\Session\SessionProvider\describe
describe(Language $lang)
Return an identifier for this session type.Language to use. string Stable to override
Definition: SessionProvider.php:542
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:101
MediaWiki\Session\SessionProvider\setHookContainer
setHookContainer( $hookContainer)
Set the hook container.
Definition: SessionProvider.php:147
MediaWiki\Session\SessionProvider\sessionIdWasReset
sessionIdWasReset(SessionBackend $session, $oldId)
Notification that the session ID was reset.
Definition: SessionProvider.php:354
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:562
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:460
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
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:41
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:52
MediaWiki\Session\SessionProvider\hashToSessionId
hashToSessionId( $data, $key=null)
Hash data as a session ID.
Definition: SessionProvider.php:582
MediaWiki\Session\SessionProvider\getHookRunner
getHookRunner()
Get the HookRunner.
Definition: SessionProvider.php:169