Created
March 15, 2017 13:49
-
-
Save MikuAuahDark/b9c832631e1b82b7395893fbe97eeb5c to your computer and use it in GitHub Desktop.
NPPS3 example login/authkey
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// login/authkey | |
return new class implements NPPS\ActionHandler | |
{ | |
private $NPPSDB = NULL; | |
function __construct() | |
{ | |
$NPPSDB = NPPS\GetMainDatabase(); | |
} | |
function __destruct() {} | |
public function Permissions(): int | |
{ | |
return | |
NPPS_ACCESSLEVEL_UNAUTHENTICATED | // Anyone can access this, even without token | |
NPPS_PERMISSION_NOMULTI | // This module can't be accessed under /api | |
NPPS_PERMISSION_NOXMC; // X-Message-Code header is not needed for this | |
} | |
public function Parameters(): array | |
{ | |
// Check if new authentication method is on (v4.3+) | |
if(NPPS\GetConfig('NEW_AUTHENTICATION')) | |
return [ | |
'dummy_token' => NPPS_DATATYPE_STRING, // dummy_token must be string | |
'auth_data' => NPPS_DATATYPE_STRING // auth_data must be string | |
]; | |
else | |
return []; // No arguments | |
} | |
public function Execute(array $RequestData): NPPS\ActionHandlerResult | |
{ | |
if(NPPS\GetConfig('NEW_AUTHENTICATION')) | |
{ | |
// New-style authentication | |
if(strlen($RequestData['auth_data']) >= 24 && strlen($RequestData['dummy_token']) == 44) | |
{ | |
$ClientKey = NULL; | |
// Decrypt client dummy_token | |
if(!openssl_private_decrypt(base64_decode($RequestData['dummy_token']), &$ClientKey, NPPS\Authentication\GetRSAPrivateKey())); | |
return new NPPS\ActionInvalidArgument('Failed to decrypt client key'); // "new" keyword is optional | |
// Actually we don't need auth_data, so just ignore it. | |
$ServerKey = random_bytes(32); // Generate random server key | |
$Token = NPPS\Token\Generate(); // Generate token | |
$NPPSDB->query('INSERT INTO `logged_in` (token, xmc_key) VALUES (?, ?)', 'sb', | |
$Token, | |
$ServerKey ^ $ClientKey // XOR it on-the-fly | |
); | |
// Return | |
return new NPPS\ActionResponse([ | |
'authorize_token' => $Token, | |
'dummy_token' => base64_encode($ServerKey) | |
]); | |
} | |
else | |
return new NPPS\ActionInvalidArgument('Invalid dummy_token or auth_data'); | |
} | |
else | |
{ | |
// Old-stype authentication | |
$Token = NPPS\Token\Generate(); // Generate token | |
$NPPSDB->query('INSERT INTO `logged_in` (token) VALUES (?)', 'sb', $Token); | |
// Return | |
return new NPPS\ActionResponse([ | |
'authorize_token' => $Token | |
]); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment