Skip to content

Commit

Permalink
fixed search
Browse files Browse the repository at this point in the history
  • Loading branch information
gaokevin1 committed Oct 28, 2024
1 parent a0f1ccc commit d5619aa
Show file tree
Hide file tree
Showing 19 changed files with 810 additions and 578 deletions.
4 changes: 2 additions & 2 deletions sample/callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
echo "Descope Project ID not present. Please check .env file.";
exit(1);
}

$descopeSDK = new DescopeSDK([
'projectId' => $_ENV['DESCOPE_PROJECT_ID']
]);
]);

if (isset($_POST["sessionToken"])) {
if ($descopeSDK->verify($_POST["sessionToken"])) {
Expand Down
11 changes: 0 additions & 11 deletions sample/dashboard.php
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
<?php
require '../vendor/autoload.php';
use Descope\SDK\DescopeSDK;

session_start();

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

// if (!isset($_ENV['DESCOPE_PROJECT_ID'])) {
// echo "Descope Project ID not present. Please check .env file.";
// exit(1);
// }

// $descopeSDK = new DescopeSDK([
// 'projectId' => $_ENV['DESCOPE_PROJECT_ID'],
// 'managementKey' => $_ENV['DESCOPE_MANAGEMENT_KEY']
// ]);

if (!isset($_SESSION["user"])) {
session_destroy();
header('Location: login.php');
Expand Down
6 changes: 6 additions & 0 deletions sample/login.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ function sendFormData(sessionToken, userDetails) {
return user;
}
async function handleLogout() {
}
async function handleLogin() {
try {
console.log("Attempting to refresh the session...");
Expand All @@ -57,6 +61,7 @@ function sendFormData(sessionToken, userDetails) {
sendFormData(sessionToken, user.data);
} catch (error) {
console.log("Error during login:", error);
sdk.logout();
window.location.href = 'login.php'; // Redirect to login on error
}
}
Expand All @@ -68,6 +73,7 @@ function sendFormData(sessionToken, userDetails) {
console.log("Valid refresh token found. Logging in...");
handleLogin();
} else {
sdk.logout();
console.log("No valid refresh token. Displaying login form.");
const container = document.getElementById("container")
container.innerHTML = '<descope-wc project-id="' + projectId + '" flow-id="sign-up-or-in"></descope-wc>';
Expand Down
119 changes: 91 additions & 28 deletions src/SDK/API.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class API
/**
* Constructor for API class.
*
* @param string $projectId
* @param string $projectId
* @param string|null $managementKey Management key for authentication.
*/
public function __construct(string $projectId, ?string $managementKey)
Expand Down Expand Up @@ -52,7 +52,7 @@ public function __construct(string $projectId, ?string $managementKey)
* This function ensures that empty arrays in the input data are
* converted to empty objects (stdClass) before being JSON encoded.
*
* @param mixed $data The data to transform, which can be an array or any other type.
* @param mixed $data The data to transform, which can be an array or any other type.
* @return mixed The transformed data with empty arrays replaced by empty objects.
*/
private function transformEmptyArraysToObjects($data)
Expand All @@ -76,9 +76,9 @@ private function transformEmptyArraysToObjects($data)
/**
* Requests JwtResponse from Descope APIs with the given body and auth token.
*
* @param string $uri URI endpoint.
* @param array $body Request body.
* @param bool $useManagementKey Whether to use the management key for authentication.
* @param string $uri URI endpoint.
* @param array $body Request body.
* @param bool $useManagementKey Whether to use the management key for authentication.
* @return array JWT response array.
* @throws AuthException|GuzzleException|\JsonException If the request fails.
*/
Expand Down Expand Up @@ -130,8 +130,8 @@ public function doPost(string $uri, array $body, ?bool $useManagementKey = false
/**
* Sends a GET request to the specified URI with an optional auth token.
*
* @param string $uri URI endpoint.
* @param bool $useManagementKey Whether to use the management key for authentication.
* @param string $uri URI endpoint.
* @param bool $useManagementKey Whether to use the management key for authentication.
* @return array JWT response array.
* @throws AuthException|GuzzleException|\JsonException If the request fails.
*/
Expand Down Expand Up @@ -175,12 +175,53 @@ public function doGet(string $uri, bool $useManagementKey, ?string $refreshToken
}
}

/**
* Sends a DELETE request to the specified URI with an auth token.
*
* @param string $uri URI endpoint.
* @return array JWT response array.
* @throws AuthException|GuzzleException|\JsonException If the request fails.
*/
public function doDelete(string $uri): array
{
$authToken = $this->getAuthToken(true);

try {
$response = $this->httpClient->delete(
$uri,
[
'headers' => $this->getHeaders($authToken),
]
);

// Ensure the response is an object with getBody method
if (!is_object($response) || !method_exists($response, 'getBody') || !method_exists($response, 'getHeader')) {
throw new AuthException(500, 'internal error', 'Invalid response from API');
}

// Read Body
$body = $response->getBody();
$body->rewind();
$contents = $body->getContents() ?? [];

return json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
} catch (RequestException $e) {
$statusCode = $e->getResponse() ? $e->getResponse()->getStatusCode() : 'N/A';
$responseBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'No response body';
echo "Error: HTTP Status Code: $statusCode, Response: $responseBody";
return [
'statusCode' => $statusCode,
'response' => $responseBody,
];
}
}

/**
* Generates a JWT response array with the given parameters.
*
* @param array $responseBody
* @param string|null $refreshToken Refresh token.
* @param string|null $audience Audience.
* @param array $responseBody
* @param string|null $refreshToken Refresh token.
* @param string|null $audience Audience.
* @return array JWT response array.
*/
public function generateJwtResponse(array $responseBody, ?string $refreshToken = null, ?string $audience = null): array
Expand All @@ -196,7 +237,7 @@ public function generateJwtResponse(array $responseBody, ?string $refreshToken =
/**
* Generates headers for the HTTP request.
*
* @param string|null $authToken Authentication token.
* @param string|null $authToken Authentication token.
* @return array Headers array.
*/
private function getHeaders(string $authToken): array
Expand All @@ -214,7 +255,7 @@ private function getHeaders(string $authToken): array
/**
* Constructs the auth token based on whether the management key is used.
*
* @param bool $useManagementKey Whether to use the management key for authentication.
* @param bool $useManagementKey Whether to use the management key for authentication.
* @return string The constructed auth token.
*/
private function getAuthToken(bool $useManagementKey, ?string $refreshToken = null): string
Expand All @@ -230,27 +271,39 @@ private function getAuthToken(bool $useManagementKey, ?string $refreshToken = nu
return $this->projectId;
}

/**
* Generates authentication information from the response body.
*
* This method processes the response body to extract JWTs, session data,
* and cookie settings, and adjusts properties based on the token type.
*
* @param array $responseBody The API response body containing JWTs and user data.
* @param string|null $refreshToken Optional refresh token.
* @param bool $userJwt Indicates if user-related JWT information should be processed.
* @param string|null $audience Optional audience identifier.
* @return array The structured JWT response array containing session and user data.
*/
private function generateAuthInfo(array $responseBody, ?string $refreshToken, bool $userJwt, ?string $audience): array
{
$jwtResponse = [];
$stJwt = $responseBody['sessionJwt'] ?? '';

if ($stJwt) {
$jwtResponse[EndpointsV1::SESSION_TOKEN_NAME] = $stJwt;
$jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME] = $stJwt;
}

$rtJwt = $responseBody['refreshJwt'] ?? '';

if ($refreshToken) {
$jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME] = $refreshToken;
$jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME] = $refreshToken;
} elseif ($rtJwt) {
$jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME] = $rtJwt;
$jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME] = $rtJwt;
}

$jwtResponse = $this->adjustProperties($jwtResponse, $userJwt);

if ($userJwt) {
$jwtResponse[EndpointsV1::COOKIE_DATA_NAME] = [
$jwtResponse[EndpointsV1::$COOKIE_DATA_NAME] = [
'exp' => $responseBody['cookieExpiration'] ?? 0,
'maxAge' => $responseBody['cookieMaxAge'] ?? 0,
'domain' => $responseBody['cookieDomain'] ?? '',
Expand All @@ -261,31 +314,41 @@ private function generateAuthInfo(array $responseBody, ?string $refreshToken, bo
return $jwtResponse;
}

/**
* Adjusts properties of the JWT response array.
*
* This method sets permissions, roles, and tenant data from the JWT
* and processes the issuer and subject values to extract project and user IDs.
*
* @param array $jwtResponse The JWT response array to adjust.
* @param bool $userJwt Indicates if user-related JWT information should be processed.
* @return array The adjusted JWT response array with updated properties.
*/
private function adjustProperties(array $jwtResponse, bool $userJwt): array
{
if (isset($jwtResponse[EndpointsV1::SESSION_TOKEN_NAME])) {
$jwtResponse['permissions'] = $jwtResponse[EndpointsV1::SESSION_TOKEN_NAME]['permissions'] ?? [];
$jwtResponse['roles'] = $jwtResponse[EndpointsV1::SESSION_TOKEN_NAME]['roles'] ?? [];
$jwtResponse['tenants'] = $jwtResponse[EndpointsV1::SESSION_TOKEN_NAME]['tenants'] ?? [];
} elseif (isset($jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME])) {
$jwtResponse['permissions'] = $jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME]['permissions'] ?? [];
$jwtResponse['roles'] = $jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME]['roles'] ?? [];
$jwtResponse['tenants'] = $jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME]['tenants'] ?? [];
if (isset($jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME])) {
$jwtResponse['permissions'] = $jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME]['permissions'] ?? [];
$jwtResponse['roles'] = $jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME]['roles'] ?? [];
$jwtResponse['tenants'] = $jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME]['tenants'] ?? [];
} elseif (isset($jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME])) {
$jwtResponse['permissions'] = $jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME]['permissions'] ?? [];
$jwtResponse['roles'] = $jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME]['roles'] ?? [];
$jwtResponse['tenants'] = $jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME]['tenants'] ?? [];
} else {
$jwtResponse['permissions'] = $jwtResponse['permissions'] ?? [];
$jwtResponse['roles'] = $jwtResponse['roles'] ?? [];
$jwtResponse['tenants'] = $jwtResponse['tenants'] ?? [];
}

$issuer = $jwtResponse[EndpointsV1::SESSION_TOKEN_NAME]['iss'] ??
$jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME]['iss'] ??
$issuer = $jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME]['iss'] ??
$jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME]['iss'] ??
$jwtResponse['iss'] ?? '';

$issuerParts = explode("/", $issuer);
$jwtResponse['projectId'] = end($issuerParts);

$sub = $jwtResponse[EndpointsV1::SESSION_TOKEN_NAME]['sub'] ??
$jwtResponse[EndpointsV1::REFRESH_TOKEN_NAME]['sub'] ??
$sub = $jwtResponse[EndpointsV1::$SESSION_TOKEN_NAME]['sub'] ??
$jwtResponse[EndpointsV1::$REFRESH_TOKEN_NAME]['sub'] ??
$jwtResponse['sub'] ?? '';

if ($userJwt) {
Expand Down
4 changes: 4 additions & 0 deletions src/SDK/EndpointsV1.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
const SESSION_TOKEN = "sessionToken";
const REFRESH_TOKEN = "refreshSessionToken";

const COOKIE_DATA = "cookieData";

const REDIRECT_LOCATION_NAME = "Location";

const PHONE_REGEX = '/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?){0,}((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/';
Expand All @@ -29,6 +31,8 @@ class EndpointsV1
public static $SESSION_TOKEN_NAME = SESSION_TOKEN;
public static $REFRESH_TOKEN_NAME = REFRESH_TOKEN;

public static $COOKIE_DATA_NAME = COOKIE_DATA;

public static $REDIRECT_LOCATION_COOKIE_NAME = REDIRECT_LOCATION_NAME;

public static $REFRESH_TOKEN_PATH;
Expand Down
13 changes: 2 additions & 11 deletions src/SDK/Management/AssociatedTenant.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,17 @@ class AssociatedTenant
*/
public $roleNames = [];

/**
* Represents the role IDs for a user in the Tenant.
*
* @var array<string> The Role IDs.
*/
public $roleIds = [];

/**
* Constructor for the AssociatedTenant class.
*
* @param string $tenantId The Tenant ID.
* @param array<string> $roleNames The role names for the user in the tenant.
* @param array<string> $roleIds The role IDs for the user in the tenant.
*/
public function __construct(string $tenantId, array $roleNames = [], array $roleIds = [])
public function __construct(string $tenantId, array $roleNames = [])
{
$this->tenantId = $tenantId;
$this->roleNames = $roleNames;
$this->roleIds = $roleIds;
}

/**
Expand All @@ -49,8 +41,7 @@ public function toArray(): array
{
return [
'tenantId' => $this->tenantId,
'roleNames' => $this->roleNames,
'roleIds' => $this->roleIds,
'roleNames' => $this->roleNames
];
}
}
12 changes: 12 additions & 0 deletions src/SDK/Management/Management.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class Management
* @var User The User management component.
*/
public User $user;
public Audit $audit;

/**
* Constructor for Management class.
Expand All @@ -25,6 +26,7 @@ class Management
public function __construct(API $auth)
{
$this->user = new User($auth);
$this->audit = new Audit($auth);
}

/**
Expand All @@ -36,4 +38,14 @@ public function user(): User
{
return $this->user;
}

/**
* Get the Audit Management component.
*
* @return Audit The Audit management instance.
*/
public function audit(): Audit
{
return $this->audit;
}
}
7 changes: 6 additions & 1 deletion src/SDK/Management/MgmtV1.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

use Descope\SDK\EndpointsV1;


const DEFAULT_URL_PREFIX = "https://api";
const DEFAULT_DOMAIN = "descope.com";

Expand Down Expand Up @@ -96,6 +95,8 @@ class MgmtV1
public static string $TENANT_DELETE_PATH;
public static string $TENANT_UPDATE_PATH;
public static string $TENANT_CREATE_PATH;
public static string $AUDIT_SEARCH;
public static string $AUDIT_CREATE_EVENT;

/**
* Sets the base URL based on the project ID, taking into account the region.
Expand Down Expand Up @@ -232,6 +233,10 @@ private static function updatePaths(): void
self::$FLOW_EXPORT_PATH = self::$baseUrl . "/v1/mgmt/flow/export";
self::$TEMPLATE_IMPORT_PATH = self::$baseUrl . "/v1/mgmt/template/import";
self::$TEMPLATE_EXPORT_PATH = self::$baseUrl . "/v1/mgmt/template/export";

// Audit
self::$AUDIT_SEARCH = self::$baseUrl . "/v1/mgmt/audit/search";
self::$AUDIT_CREATE_EVENT = self::$baseUrl . "/v1/mgmt/audit/event";
}
}

Expand Down
Loading

0 comments on commit d5619aa

Please sign in to comment.