CognitoIdentityClient - 404 not found in iam/security-credentials - amazon-web-services

I want to register an AWS Cognito Identity using getOpenIdTokenForDeveloperIdentity.
Below are my codes written in CodeIgniter framework:
Awscognitoauth.php
<?php
// <MYPROJECT>/application/controllers/Awscognitoauth.php
defined('BASEPATH') or exit('No direct script access allowed');
class Awscognitoauth extends CI_Controller {
function getOpenId($userId) {
$this->load->library('awsauth');
return $this->awsauth->identity($userId);
}
}
Awsauth.php
<?php
// <MY PROJECT>/application/libraries/Awsauth.php
defined('BASEPATH') or exit('No direct script access allowed');
require_once APPPATH . "third_party/aws/aws-autoloader.php";
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
class Awsauth {
public function identity($userId) {
$region = '<my region>';
$key = '<my key>';
$secret = '<my secret>';
$version = 'latest';
$client = CognitoIdentityClient::factory(array('region' => $region, 'key' => $key, 'secret' => $secret, 'version' => $version));
$poolId = '<my pool Id>'; // formatted: "<region>:<UUID>"
$domain = '<my reversed company domain>'; // com.<company...>...
return $client->GetOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $poolId, 'Logins' => array($domain => $userId))); // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html
}
}
In safari, I call the controller Awscognitoauth and get the following error:
I double-checked my user's role here:
It is AdministratorAccess
Access key does match with the key in my code
What could cause this 404 Not Found response? I thought that my user has AdministratorAccess and I can access any resource. Do I miss something?

oh shoot!
I just found out that the $key and $secret must be wrapped in credentials.
So, the final code for Awsauth.php is:
<?php
// <MY PROJECT>/iot.kooltechs.com/application/libraries
defined('BASEPATH') or exit('No direct script access allowed');
require_once APPPATH . "third_party/aws/aws-autoloader.php";
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
class Awsauth {
public function identity($userId) {
$region = '<my region>';
$key = '<my key>';
$secret = '<my secret>';
$version = 'latest';
$config = [
'version' => $version,
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret
]
];
$client = CognitoIdentityClient::factory($config);
$poolId = '<my pool Id>'; // formatted: "<region>:<UUID>"
$domain = '<my reversed company domain>'; // com.<company...>...
return $client->GetOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $poolId, 'Logins' => array($domain => $userId)));
}
}
Regards,

Related

Symfony ignore mock in test service

I'm trying to test a service using phpunit. When i mock a function in my StatServiceTest, my service ignore the mock i did.
with an example will be more clear :
my service.yml
my_service:
class: '%my_service.class%'
parent: parent_service
arguments:
- '#service.repository.commutation'
- '#service.repository.stat'
- '#service.repository.switchboard'
- '%sunrise_host%'
my service : StatService.php
class StatService extends AbstractService
{
protected $commutationRepository;
protected $statRepository;
protected $switchboardRepository;
protected $sunrise_host;
public function __construct(CommutationRepository $commutationRepository, StatRepository $statRepository, SwitchboardRepository $switchboardRepository, $sunrise_host)
{
$this->commutationRepository = $commutationRepository;
$this->statRepository = $statRepository;
$this->switchboardRepository = $switchboardRepository;
$this->sunrise_host = $sunrise_host;
}
public function getNightsWithSunService($id, $start, $end)
{
$switchboard = $this->switchboardRepository->getById($id);
$parameters = array(
'begin' => (int) $start,
'end' => (int) $end,
'lat' => (float) $switchboard->getElement()->getCoordinate()->getLat(),
'lng' => (float) $switchboard->getElement()->getCoordinate()->getLng(),
'timezone' => $switchboard->getElement()->getCoordinate()->getTimezone(),
);
$buzz = new Buzz();
$result = $buzz->post(
$this->sunrise_host.'/nights',
array(
'Content-Type' => 'application/json',
),
json_encode($parameters)
);
return json_decode($result->getContent(), true);
}
}
and finally my StatServiceTest.php
class StatServiceTest extends WebTestCase
{
public function testGetNightsWithSunService()
{
$dic = $this->_client->getKernel()->getContainer();
$sunriseHost = $dic->getParameter('sunrise_host');
$id = 426;
$start = 1538400421;
$end = 1538569621;
$mapNights = $this->getNights();
$mockStatService = $this->getMockBuilder("StatService")
->disableOriginalConstructor()
->getMock();
$mockStatService
->expects($this->any())
->method('getNightsWithSunService')
->withConsecutive(array($id, $start, $end))
->willReturnOnConsecutiveCalls($mapNights)
;
$statService = new StatService($mockCommutationRepository,
$mockStatRepository, $mockSwitchboardRepository, $sunriseHost);
$result = $statService->getNightsWithSunService($id, $start, $end);
$nights = array(
array(
'start' => 1538414415,
'end' => 1538458643,
),
array(
'start' => 1538500702,
'end' => 1538545117,
),
);
$this->assertTrue($this->arrays_are_similar($nights, $result));
}
public function getNights()
{
$nights = array(
array(
'start' => 1538414415,
'end' => 1538458643,
),
array(
'start' => 1538500702,
'end' => 1538545117,
),
);
return $nights;
}
public function arrays_are_similar($a, $b)
{
// we know that the indexes, but maybe not values, match.
// compare the values between the two arrays
foreach ($a as $k => $v) {
if ($v !== $b[$k]) {
return false;
}
}
// we have identical indexes, and no unequal values
return true;
}
}
the error is :
testGetNightsWithSunService
Buzz\Exception\RequestException:
file_get_contents(http://localhost:4244/nights): failed to open
stream: Connection refused
i instantiate my service and i inject in it repositories that i mocked, i just put the part of code that concerns the problem.
What i did wrong ? please any advice will be helpful
The solution i founded is to do another service => toolsService with a function callback for the buzz part, and then we can inject this service and will be more easy to mock it.
I hope that will help you

Fail to mock object (Cakephp 3.0.3)

I am using Cakephp 3.0.3 and I have following method in my User Entity,
public function sendRecovery()
{
$email = new Email('default');
$email->viewVars([
'userId' => $this->id,
'token' => $this->token
]);
$email->template('GintonicCMS.forgot_password')
->emailFormat('html')
->to($this->email)
->from([Configure::read('admin_mail') => Configure::read('site_name')])
->subject('Forgot Password');
return $email->send();
}
i am writing testCase for it.
here is my testCase Method.
public function testSendRecovery()
{
$entity = new User([
'id' => 1,
'email' => 'hitesh#securemetasys.com',
'token' => 'jhfkjd456d4sgdsg'
]);
$email = $this->getMock('Cake\Network\Email\Email', ['sendRecovery']);
$email->expects($this->once())
->method('sendRecovery')
->with($this->equalTo('hitesh#securemetasys.com'));
$entity->sendRecovery();
}
when i run phpunit then i got following error,
There was 1 error:
1) GintonicCMS\Test\TestCase\Model\Entity\UserTest::testSendRecovery
InvalidArgumentException: Unknown email configuration "default".
E:\xampp\htdocs\Cake3\Proball-Market\plugins\GintonicCMS\vendor\cakephp\cakephp\src\Network\Email\Email.php:1382
E:\xampp\htdocs\Cake3\Proball-Market\plugins\GintonicCMS\vendor\cakephp\cakephp\src\Network\Email\Email.php:1269
E:\xampp\htdocs\Cake3\Proball-Market\plugins\GintonicCMS\vendor\cakephp\cakephp\src\Network\Email\Email.php:383
E:\xampp\htdocs\Cake3\Proball-Market\plugins\GintonicCMS\src\Model\Entity\User.php:90
E:\xampp\htdocs\Cake3\Proball-Market\plugins\GintonicCMS\tests\TestCase\Model\Entity\UserTest.php:73
can any one help me Please?

Undefined index: action error in facebook api

I am using php api's in my website (to make a profile page)
I am using the below code:
$action = $_REQUEST["action"];
switch($action){
case "fblogin":
include 'facebook.php';
$appid = "**********";
$appsecret = "*************************";
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
$user_profile = $facebook->api('/me');
}
catch (Exception $e) {
echo $e->getMessage();
exit();
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fnmae = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
$check_select = mysql_num_rows(mysql_query("SELECT * FROM `fblogin` WHERE email = '$user_email'"));
if($check_select > 0){
mysql_query("INSERT INTO `fblogin` (fb_id, name, email, image, postdate) VALUES ('$user_fbid', '$user_fnmae', '$user_email', '$user_image', '$now')");
}
}
break;
}
It gives an error saying : Undefined index: action
I am using wamp server as localhost. Please provide a solution

Cakephp mock Email Utility

i'm a little stuck trying to test my users-controller in cakephp,
i have an action wich sends an email to a certain email address.
The email utility works, no problem whatsoever.
I want to mock the email utility so that when i test the action (with "testAction"),
no email will be sent.
I already searched all over stackoverflow and tried a lot of solutions, the current code is like follows:
UsersController:
/**
* Get Email Utility, use method so that unit testing is possible
* #return object
*/
public function _getEmailer()
{
return new CakeEmail();
}
public function lostPassword()
{
if($this->request->is('post'))
{
$email = $this->request->data['User']['email'];
$this->User->recursive = -1;
$user = $this->User->find('first', array('conditions' => array('email' => $email)));
if(!$user)
{
$this->Session->setFlash('Error: user not found');
return $this->render();
}
$recoverTrials = $this->User->Recover->find('count', array('conditions' => array('email' => $email)));
if($recoverTrials > 3)
{
$this->Session->setFlash(__('message.recover-too-many'));
return $this->redirect('/');
}
// Generate random key to reset password
$key = md5(microtime().rand());
$data = array('user_id' => $user['User']['id'],
'key' => $key,
'active' => 1,
'created' => date('Y-m-d H:i:s'));
if(!$this->User->Recover->save($data))
{
$this->Session->setFlash('Error while sending the recovery-mail');
return $this->redirect('/');
}
$this->Email = $this->_getEmailer();
$this->Email->emailFormat('html');
$this->Email->to($email);
$this->Email->subject('Password recover');
$this->Email->replyTo('noreply#domain.com');
$this->Email->from(array('noreply#domain.com' => 'Sender ID'));
$this->Email->template('recover');
$this->Email->viewVars(array('key' => $key)); // Set variables for template
try
{
$this->Email->send();
}
catch(Exception $e)
{
$this->Session->setFlash('Error while sending the recovery-mail');
return $this->render();
}
$this->Session->setFlash('The recovery mail with instructions to reset your password has been sent. Please note that the link will only remain active for 2 hours.');
return $this->redirect('/');
}
}
And my test class looks like (excerpt):
public function testPostLostPassword()
{
$this->Controller = $this->generate('Users', array(
'methods' => array(
'_getEmailer'
),
'components' => array('Security')
));
$emailer = $this->getMock('CakeEmail', array(
'to',
'emailFormat',
'subject',
'replyTo',
'from',
'template',
'viewVars',
'send'
));
$emailer->expects($this->any())
->method('send')
->will($this->returnValue(true));
$this->Controller->expects($this->any())
->method('_getEmailer')
->will($this->returnValue($emailer));
Correct email
$data = array('User' => array('email' => 'me#domain.com'));
$result = $this->testAction('/lostPassword', array('method' => 'post',
'data' => $data,
'return' => 'contents'));
}
What am i doing wrong? The Email utility still sends out the email to my address, even though i mocked it...
Thanks in advance!

Class 'EventManager' not found

I'm trying to learn about Events in Doctrine, but when I read the docs, I get stuck at the very first line:
$evm = new EventManager();
Here I get a
PHP Fatal error: Class 'EventManager' not found
How can I solve this issue?
Here is the complete code:
use Doctrine\ORM\Tools\Setup;
require_once("Doctrine/ORM/Tools/Setup.php");
Setup::registerAutoloadPEAR();
$classLoader = new Doctrine\Common\ClassLoader('Entities', __DIR__);
$classLoader->register();
$paths = array();
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$dbParams = array("driver" => "pdo_mysql",
"host" => variable_get("dbManip_host"),
"user" => variable_get("dbManip_user"),
"password" => variable_get("dbManip_password"),
"dbname" => variable_get("dbManip_dbName"),
"charset" => "utf8");
global $entityManager_globalObject;
$entityManager_globalObject = \Doctrine\ORM\EntityManager::create($dbParams, $config);
$entityManager_globalObject->getConnection()->exec("SET NAMES UTF8");
$evm = new EventManager();
You are looking for class Doctrine\Common\EventManager.
$evm = new \Doctrine\Common\EventManager();
or
use Doctrine\Common\EventManager; // at the top of your file
$evm = new EventManager();