Skip to content
Snippets Groups Projects
Commit f0dcb79c authored by lukasmatusiewicz's avatar lukasmatusiewicz
Browse files

initial commit

parent 320618e9
Branches
Tags
No related merge requests found
##This is the privacyIDEA-PHP-SDK.
This library will help you to connect your plugin to the privacyIDEA server using REST APIs.
##Requirements
To use our API library you have to install curl on your machine or add curl/curl using Composer.
To do it with Composer simply copy that line to your terminal in your project directory:
`composer require curl/curl`
Remember that you have to install composer first. If you will know how to do it, check this documentation:
https://getcomposer.org/doc/00-intro.md
##
\ No newline at end of file
{
"name": "privacyidea/privacyidea-php-sdk",
"description": "This is the privacyIDEA-PHP-SDK. The library that will help you to connect your plugin to the privacyIDEA server using REST APIs.",
"minimum-stability": "stable",
"authors": [
{
"name": "Lukas Matusiewicz",
"email": "lukas.matusiewicz@netknights.it"
}
],
"repositories": [
{
"type": "git",
"url": "https://github.com/lukasmatusiewicz/privacyidea-php-sdk"
}
],
"require": {
"php": ">=7.4",
"phpunit/phpunit": "^9.5",
"internations/http-mock": "^0.14.0",
"curl/curl": ">=2.0.0"
}
}
<?php
class PIChallenge
{
/**
* @var string Token's type.
*/
public $type = "";
/**
* @var string Message from single challenge.
*/
public $message = "";
/**
* @var string
*/
public $transaction_id = "";
/**
* @var string Token's serial.
*/
public $serial = "";
/**
* @var string
*/
public $attributes = "";
}
\ No newline at end of file
<?php
/**
* Interface PILog
* Call the functions that collect debug and error messages
*/
interface PILog
{
public function pi_debug($message);
public function pi_error($message);
}
\ No newline at end of file
<?php
require_once 'SDK-Autoloader.php';
class PIResponse
{
/**
* @var string All tokens messages which are sended by PI and can be used in UI to help user interact with service.
*/
public $messages = "";
/**
* @var string Transaction ID which is needed by some PI API requests.
*/
public $transaction_id = "";
/**
* @var string This is the raw PI response in JSON format.
*/
public $raw = "";
/**
* @var array Here are all triggered challenges delivered as object of PIChallenge class.
*/
public $multi_challenge = array();
/**
* @var bool The status indicates if the request was processed correctly by the server.
*/
public $status = false;
/**
* @var bool The value tell us if authentication was successfull.
*/
public $value = false;
/**
* @var array All interessing details about user which can be shown in the UI at the end of the authentication.
*/
public $detailAndAttributes = array();
/**
* @var string PI error messages with error codes will be delivered here.
*/
public $error;
/**
* Prepare a good readable PI response and return it as an object
* @param $json
* @param \PrivacyIDEA $privacyIDEA
* @return \PIResponse|null
*/
public static function fromJSON($json, PrivacyIDEA $privacyIDEA) // No mixed type declaration possible here
{
if ($json == null || $json == "") {
$privacyIDEA->errorLog("PrivacyIDEA - PIResponse: No response from PI.");
return null;
}
// Build an PIResponse object and decode the response from JSON to PHP
$ret = new PIResponse();
$map = json_decode($json, true);
// If wrong response format - throw error
if ($map == null) {
$privacyIDEA->errorLog("PrivacyIDEA - PIResponse: Response from PI was in wrong format. JSON expected.");
return null;
}
// Prepare raw JSON Response if needed
$ret->raw = $json;
// Possibility to show an error if no value
if (!isset($map['result']['value'])) {
$ret->error = $map['result']['error']['message'];
return $ret;
}
// Set information from PI response to property
if (isset($map['detail']['messages'])) {
$ret->messages = implode(", ", array_unique($map['detail']['messages'])) ?: "";
}
if (isset($map['detail']['transaction_id'])) {
$ret->transaction_id = $map['detail']['transaction_id'];
}
$ret->status = $map['result']['status'] ?: false;
$ret->value = $map['result']['value'] ?: false;
// Prepare attributes and detail
if (!empty($map['detail']['user'])) {
$attributes = $map['detail']['user'];
$detail = $map['detail'];
if (isset($attributes['username'])) {
$attributes['realm'] = $map['detail']['user-realm'] ?: "";
$attributes['resolver'] = $map['detail']['user-resolver'] ?: "";
}
$ret->detailAndAttributes = array("detail" => $detail, "attributes" => $attributes);
}
// Set all challenges to objects and set it all to one array
if (isset($map['detail']['multi_challenge'])) {
$mc = $map['detail']['multi_challenge'];
foreach ($mc as $challenge) {
$tmp = new PIChallenge();
$tmp->transaction_id = $challenge['transaction_id'];
$tmp->message = $challenge['message'];
$tmp->serial = $challenge['serial'];
$tmp->type = $challenge['type'];
$tmp->attributes = $challenge['attributes'];
array_push($ret->multi_challenge, $tmp);
}
}
return $ret;
}
/**
* Get array with all triggered token types
* @return array
*/
public function triggeredTokenTypes(): array
{
$ret = array();
foreach ($this->multi_challenge as $challenge) {
array_push($ret, $challenge->type);
}
return array_unique($ret);
}
/**
* Get OTP message if OTP token(s) triggered
* @return array
*/
public function otpMessage(): array
{
$ret = array();
foreach ($this->multi_challenge as $challenge) {
if ($challenge['type'] !== "push" || $challenge['type'] !== "webauthn") {
array_push($ret, $challenge['message']);
}
}
return array_unique($ret);
}
/**
* Get push message if push token triggered
* @return string
*/
public function pushMessage(): string
{
foreach ($this->multi_challenge as $challenge) {
if ($challenge['type'] === "push") {
return $challenge['message'];
}
}
return false;
}
/**
* Check if push token is available
* @return bool
*/
public function pushAvailability(): bool
{
foreach ($this->multi_challenge as $challenge) {
if ($challenge['type'] === "push") {
return true;
}
}
return false;
}
}
\ No newline at end of file
<?php
/**
* All the API requests which you need are already done and set to methods in this class.
* All you have to do is include the SDK-Autoloader to your PHP file
* and call the methods adding the needed parameters.
*
* @author Lukas Matusiewicz <lukas.matusiewicz@netknights.it>
*/
require_once('SDK-Autoloader.php');
class PrivacyIDEA
{
/**
* @var string Plugins name which must to be verified in privacyIDEA.
*/
public $userAgent = "";
/**
* @var string This is the URL to your privacyIDEA server.
*/
public $serverURL = "";
/**
* @var string Here is realm of users account.
*/
public $realm = "";
/**
* @var bool You can decide if you want to verify your ssl certificate.
*/
public $sslVerifyHost = true;
/**
* @var bool You can decide if you want to verify your ssl certificate.
*/
public $sslVerifyPeer = true;
/**
* @var string Username to your service account. You need it to get auth token which is needed by some PI API requests.
*/
public $serviceAccountName = "";
/**
* @var string Password to your service account. You need it to get auth token which is needed by some PI API requests.
*/
public $serviceAccountPass = "";
/**
* @var string If needed you can add it too.
*/
public $serviceAccountRealm = "";
/**
* @var bool You can disable the log function by setting this variable to true.
*/
public $disableLog = false;
/**
* @var object This object will deliver PI debug and error messages to your plugin so you can log it wherever you want.
*/
public $logger = null;
/**
* PrivacyIDEA constructor.
* @param $userAgent string the user agent that should set in the http header
* @param $serverURL string the url of the privacyIDEA server
*/
public function __construct($userAgent, $serverURL)
{
$this->userAgent = $userAgent;
$this->serverURL = $serverURL;
}
/**
* This function collect the debug messages and send it to PILog.php
* @param $message
*/
function debugLog($message)
{
if (!$this->disableLog && $this->logger != null) {
$this->logger->pi_debug($message);
}
}
/**
* This function collect the error messages and send it to PILog.php
* @param $message
*/
function errorLog($message)
{
if (!$this->disableLog && $this->logger != null) {
$this->logger->pi_error($message);
}
}
/**
* Handle validateCheck using user's username, password and if challenge response - transaction_id.
*
* @param $params array 'user' and 'pass' keys are required and optionally 'realm' if set.
* @param null $transaction_id optional transaction id. Used to reference a challenge that was triggered beforehand.
* @return \PIResponse|null This method returns an PIResponse object which contains all the useful information from the PI server. In case of error returns null.
*/
public function validateCheck($params, $transaction_id = null)
{
//Check if parameters are set
if (!empty($params['user']) || !empty($params['pass'])) {
if ($transaction_id) {
//Add transaction ID in case of challenge response
$params["transaction_id"] = $transaction_id;
}
if ($this->realm) {
$params["realm"] = $this->realm;
}
//Call send_request function to handle an API Request using $parameters and return it.
$response = $this->sendRequest($params, array(''), 'POST', '/validate/check');
//Return the response from /validate/check as PIResponse object
$ret = PIResponse::fromJSON($response, $this);
if ($ret == null) {
$this->debugLog("privacyIDEA - Validate Check: no response from PI-server");
}
return $ret;
} else {
//Handle error if $username is empty
$this->debugLog("privacyIDEA - Validate Check: params incomplete!");
}
return null;
}
/**
* Trigger all challenges for the given username.
* This function requires a service account to be set.
*
* @param $username
* @return \PIResponse|null This method returns an PIResponse object which contains all the useful information from the PI server.
*/
public function triggerChallenge($username)
{
if ($username) {
$authToken = $this->getAuthToken();
// Set header to: "'authorization' : auth token" and set username as parameter
$header = array("authorization:" . $authToken);
$parameter = array("user" => $username);
//Call /validate/triggerchallenge with username as paramter and return it.
$response = $this->sendRequest($parameter, $header, 'POST', '/validate/triggerchallenge');
//Return the response from /validate/triggerchallenge as PIResponse object
$ret = PIResponse::fromJSON($response, $this);
if ($ret == null) {
$this->debugLog("privacyIDEA - Trigger Challenge: no response from PI-server");
}
return $ret;
} else {
//Handle error if empty $username
$this->debugLog("privacyIDEA - Trigger Challenge: no username");
}
return null;
}
/**
* Call /validate/polltransaction using transaction_id
*
* @param $transaction_id string An unique ID which is needed by some API requests.
* @return bool Returns true if PUSH is accepted, false otherwise.
*/
public function pollTransaction($transaction_id): bool
{
if (!empty($transaction_id)) {
$params = array("transaction_id" => $transaction_id);
// Call /validate/polltransaction using transaction_id and decode it from JSON
$responseJSON = $this->sendRequest($params, array(''), 'GET', '/validate/polltransaction');
$response = json_decode($responseJSON, true);
//Return the response from /validate/polltransaction
return $response['result']['value'];
} else {
//Handle error if $transaction_id is empty
$this->debugLog("privacyIDEA - Poll Transaction: No transaction_id");
}
return false;
}
/**
* Check if user already has token
* Enroll a new token
*
* @param $params array as parameters you need to set: user, genkey, type, description.
* @return mixed
*/
public function enrollToken($params) // No return type because mixed not allowed yet
{
// Check if parameters contain the required keys
if (empty($params["user"]) ||
empty($params["genkey"]) ||
empty($params["type"])) {
$this->debugLog("privacyIDEA - Enroll Token: Token enrollment not possible because params are not complete");
return array();
}
$authToken = $this->getAuthToken();
// Set header to: "'authorization' : auth token"
$header = array("authorization:" . $authToken);
// Check if user has token
$tokenInfo = json_decode($this->sendRequest(array("user" => $params['user']), $header, 'GET', '/token/'));
if (!empty($tokenInfo->result->value->tokens)) {
$this->debugLog("privacyIDEA - Enroll Token: User already has a token. No need to enroll a new one.");
return array();
} else {
// Call /token/init endpoint and return the PI response
return json_decode($this->sendRequest($params, $header, 'POST', '/token/init'));
}
}
/**
* Retrieves an auth token from the server using the service account. The auth token is required to make certain requests to privacyIDEA.
* If no service account is set or an error occured, this function returns false.
*
* @return string|bool the auth token or false.
*/
public function getAuthToken()
{
// Check if service account is available
if (empty($this->serviceAccountName) || empty($this->serviceAccountPass)) {
return false;
}
// To get auth token from server use API Request: /auth with added service account and service pass
$params = array(
"username" => $this->serviceAccountName,
"password" => $this->serviceAccountPass
);
if ($this->serviceAccountRealm != null && $this->serviceAccountRealm != "") {
$params["realm"] = $this->serviceAccountRealm;
}
// Call /auth endpoint and decode the response from JSON to PHP
$response = json_decode($this->sendRequest($params, array(''), 'POST', '/auth'), true);
if ($response) {
// Get auth token from response->result->value->token and return the token
return $response['result']['value']['token'];
}
// If no response return false
$this->debugLog("privacyIDEA - getAuthToken: No response from PI-Server");
return false;
}
/**
* Prepare send_request and make curl_init.
*
* @param $params array request parameters in an array
* @param $headers array headers fields in array
* @param $http_method string
* @param $endpoint string endpoint of the privacyIDEA API (e.g. /validate/check)
* @return string returns string with response from server or an empty string if error occurs
*/
public function sendRequest($params, $headers, $http_method, $endpoint): string
{
assert('array' === gettype($params));
assert('array' === gettype($headers));
assert('string' === gettype($http_method));
assert('string' === gettype($endpoint));
$curl_instance = curl_init();
// Compose an API Request using privacyIDEA's URL from config and endpoint created in function
$completeUrl = $this->serverURL . $endpoint;
curl_setopt($curl_instance, CURLOPT_URL, $completeUrl);
curl_setopt($curl_instance, CURLOPT_HEADER, true);
if ($headers) {
curl_setopt($curl_instance, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl_instance, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_instance, CURLOPT_USERAGENT, $this->userAgent);
if ($http_method === "POST") {
curl_setopt($curl_instance, CURLOPT_POST, true);
curl_setopt($curl_instance, CURLOPT_POSTFIELDS, $params);
} elseif ($http_method === "GET") {
$params_str = '?';
if (!empty($params)) {
foreach ($params as $key => $value) {
$params_str .= $key . "=" . $value . "&";
}
}
curl_setopt($curl_instance, CURLOPT_URL, $completeUrl . $params_str);
}
// Check if you schould to verify privacyIDEA's SSL certificate in your config
// If true - do it, if false - don't verify
if ($this->sslVerifyHost == false) {
curl_setopt($curl_instance, CURLOPT_SSL_VERIFYHOST, 0);
} else {
curl_setopt($curl_instance, CURLOPT_SSL_VERIFYHOST, 2);
}
if ($this->sslVerifyPeer == false) {
curl_setopt($curl_instance, CURLOPT_SSL_VERIFYPEER, 0);
} else {
curl_setopt($curl_instance, CURLOPT_SSL_VERIFYPEER, 2);
}
//Store response in the variable
$response = curl_exec($curl_instance);
if (!$response) {
//Handle error if no response and return an empty string
$this->errorLog("privacyIDEA-SDK: Bad request to PI server. " . curl_error($curl_instance));
return '';
}
$header_size = curl_getinfo($curl_instance, CURLINFO_HEADER_SIZE);
curl_close($curl_instance);
//Return decoded response from API Request
return substr($response, $header_size);
}
}
\ No newline at end of file
<?php
/**
* Include all files you need to authenticate against privacyIDEA
* All that files are placed in privacyIDEA-PHP-SDK direction
*/
spl_autoload_register('autoLoader');
function autoLoader($className): bool
{
$fullPath=dirname(__FILE__) ."/". $className . ".php";
if(file_exists($fullPath)){
require_once $fullPath;
return true;
}else{
return false;
}
}
\ No newline at end of file
<?php
declare(strict_types=1);
require_once('../../src/privacyidea-php-sdk/SDK-Autoloader.php');
require_once('../../vendor/autoload.php');
use PHPUnit\Framework\TestCase;
use InterNations\Component\HttpMock\PHPUnit\HttpMockTrait;
class PrivacyIDEATest extends TestCase
{
private PrivacyIDEA $pi;
use HttpMockTrait;
public static function setUpBeforeClass(): void
{
static::setUpHttpMockBeforeClass('8082', 'localhost');
}
public static function tearDownAfterClass(): void
{
static::tearDownHttpMockAfterClass();
}
public function setUp(): void
{
$this->setUpHttpMock();
$this->pi = new PrivacyIDEA('testUserAgent', "http://127.0.0.1:8082");
$this->pi->disableLog = true;
}
public function tearDown(): void
{
$this->tearDownHttpMock();
}
public function testValidateCheck()
{
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/validate/check')
->then()
->body(null)
->end();
$this->http->setUp();
$response = $this->pi->validateCheck(['user' => 'testUser', 'pass' => 'testPass'], "1234567890");
$this->assertNull($response, "Response is not NULL.");
$respValidateCheck = '{
"detail": {
"attributes": null,
"message": "Please enter OTP: ",
"messages": [
"Please enter OTP: "
],
"multi_challenge": [
{
"attributes": null,
"message": "Please enter OTP: ",
"serial": "OATH00016327",
"transaction_id": "10254108800156191660",
"type": "hotp"
}
],
"serial": "OATH00016327",
"threadid": 139868461995776,
"transaction_id": "10254108800156191660",
"transaction_ids": [
"10254108800156191660"
],
"type": "hotp"
},
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": false
},
"version": "privacyIDEA 3.5.2",
"versionnumber": "3.5.2",
"signature": "rsa_sha256_pss:12345"
}';
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/validate/check')
->then()
->body($respValidateCheck)
->end();
$this->http->setUp();
$this->pi->sslVerifyHost = false;
$this->pi->sslVerifyPeer = false;
$response = $this->pi->validateCheck(array());
$this->assertNull($response, "No user or pass added to params.");
$this->pi->realm = "testRealm";
$response = $this->pi->validateCheck(['user' => 'testUser', 'pass' => 'testPass'], "1234567890");
$this->assertNotNull($response, "Response is NULL.");
$this->assertEquals('Please enter OTP: ', $response->messages, "Message did not match.");
$this->assertEquals("10254108800156191660", $response->transaction_id, "Transaction id did not match.");
$this->assertEquals($respValidateCheck, $response->raw, "Cannot to get the raw response in JSON format!");
$this->assertTrue($response->status, "Status is not true as expected.");
$this->assertFalse($response->value, "Value is not false as expected.");
$this->assertEmpty($response->detailAndAttributes, "detailAndAttributes is not empty as expected.");
$this->assertNull($response->error, "Error is not null as expected.");
$this->assertEquals("10254108800156191660", $response->multi_challenge[0]->transaction_id, "Transaction id did not match.");
$this->assertEquals("Please enter OTP: ", $response->multi_challenge[0]->message, "Message did not match.");
$this->assertEquals("OATH00016327", $response->multi_challenge[0]->serial, "Serial did not match.");
$this->assertEquals("hotp", $response->multi_challenge[0]->type, "Type did not match.");
$this->assertNull($response->multi_challenge[0]->attributes, "attributes did not match.");
}
public function testTriggerChallenge()
{
$respAuthToken = '{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"token": "eyJhbGciOiJIUz....jdpn9kIjuGRnGejmbFbM"
}
},
"version": "privacyIDEA unknown"
}';
$respTriggerChallenge = '{
"detail":{
"attributes":null,
"messages":[
"Please confirm the authentication on your mobile device!"
],
"multi_challenge":[
{
"attributes":null,
"message":"please enter otp: ",
"serial":"OATH00016327",
"transaction_id":"08282050332563531714",
"type":"hotp"
}
],
"serial":"TOTP0002A944",
"transaction_id":"08282050332563531714",
"type":"totp"
},
"result":{
"status":true,
"value":1
},
"version":"privacyIDEA 3.5.2",
"versionnumber":"3.5.2",
"signature":"rsa_sha256_pss:12345"
}';
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/auth')
->then()
->body($respAuthToken)
->end();
$this->http->setUp();
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/validate/triggerchallenge')
->then()
->body(null)
->end();
$this->http->setUp();
$response = $this->pi->triggerChallenge("testUser");
$this->assertNull($response, "Response is not NULL.");
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/validate/triggerchallenge')
->then()
->body($respTriggerChallenge)
->end();
$this->http->setUp();
$response = $this->pi->triggerChallenge("");
$this->assertNull($response, "Response not NULL even if the username not given.");
$response = $this->pi->triggerChallenge("testUser");
$this->assertNotNull($response, "Response is NULL.");
$this->assertEquals("Please confirm the authentication on your mobile device!", $response->messages, "Message did not match.");
$this->assertEquals("08282050332563531714", $response->transaction_id, "Transaction id did not match.");
$this->assertEquals($respTriggerChallenge, $response->raw, "Cannot to get the raw response in JSON format!");
$this->assertTrue($response->status, "Status is not true as expected.");
$this->assertEquals("1", $response->value, "Value is not false as expected.");
$this->assertEmpty($response->detailAndAttributes, "detailAndAttributes is not empty as expected.");
$this->assertNull($response->error, "Error is not null as expected.");
$this->assertEquals("08282050332563531714", $response->multi_challenge[0]->transaction_id, "Transaction id did not match.");
$this->assertEquals("please enter otp: ", $response->multi_challenge[0]->message, "Message did not match.");
$this->assertEquals("OATH00016327", $response->multi_challenge[0]->serial, "Serial did not match.");
$this->assertEquals("hotp", $response->multi_challenge[0]->type, "Type did not match.");
$this->assertNull($response->multi_challenge[0]->attributes, "attributes did not match.");
}
public function testPollTransaction()
{
$respPolling = '{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": true
},
"version": "privacyIDEA 3.5.2",
"versionnumber": "3.5.2",
"signature": "rsa_sha256_pss:12345"
}';
$this->http->mock
->when()
->methodIs('GET')
->pathIs('/validate/polltransaction')
->then()
->body($respPolling)
->end();
$this->http->setUp();
$response = $this->pi->pollTransaction("");
$this->assertNotNull($response, "Response is not NULL without transaction_id given.");
$response = $this->pi->pollTransaction("1234567890");
$this->assertNotNull($response, "Response is NULL.");
$this->assertTrue($response, "Value is not true as expected.");
}
public function testEnrollToken()
{
// Test case if user already have a token
$respAuthToken = '{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"token": "eyJhbGciOiJIUz....jdpn9kIjuGRnGejmbFbM"
}
},
"version": "privacyIDEA unknown"
}';
$respTokenInfo = '{
"id":1,
"jsonrpc":"2.0",
"result":{
"status":true,
"value":{
"count":3,
"current":1,
"tokens":[
{
"active":true,
"count":37,
"info":{
"count_auth":"126",
"tokenkind":"software"
},
"locked":false,
"realms":[
"testRealm"
],
"resolver":"testResolver",
"revoked":false
}
]
}
},
"version":"privacyIDEA 3.5.2",
"versionnumber":"3.5.2",
"signature":"rsa_sha256_pss:12345"
}';
$respTokenInit = '{
"detail":{
"googleurl":{
"description":"URL for google Authenticator",
"img":"data:image/png;base64,iVBORw0",
"value":"otpauth://totp/TOTP0002A944?secret=Y5D5IM4H274ZI6NRO347QGQ4NPTIOHKL&period=30&digits=6&issuer=privacyIDEA"
},
"oathurl":{
"description":"URL for OATH token",
"img":"data:image/png;base64,iVBORw0",
"value":"oathtoken:///addToken?name=TOTP0002A944&lockdown=true&key=c747d43387d7f99479b176f9f81a1c6be6871d4b&timeBased=true"
},
"otpkey":{
"description":"OTP seed",
"img":"data:image/png;base64,iVBORw0",
"value":"seed://c747d43387d7f99479b176f9f81a1c6be6871d4b",
"value_b32":"Y5D5IM4H274ZI6NRO347QGQ4NPTIOHKL"
},
"rollout_state":"",
"serial":"TOTP0002A944",
"threadid":140286414018304
},
"id":1,
"jsonrpc":"2.0",
"result":{
"status":true,
"value":true
},
"version":"privacyIDEA 3.5.2",
"versionnumber":"3.5.2",
"signature":"rsa_sha256_pss:12345"
}';
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/auth')
->then()
->body($respAuthToken)
->end();
$this->http->setUp();
$this->http->mock
->when()
->methodIs('GET')
->pathIs('/token/')
->then()
->body($respTokenInfo)
->end();
$this->http->setUp();
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/token/init')
->then()
->body($respTokenInit)
->end();
$this->http->setUp();
$response = $this->pi->enrollToken([
"user" => "testUser",
"genkey" => "1",
"type" => "totp",
"description" => "Enrolled for Test"]);
$this->assertNotNull($response, "Response is NULL.");
$this->assertEmpty($response);
// Test case if user have no token and we should enroll a new one
$respTokenInfo = '{
"id":1,
"jsonrpc":"2.0",
"result":{
"status":true,
"value":{
"count":3,
"current":1,
"tokens":[]
}
},
"version":"privacyIDEA 3.5.2",
"versionnumber":"3.5.2",
"signature":"rsa_sha256_pss:12345"
}';
$this->http->mock
->when()
->methodIs('GET')
->pathIs('/token/')
->then()
->body($respTokenInfo)
->end();
$this->http->setUp();
$response = $this->pi->enrollToken([
"user" => "",
"genkey" => "1",
"type" => "totp",
"description" => "Enrolled for Test"]);
$this->assertEmpty($response, "Without user given enrollToken() should return an empty array.");
$response = $this->pi->enrollToken([
"user" => "testUser",
"genkey" => "",
"type" => "totp"]);
$this->assertEmpty($response, "Without genkey given enrollToken() should return an empty array.");
$response = $this->pi->enrollToken([
"user" => "testUser",
"genkey" => "1",
"type" => ""]);
$this->assertEmpty($response, "Without type given enrollToken() should return an empty array.");
$response = $this->pi->enrollToken([
"user" => "testUser",
"genkey" => "1",
"type" => "totp",
"description" => "Enrolled for Test"]);
$this->assertNotNull($response, "Response is NULL.");
$this->assertIsObject($response);
$this->assertObjectHasAttribute('detail', $response, "Object have no detail attribute.");
$this->assertEquals("data:image/png;base64,iVBORw0", $response->detail->googleurl->img, "Object have no image data.");
}
public function testGetAuthToken()
{
$respAuthToken = '{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"token": "eyJhbGciOiJIUz....jdpn9kIjuGRnGejmbFbM"
}
},
"version": "privacyIDEA unknown"
}';
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/auth')
->then()
->body($respAuthToken)
->end();
$this->http->setUp();
$response = $this->pi->getAuthToken();
$this->assertFalse($response, "Response is not false.");
$this->pi->serviceAccountPass = "testPass";
$this->pi->serviceAccountName = "testAdmin";
$this->pi->serviceAccountRealm = "testRealm";
$response = $this->pi->getAuthToken();
$this->assertEquals('eyJhbGciOiJIUz....jdpn9kIjuGRnGejmbFbM', $response, "Auth token did not match.");
$this->http->mock
->when()
->methodIs('POST')
->pathIs('/auth')
->then()
->end();
$this->http->setUp();
$response = $this->pi->getAuthToken();
$this->assertFalse($response);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment