Jump to content

Manual:SessionManager and AuthManager/SessionProvider examples

From mediawiki.org

Use cookies set by some external authentication system

[edit]
use MediaWiki\Session\ImmutableSessionProviderWithCookie;
use MediaWiki\Session\UserInfo;

class MySessionProvider extends ImmutableSessionProviderWithCookie {
    public function provideSessionInfo( WebRequest $request ) {
        $data = $request->getCookie( 'someCookie' );
        $isLoggedIn = getLoggedInStatusFromCookieSomehow( $data );
        $username = getUsernameFromCookieSomehow( $data ); // assumed to be safe against tampering
        if ( !$isLoggedIn ) {
            return null;
        }

        // Beware of mismatches in allowed characters or semantics in the username.
        // For example, MediaWiki ignores the case of only the first letter, while
        // the external system may be fully case-sensitive or case-insensitive.
        // See T165795 for an example of such a bug.
        $userInfo = UserInfo::newFromName( $username, true );

        if ( $this->sessionCookieName === null ) {
            $id = $this->hashToSessionId( $username );
            $persisted = false;
            $forceUse = true;
        } else {
            $id = $this->getSessionIdFromCookie( $request );
            $persisted = $id !== null;
            $forceUse = false;
        }

        return new SessionInfo( SessionInfo::MAX_PRIORITY, [
            'provider' => $this,
            'id' => $id,
            'userInfo' => $userInfo,
            'persisted' => $persisted,
            'forceUse' => $forceUse,
        ] );
    }
}