Creating own Zend_Auth_Adapter - zend-framework

i am having difficulties creating my own Zend_Auth_Adapter. i am using Doctrine 2 with it also. so far i have ... code below
i am getting the error
Method "hasIdentity" does not exist and was not trapped in __call()
whats wrong?
use \Doctrine\ORM;
class Application_Auth_Adapter implements Zend_Auth_Adapter_Interface {
private $username;
private $password;
function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
function authenticate() {
$em = Zend_Registry::get('em');
$query = $em->createQuery('select u from Application\Entities\User u WHERE u.name = :username')
->setParameter('username', $this->username);
try {
$user = $query->getSingleResult();
$salt = $user->salt;
$hashedPassword = hash_hmac('sha256', $this->password, $salt);
if ($hashedPassword == $user->password) {
// login success
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
} else {
// wrong password
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, null);
}
} catch (NonUniqueResultException $e) {
// non unique result
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
} catch (NoResultException $e) {
// no result found
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, null);
} catch (Exception $e) {
// exception occured
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
}
}
}
UPDATE
i noticed that the problem comes from abt line 123 of Zend_Auth
if ($this->hasIdentity()) {
$this->clearIdentity();
}
but just below that function, authenticate(), its
public function hasIdentity()
i noticed something strange with teh stack trace
#0 [internal function]: Zend_Controller_Action->__call('hasIdentity', Array)
#1 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Auth.php(123): AuthController->hasIdentity()
#2 D:\Projects\Websites\php\ZendFramework\LearningZF\application\controllers\AuthController.php(23): Zend_Auth->authenticate(Object(Application_Auth_Adapter))
#3 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Action.php(513): AuthController->loginAction()
#4 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('loginAction')
#5 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#6 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#7 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#8 D:\Projects\Websites\php\ZendFramework\LearningZF\public\index.php(26): Zend_Application->run()
#9 {main}
see AuthController->hasIdentity() its trying to call hasIdentity() from AuthController!

i found out why! see my update ... the stack trace. i am calling a method as if it were static. wont that produce an error? anyways ... i shld be doing
$result = Zend_Auth::getInstance()->authenticate($adapter);

Nice adapter, although I suggest $user->getPassword() and $user->getSalt()

Related

How to catch exception in a callback function in Dart (Flutter)?

I'm using WebSocket variable in my MyWebSocket class. For listen i give a callback function as parameter.
If this callback function throws an exception in calling class MyChat, then i can not catch that exception anywhere.
My simplified code is:
class MyWebSocket {
WebSocket _ws;
...
// initialized in controller: _ws = WebSocket.connect(_some_url_);
// everything works (connect, listen)
...
void listen({void Function(dynamic) myOnListen}) {
try {
_ws.listen(myOnListen)
.onError((e) => print("MyWebSocket in MyChat.onError: $e"));
} catch (e) {
print("Catched in MyWebSocket: $e");
}
}
}
class MyChat {
MyWebSocket _chatWs = MyWebSocket();
...
void initWS() {
try {
_chatWs.listen(myOnListen: processMsg);
} catch (e) {
print("Catched in MyChat: $e");
}
}
void processMsg(dynamic msg) {
if(_some_stuff_like_invalid_msg_or_not_logged_in_...)
throw Exception("There is my Exception");
}
}
I have built try-catch in every possible place to catch exceptions - no success, i got only unhandled exception:
E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Exception: There is my Exception
E/flutter: #0 MyChat.processMsg
Beware that you cannot use the passed listener as a key for later removal. For that you can pass the new listener created in MyWebSocket class when listen() is called, then use this key to remove the listener.
class MyWebSocket {
WebSocket _ws;
void listen({void Function(dynamic) myOnListen, void Function(Error) onError}) {
try {
_ws.listen((){
try {
myOnListen({"label": "DATA"});
} catch (e) {
if(onError is Function)
onError(e)
}
})
.onError(onError);
} catch (e) {
print("Catched in MyWebSocket: $e");
}
}
}
class MyChat {
MyWebSocket _chatWs = MyWebSocket();
void initWS() {
try {
_chatWs.listen(myOnListen: processMsg, onError: (Error error){
print("ERROR: "+error.toString());
});
} catch (e) {
print("Catched in MyChat: $e");
}
}
void processMsg(dynamic msg) {
if(_some_stuff_like_invalid_msg_or_not_logged_in_...)
throw Exception("There is my Exception");
}
}
You need to handle it inside your processMsg
If you analyze carefully the execution of your code the _ws.listent register a listener for when you receive a message and that will happen in the FUTURE, but you don't get an error WHILE you are REGISTERING your listener that's why that doesn't work the way you expect.
processMsg will do something in the future, it will throw an error and it's at the end of the pipeline.
You are simulating an exception and nothing is handling it, it happens in a different stack frame, in the future.
The void listen({void Function(dynamic) myOnListen}) function execution is long gone when you receive and you precessMsg.
Alternatively you could do:
Function tryCatchHOF(Function cb) {
decorated(dynamic param) {
try {
cb(param);
} catch (e) {
print("$e");
}
}
;
return decorated;
}
void processMsg(dynamic msg) {
if (true) throw Exception("There is my Exception");
}
var processMsgWithTryCatch = tryCatchHOF(processMsg);
processMsgWithTryCatch('');
and then pass processMsgWithTryCatch down to your listener if you don't want to handle inside processMsg
I hope that make sense

How to do queries with pdo db connection function?

I read too many questions and answers around but couldn't be sure.
I have 2 questions
1.I turned my db connection into a function and I am not sure if its
safe ?
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
function DB()
{
try {
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}
2.is my query done right way ?
query:
try {
$pdo = DB();
$stmt = $pdo->prepare("SELECT * FROM settings");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$c = htmlspecialchars($row['site_url']);
$e = filterString($row['contact']);
}
unset($stmt);
} catch (PDOException $e) {
exit($e->getMessage());
}
Thanks for any help
Perhaps keep one connection, rather than opening multiple connections to the Database. You can look into a project PDOEasy that I created to make MVC easy with PDO or use the below static example.
class DB
{
private $_connection;
private static $_instance;
public static function getInstance() {
if(self::$_instance) return self::$_instance;
self::$_instance = new self();
return self::$_instance;
}
private function __construct() {
$this->_connection = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD, array(
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
));
}
public function getConnection() { return $this->_connection; }
}
Which can be used like so:
$stmt = DB::getInstance()
->getConnection()
->Prepare('SELECT * FROM settings');
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
// ...
}

How to use monolog in slim 3?

In my app.php file:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class App extends \DI\Brifge\Slim\app
{
public function configureContainer(ContainerBuilder $builder)
{
$dependencies = [
'logger' => function (Container $container) {
$logger = new Monolog\Logger('logger');
$filename = _DIR__ . '/../log/error.log';
$stream = new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG);
$fingersCrossed = new Monolog\Handler\FingersCrossedHandler(
$stream, Monolog\Logger::ERROR);
$logger->pushHandler($fingersCrossed);
return $logger;
},
];
}
}
In my custom error handler:
class CustomErrorHandler
{
protected $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $exception)
{
$output = ['success'=>0, 'error'=>"Oops! Something's not right "];
$this->logger->critical($output);
return $response->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode($output));
}
}
When an error is thrown, following message is displayed:
Fatal error: Uncaught Error: Class 'App\Monolog\Logger' not found in C:\xampp\htdocs\backend\app\App.php:103 Stack trace: #0 [internal function]: App\App->App{closure}(Object(DI\Container)) #1 C:\xampp\htdocs\backend\vendor\php-di\invoker\src\Invoker.php(82): call_user_func_array(Object(Closure), Array) #2 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\FactoryResolver.php(81): Invoker\Invoker->call(Object(Closure), Array) #3 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\ResolverDispatcher.php(58): DI\Definition\Resolver\FactoryResolver->resolve(Object(DI\Definition\FactoryDefinition), Array) #4 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(287): DI\Definition\Resolver\ResolverDispatcher->resolve(Object(DI\Definition\FactoryDefinition), Array) #5 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(124): DI\Container->resolveDefinition(Object(DI\Definition\FactoryDefinition)) #6 C:\xampp\htdocs\backend\app\App.php(95): DI\Container->get('l in C:\xampp\htdocs\backend\app\App.php on line 103
I have included the statement use Monolog\Logger; in App.php file but I get the above error.
You forgot to register dependencies in configureContainer method:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class App extends \DI\Bridge\Slim\App
{
public function configureContainer(ContainerBuilder $builder)
{
$dependencies = [
'logger' => function (Container $container) {
$logger = new Monolog\Logger('logger');
$filename = _DIR__ . '/../log/error.log';
$stream = new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG);
$fingersCrossed = new Monolog\Handler\FingersCrossedHandler(
$stream, Monolog\Logger::ERROR);
$logger->pushHandler($fingersCrossed);
return $logger;
},
];
// Register definitions
$builder->addDefinitions($dependencies);
}
}
Also you have a mistake in App class declaration, it's \DI\Bridge\Slim\App, not \DI\Brifge\Slim\app
I understood where I was wrong.
No need to include the lines:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
While instantiating, I have included the complete path.

In Magento, on submitting the registation form; throws a new Exception()

I am creating a custom Registration form. On submitting the form it has to generate a mail but now it is throwing a new Exception(); error. Guide me on how to solve this problem
my code
<?php
class Huntgather_Registration_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/huntgather_registration/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/huntgather_registration/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/huntgather_registration/email_template';
const XML_PATH_ENABLED = 'contacts/huntgather_registration/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('registrationForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['product-name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['serial-number']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['date']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['address']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is($post['data-privacy'], 'NotEmpty')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('huntgather_registration')->__('Your registration has been processed. Thank you for registering your product'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
Form submit getting error
(We were unable to process your registration. Please make sure you have entered all required data in the form below)
I think you got an exception while sending email. You should replace
Mage::getSingleton('customer/session')->addError(Mage::helper('huntgather_registration')->__('We were unable to process your registration. Please make sure you have entered all required data in the form below'));
With
Mage::getSingleton('customer/session')->addError($e->getMessage());
to get problem exactly.

zend form not working when calling to multiple page

I have a controller action
public function pagedetailAction(){
$id = $this->_getParam('id',0);
$detail = new Application_Model_Page();
$this->view->detail = $detail->findArr($id);
//CALLING FORM WITH OTHER CONTENTS
$form = new Application_Form_Request();
$this->view->form = $form;
}
To process the form I have this function
public function submitrequestAction(){
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$newsadd = new Application_Model_Request($formData);
$newsadd->set_ID(null);
$newsadd->save();
$this->_helper->flashMessenger->addMessage(array('success'=>'Message Sent'));
$this->_redirect('/index/frontmsg');
} else {
$form->populate($formData);
}
}
}
when i click submit i get the error
Notice: Undefined variable: form in E:\xampp\htdocs\sandbox1\application\controllers\IndexController.php on line 84
Fatal error: Call to a member function isValid() on a non-object in E:\xampp\htdocs\sandbox1\application\controllers\IndexController.php on line 84
Please help me so that I can post values to database via this form. Thanks
Use this
public function submitrequestAction(){
if ($this->getRequest()->isPost()) {
$form = new Application_Form_Request();//added this
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$newsadd = new Application_Model_Request($formData);
$newsadd->set_ID(null);
$newsadd->save();
$this->_helper->flashMessenger->addMessage(array('success'=>'Message Sent'));
$this->_redirect('/index/frontmsg');
} else {
$form->populate($formData);
}
}
}
Add $form initialization to your submitrequestAction:
$form = new Application_Form_Request();