Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
CentralAuthApiTokenGenerator | |
100.00% |
15 / 15 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getToken | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | |
3 | namespace MediaWiki\Extension\CentralAuth; |
4 | |
5 | use InvalidArgumentException; |
6 | use MediaWiki\Extension\CentralAuth\User\CentralAuthUser; |
7 | use MediaWiki\User\UserIdentity; |
8 | use MWCryptRand; |
9 | |
10 | /** |
11 | * Generate an authentication token to be used for API calls. |
12 | */ |
13 | class CentralAuthApiTokenGenerator { |
14 | |
15 | private CentralAuthTokenManager $tokenManager; |
16 | |
17 | public function __construct( |
18 | CentralAuthTokenManager $tokenManager |
19 | ) { |
20 | $this->tokenManager = $tokenManager; |
21 | } |
22 | |
23 | /** |
24 | * Get a CentralAuth token for making authenticated API requests to an attached wiki. |
25 | * |
26 | * @param UserIdentity $user The registered user |
27 | * @param string $sessionId The global session ID |
28 | * @param string $wikiId The wiki ID |
29 | * @return string Token in hexadecimal, with a random part and the central user ID |
30 | * @throws InvalidArgumentException |
31 | */ |
32 | public function getToken( UserIdentity $user, string $sessionId, string $wikiId ) { |
33 | if ( !$user->isRegistered() ) { |
34 | throw new InvalidArgumentException( 'Cannot get a token for an unregistered user' ); |
35 | } |
36 | |
37 | $centralUser = CentralAuthUser::getInstance( $user ); |
38 | if ( !$centralUser->exists() || !$centralUser->isAttached() ) { |
39 | throw new InvalidArgumentException( 'Cannot get a token without an attached global user' ); |
40 | } |
41 | |
42 | $data = [ |
43 | 'userName' => $user->getName(), |
44 | 'token' => $centralUser->getAuthToken(), |
45 | 'origin' => $wikiId, |
46 | 'originSessionId' => $sessionId, |
47 | ]; |
48 | $loginToken = MWCryptRand::generateHex( 32 ) . dechex( $centralUser->getId() ); |
49 | $this->tokenManager->tokenize( $data, 'api-token', [ 'token' => $loginToken ] ); |
50 | |
51 | return $loginToken; |
52 | } |
53 | |
54 | } |