namespace MiniOrange\IDPSaml\Controller\Actions;
use Magento\Framework\App\Action\Context;
use MiniOrange\IDPSaml\Helper\IDPUtility;
use MiniOrange\IDPSaml\Helper\IDPConstants;
use MiniOrange\IDPSaml\Helper\Data;
use MiniOrange\IDPSaml\Controller\Actions\PasswordGrant;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\DataObject;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Magento\Framework\App\Bootstrap;
use Magento\Customer\Model\Customer;
use Magento\Framework\App\Response\Http;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\App\ResponseFactory;
use MiniOrange\IDPSaml\Helper\Saml2\Lib\AESEncryption;
use Magento\Framework\Controller\ResultFactory;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Eav\Model\Entity\Attribute;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection;
use Magento\Customer\Model\AddressFactory;
class Token extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface
{
private $REQUEST;
private $POST;
private $passwordGrant;
protected $resultFactory;
private $customerSession;
private $customerFactory;
private $customerRepository;
protected $response;
private $customerCollectionFactory;
protected $customerAccountManagement;
protected $idpUtility;
protected $redirect_uri;
protected $attributeCollectionFactory;
protected $customerAttribute;
protected $customerModel;
protected $_addressFactory;
protected $tokenModelFactory;
public function __construct(Context $FF, IDPUtility $Ng, ResultFactory $Fb, Session $d9, CustomerFactory $o2, CustomerRepositoryInterface $ql, AccountManagementInterface $zU, Http $WG, CollectionFactory $Fn, ResponseFactory $Pd, Attribute $Mf, Customer $VZ, \Magento\Integration\Model\Oauth\TokenFactory $Iu, AddressFactory $uw)
{
$this->resultFactory = $Fb;
$this->customerSession = $d9;
$this->idpUtility = $Ng;
$this->customerFactory = $o2;
$this->customerRepository = $ql;
$this->response = $WG;
$this->customerCollectionFactory = $Fn;
$this->customerAccountManagement = $zU;
$this->customerAttribute = $Mf;
$this->customerModel = $VZ;
$this->_addressFactory = $uw;
$this->tokenModelFactory = $Iu;
parent::__construct($FF);
}
public function execute()
{
$this->idpUtility->log_debug("Token: started");
if ($this->idpUtility->check_plan(2)) {
goto Gx;
}
$this->idpUtility->checkIfValidLicense();
goto OM;
Gx:
$this->idpUtility->checkTrialExpiry();
OM:
$lw = $this->getRequest()->getParams();
$this->idpUtility->log_debug("params in Token.php :", $lw);
$Kb = $this->idpUtility->getMiniOrangeOAuthClients();
$sG = $lw["grant_type"];
foreach ($Kb as $av) {
if (!(isset($lw["redirect_uri"]) && $av->getData()[IDPConstants::REDIRECT_URL] === $lw["redirect_uri"] || isset($lw["client_id"]) && $av->getData()[IDPConstants::CLIENT_ID] === $lw["client_id"])) {
goto NT;
}
$AG = $av->getData();
NT:
ea:
}
VW:
foreach (getallheaders() as $uM => $TC) {
$this->idpUtility->log_debug("data received in header: " . $uM . " value: " . $TC);
if (!($uM == "Authorization" && !empty($TC))) {
goto HI;
}
$TC = ltrim(substr($TC, 5));
$TC = base64_decode($TC);
$this->idpUtility->log_debug("base64 decoded value: " . $TC);
$Ii = explode(":", $TC);
$Wm = $Ii[0];
$Q_ = $Ii[1];
foreach ($Kb as $av) {
if (!($av->getData()[IDPConstants::CLIENT_ID] === $Wm)) {
goto hb;
}
$AG = $av->getData();
goto cD;
hb:
Q3:
}
cD:
HI:
if (!($uM == "redirect_uri")) {
goto s4;
}
$nf = $TC;
foreach ($Kb as $av) {
if (!($av->getData()[IDPConstants::CLIENT_REDIRECT_URL] === $TC)) {
goto Ok;
}
$AG = $av->getData();
goto HH;
Ok:
K5:
}
HH:
s4:
ya:
}
AX:
$this->idpUtility->log_debug("Token.php: client selected for attribute mapping: ", $AG[IDPConstants::CLIENT_NAME]);
$RC = $AG[IDPConstants::SELECTED_GRANT_TYPE];
if (!($sG != "refresh_token" && $RC != $sG)) {
goto VE;
}
return $this->getResponse()->setBody("Grant Type mismatch. Please contact your administrator.");
VE:
$MN = $AG[IDPConstants::CLIENT_ID];
$eW = $AG[IDPConstants::CLIENT_SECRET];
$H4 = $AG[IDPConstants::REDIRECT_URL];
$SR = $AG[IDPConstants::SCOPE];
$qD = $AG["jwt_token_expiry"];
$ZE = $AG["access_token_expiry"];
$T6 = $AG["refresh_token_expiry"];
if (!(empty($qD) || is_null($qD) || $qD == 0)) {
goto sg;
}
$qD = 1;
sg:
if (!(empty($ZE) || is_null($ZE) || $ZE == 0)) {
goto BQ;
}
$ZE = 1;
BQ:
if (!(empty($T6) || is_null($T6) || $T6 == 0)) {
goto Bx;
}
$T6 = 1;
Bx:
if ($sG == "password") {
goto a7;
}
if ($sG == "authorization_code") {
goto sP;
}
if ($sG == "refresh_token") {
goto cI;
}
$this->idpUtility->log_debug("parameters received in token request: ", print_r($lw, true));
$XT = $lw["code"];
$pj = $lw["redirect_uri"];
$sG = $lw["grant_type"];
$this->idpUtility->flushCache();
$gB = $this->idpUtility->getUserDataFromCode($XT);
$sU = $gB["user_id"];
$KU = $gB["auth_code_expiry_time"];
$ul = $gB["auth_code"];
$oi = $this->idpUtility->oauthserver_server_sso_validate_code($ul, $XT, $KU);
if (!$oi) {
goto HE;
}
return $this->getResponse()->setBody($oi);
HE:
$uB = $this->idpUtility->oauthserver_server_sso_validate_redirectUrl($pj, $H4);
if (!$uB) {
goto Z0;
}
return $this->getResponse()->setBody($uB);
Z0:
goto RP;
a7:
$NC = $lw["username"];
$u0 = $lw["password"];
$pj = "/";
if (isset($lw["redirect_uri"])) {
goto D6;
}
$pj = $H4;
goto KA;
D6:
$pj = $lw["redirect_uri"];
KA:
if (!(empty($NC) || empty($u0))) {
goto vr;
}
return $this->getResponse()->setBody("Username or Password not received");
vr:
if (isset($lw["client_id"])) {
goto bb;
}
$sg = $Wm;
goto FZ;
bb:
$sg = $lw["client_id"];
FZ:
if (isset($lw["client_secret"])) {
goto Iu;
}
$TA = $Q_;
goto Pj;
Iu:
$TA = $lw["client_secret"];
Pj:
$this->idpUtility->log_debug("received: " . $sg . "stored: " . $MN);
$BZ = $this->idpUtility->oauth_server_sso_validate_clientId($sg, $MN);
if (!$BZ) {
goto Bn;
}
return $this->getResponse()->setBody($BZ);
Bn:
$kf = $this->idpUtility->oauth_server_sso_validate_clientSecret($TA, $eW);
if (!$kf) {
goto X0;
}
return $this->getResponse()->setBody($kf);
X0:
try {
$ri = $this->customerAccountManagement->authenticate($NC, $u0);
} catch (AuthenticationException $x7) {
return $this->getResponse()->setBody("The account sign-in was incorrect or your account is disabled temporarily. Please wait and try again later.");
}
$sU = $ri->getId();
$VZ = $this->customerModel->load($sU);
$gB = $this->idpUtility->getUserDataFromUserId($sU);
$oq = time();
goto RP;
sP:
$this->idpUtility->log_debug("parameters received in token request: ", print_r($lw, true));
$XT = $lw["code"];
$pj = $lw["redirect_uri"];
$sG = $lw["grant_type"];
$gB = $this->idpUtility->getUserDataFromCode($XT);
$this->idpUtility->log_debug("Token: parameters received in userdata: ");
if (!isset($gB["user_id"])) {
goto tJ;
}
$sU = $gB["user_id"];
$KU = $gB["auth_code_expiry_time"];
$ul = $gB["auth_code"];
$oi = $this->idpUtility->oauthserver_server_sso_validate_code($ul, $XT, $KU);
$this->idpUtility->log_debug("authCodeValidationResult");
if (!$oi) {
goto pD;
}
return $this->getResponse()->setBody($oi);
pD:
$K1 = $this->idpUtility->oauthserver_server_sso_validate_grant($sG);
$this->idpUtility->log_debug("granttypeValidationResult");
if (!$K1) {
goto Cj;
}
return $this->getResponse()->setBody($K1);
Cj:
$uB = $this->idpUtility->oauthserver_server_sso_validate_redirectUrl($pj, $H4);
$this->idpUtility->log_debug("redirectUrlValidationResult");
if (!$uB) {
goto An;
}
return $this->getResponse()->setBody($uB);
An:
tJ:
goto RP;
cI:
$cj = $lw["refresh_token"];
$Ho = $this->idpUtility->generateRandom(255);
$Ho .= "client" . $MN;
$Bu = 3600 * (int) $ZE;
$oq = time();
$B1 = $oq + 3600 * (int) $ZE;
$gB = $this->idpUtility->getUserDataFromAccessToken($cj);
if (!(isset($gB["refresh_token_expiry_time"]) && $gB["refresh_token_expiry_time"] < $oq)) {
goto iA;
}
$rd = json_encode(["error" => "invalid_grant", "error_description" => "Refresh token has expired"]);
$this->response->setBody($rd);
$this->response->setStatusCode(200);
$this->response->setHeader("Content-Type", "application/json", true);
$this->response->setHeader("Content-Length", strlen($rd));
$this->response->send();
return;
iA:
if (!empty($gB)) {
goto lK;
}
$rd = json_encode(["error" => "invalid_grant", "error_description" => "Refresh token not found"]);
$this->response->setBody($rd);
$this->response->setStatusCode(200);
$this->response->setHeader("Content-Type", "application/json", true);
$this->response->setHeader("Content-Length", strlen($rd));
$this->response->send();
return;
lK:
$sU = $gB["user_id"];
$Tn = isset($gB["nonce"]) ? $gB["nonce"] : null;
$this->idpUtility->addAccessTokenData($sU, $Ho, $B1);
$this->idpUtility->flushCache();
$qA = $this->generateIDToken($MN, $sU, $AG, $Tn, $qD);
$E6 = $this->generateCustomerToken($sU);
$iD = ["access_token" => $Ho, "customer_token" => $E6, "id_token" => $qA, "expires_in" => $Bu, "token_type" => "Bearer"];
$rd = json_encode($iD);
$this->response->setBody($rd);
$this->response->setStatusCode(200);
$this->response->setHeader("Content-Type", "application/json", true);
$this->response->setHeader("Content-Length", strlen($rd));
$this->response->send();
return;
RP:
$Tn = isset($gB["nonce"]) ? $gB["nonce"] : null;
$Ho = $this->idpUtility->generateRandom(255);
$Ho .= "client" . $MN;
$cj = $this->idpUtility->generateRandom(255);
$cj .= "client" . $MN;
$E6 = $this->generateCustomerToken($sU);
$this->idpUtility->log_debug("nonce in token.php: " . $Tn);
$qA = $this->generateIDToken($MN, $sU, $AG, $Tn, $qD);
$this->idpUtility->log_debug("idToken: ", print_r($qA, true));
$Bu = 3600 * (int) $ZE;
$Rg = "SUCCESS";
$iD = ["access_token" => $Ho, "refresh_token " => $cj, "id_token" => $qA, "customer_token" => $E6, "expires_in" => $Bu, "status" => $Rg, "token_type" => "Bearer", "scope" => $SR];
$oq = time();
$hO = $this->idpUtility->getStoreConfig(IDPConstants::TOKEN);
$pv = $this->idpUtility->isExistingSSOUser("customer_entity", $sU);
$user = $this->idpUtility->getCustomer($sU);
if (!(!isset($pv[0]["idp_user"]) || $pv[0]["idp_user"] == 0 || empty($pv[0]["idp_user"]))) {
goto RO;
}
if ($this->idpUtility->check_plan(2)) {
goto Bd;
}
$this->idpUtility->checkIfUserLeft($user);
goto MR;
Bd:
$this->idpUtility->checkTrialUserLeft($user);
MR:
RO:
$B1 = $oq + 3600 * (int) $ZE;
$k3 = $oq + 3600 * (int) $T6 * 24;
if (!isset($gB["access_token"]) || empty($gB["access_token"])) {
goto jO;
}
$this->idpUtility->addAccessTokenData($sU, $Ho, $B1);
goto iO;
jO:
$this->idpUtility->addAccessTokenData($sU, $Ho, $B1);
$this->idpUtility->flushCache();
iO:
if (!isset($gB["access_token"]) || empty($gB["access_token"])) {
goto zI;
}
$this->idpUtility->addRefreshTokenData($sU, $cj, $k3);
goto Hj;
zI:
$this->idpUtility->addRefreshTokenData($sU, $cj, $k3);
$this->idpUtility->flushCache();
Hj:
$this->idpUtility->log_debug("stored client id: ", $MN);
$rd = json_encode($iD);
$this->response->setBody($rd);
$this->response->setStatusCode(200);
$this->response->setHeader("Content-Type", "application/json", true);
$this->response->setHeader("Content-Length", strlen($rd));
$this->response->send();
return;
}
public function createCsrfValidationException(RequestInterface $De) : ?InvalidRequestException
{
return null;
}
public function validateForCsrf(RequestInterface $De) : ?bool
{
return true;
}
public function generateIDToken($sg, $Rd, $AG, $Tn, $qD)
{
$base_url = $this->idpUtility->getBaseUrl();
if (!$AG[IDPConstants::IS_BACKEND_SSO_ENABLED]) {
goto U2;
}
$Zf = $this->idpUtility->getAdminUserById($Rd);
$Wc = $Zf->getEmail();
$U_ = $Zf->getFirstName();
$OO = $Zf->getLastName();
$S9 = $Zf->getRole()->getId();
$NC = $Zf->getUserName();
$sU = $Zf->getUserId();
$kr = ["alg" => "RS256", "typ" => "JWT"];
$this->idpUtility->log_debug("client id : ", $sg);
$Wo = ["iss" => $base_url, "aud" => $sg, "iat" => time(), "exp" => time() + 3600, "NameId" => $Wc, "firstName" => $U_, "lastName" => $OO, "role_id" => $S9, "username" => $NC, "userId" => $sU];
if (is_null($Tn)) {
goto cz;
}
$Wo["nonce"] = $Tn;
cz:
$this->idpUtility->log_debuG("Token.php: Final attributes to be sent: ", $Wo);
$Sf = $this->base64url_encode(json_encode($kr));
$fa = $this->base64url_encode(json_encode($Wo));
$fM = $Sf . . $fa;
$Yi = $this->idpUtility->getFileContents($this->idpUtility->getResourcePath("private_key.pem"));
$fR = hash_hmac("sha256", $fM, $Yi);
$fR = str_replace(["+", "/", "="], ["-", "_", ''], base64_encode($fR));
openssl_sign($fM, $fR, $Yi, OPENSSL_ALGO_SHA256);
$CP = $this->base64url_encode($fR);
$lK = $Sf . . $fa . . $CP;
$this->idpUtility->log_debug("id_token : ", $lK);
return $lK;
goto Av;
U2:
$Zf = $this->customerRepository->getById($Rd);
$Qq = $this->customerFactory->create()->load($Rd);
$JM = $Qq->getData();
$this->idpUtility->log_debug("customer_entity attributes : ", $JM);
$Eo = $Qq->getDefaultBilling();
$TO = $Qq->getDefaultShipping();
$this->idpUtility->log_debug("billing address id : ", $Eo);
$this->idpUtility->log_debug("shipping address id : ", $TO);
$qC = $this->_addressFactory->create()->load($Eo);
$y4 = $this->_addressFactory->create()->load($TO);
if (!isset($qC)) {
goto M0;
}
$kC = $qC->getData();
$this->idpUtility->log_debug("billing address : ", $kC);
M0:
if (!isset($y4)) {
goto Eu;
}
$mY = $y4->getData();
$this->idpUtility->log_debug("Shipping address : ", $mY);
Eu:
$Wc = $Zf->getEmail();
$U_ = $Zf->getFirstName();
$OO = $Zf->getLastName();
$S9 = $Zf->getGroupId();
$kr = ["alg" => "RS2", "typ" => "JWT"];
$this->idpUtility->log_debug("client id : ", $sg);
$GV = $AG[IDPConstants::ATTRIBUTE_MAPPING];
$this->idpUtility->log_debuG("Token.php: mapped_attrs: ", $GV);
$rk = $AG[IDPConstants::CUSTOM_ATTRIBUTE_MAPPING];
$this->idpUtility->log_debuG("Token.php: mapped_custom_attrs: ", $rk);
$Wo = ["iss" => $base_url, "aud" => $sg, "iat" => time(), "exp" => time() + 3600 * (int) $qD, "NameId" => $Wc, "first_name" => $U_, "last_name" => $OO];
if (is_null($Tn)) {
goto kb;
}
$Wo["nonce"] = $Tn;
kb:
if (!($GV != null)) {
goto CA;
}
$GV = json_decode((string) $GV);
foreach ($GV as $hO => $TC) {
if (isset($JM[$TC])) {
goto L1;
}
if (isset($kC[$TC])) {
goto OU;
}
if (!isset($mY[$TC])) {
goto yZ;
}
$Wo[$hO] = $mY[$TC];
yZ:
goto Gy;
OU:
$Wo[$hO] = $kC[$TC];
Gy:
goto uO;
L1:
$Wo[$hO] = $JM[$TC];
uO:
MH:
}
J2:
CA:
if (!($rk != NULL)) {
goto Z6;
}
$rk = json_decode((string) $rk);
foreach ($rk as $hO => $TC) {
$Wo[$hO] = $TC;
fy:
}
hj:
Z6:
$Sf = $this->base64url_encode(json_encode($kr));
$fa = $this->base64url_encode(json_encode($Wo));
$fM = $Sf . . $fa;
$Yi = $this->idpUtility->getFileContents($this->idpUtility->getResourcePath("private_key.pem"));
$fR = hash_hmac("sha6", $fM, $Yi);
$fR = str_replace(["+", "/", "="], ["-", "_", ''], base64_encode($fR));
openssl_sign($fM, $fR, $Yi, OPENSSL_ALGO_SHA256);
$CP = $this->base64url_encode($fR);
$lK = $Sf . . $fa . . $CP;
return $lK;
Av:
}
public function base64url_encode($Ti)
{
return rtrim(strtr(base64_encode($Ti), "+/", "-_"), "=");
}
private function generateCustomerToken($Ij)
{
try {
$E6 = $this->tokenModelFactory->create()->createCustomerToken($Ij)->getToken();
$this->idpUtility->log_debug("Token: Customer token created");
return $E6;
} catch (\Exception $x7) {
$this->idpUtility->log_error("Token: Token creation error - " . $x7->getMessage());
return null;
}
}
}
© 2023 Quttera Ltd. All rights reserved.