Laravel queue:work not behaving same as queue:listen - laravel-8

<?php
namespace App\Notifications;
use Illuminate\Notifications\Channels\MailChannel;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Config;
class DynamicEmailChannel extends MailChannel
{
public function send($notifiable, Notification $notification)
{
$service = $notification->service;
$customConfig = [];
$from = [];
if ($service->sender_email && $service->sender_password) {
$customConfig = [
'transport' => 'smtp',
'host' => 'smtp.googlemail.com',
'port' => 587,
'encryption' => 'tls',
'username' => $service->sender_email,
'password' => $service->sender_password,
'timeout' => null,
'auth_mode' => null,
];
$from = [
'address' => $service->sender_email,
'name' => $service->title
];
} else {
$customConfig = [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
];
$from = [
'address' => env('MAIL_FROM_ADDRESS', 'hello#example.com'),
'name' => env('MAIL_FROM_NAME', 'Example')
];
}
Config::set('mail.mailers.smtp', $customConfig);
Config::set('mail.from', $from);
app()->forgetInstance('mail.manager');
parent::send($notifiable, $notification);
}
}
this program works when run through php artisan queue:listen but the app()->forgetInstance('mail.manager'); runs only once when run through php artisan queue:work. How do i make it behave as with queue:listen?
I am trying to send mail notifications through credentials saved in database.
If i am not wrong, if i delete the 'mail.manager' serviceInstance, it will create new one when called with latest config. it works the same way for queue:listen but not for queue:work. what am i missing, or not understanding here.

After doing some digging replacing app()->forgetInstance('mail.manager'); with Mail::purge('smtp'); solved the issue.

Related

Cakephp 4 save delete auto_increment

I'm doing cakephp4 controller test with phpUnit but when I call save my id auto_increment disapear.
My table before save():
Image before save
The test:
public function testAdd(): void
{
$this->session([
'Auth' => [
'id' => 1,
'DNI_CIF' => '22175395Z',
'name' => 'Prueba',
'lastname' => 'Prueba Prueba',
'username' => 'Pruebatesting',
'password' => 'prueba',
'email' => 'prueba#gmail.com',
'phone' => '639087621',
'role' => 'admin',
'addres_id' => 1
]
]);
$this->get('animal/add');
$this->assertResponseOk();
$data=[
'id' => 1,
'name' => 'AñadirAnimal',
'image' => '',
'specie' => 'dog',
'chip' => 'no',
'sex' => 'intact_male',
'race' => 'cat',
'age' => 1,
'information' => 'Es un animal.',
'state' => 'sick',
'animal_shelter' => [
'id' => 1,
'start_date' => '2022-11-03 10:47:38',
'end_date' => '2022-11-03 10:47:38',
'user_id' => 1,
'animal_id' => 1
]
];
$this->enableCsrfToken();
$this->post('animal/add',$data);
$this->assertResponseOk();
}
The controller:
public function add()
{
$animal = $this->Animal->newEmptyEntity();
if ($this->request->is('post')) {
$animal = $this->Animal->patchEntity($animal, $this->request->getData());
if(!$animal->getErrors){
$image = $this->request->getData('image_file');
if($image !=NULL){
$name = $image->getClientFilename();
}
if( !is_dir(WWW_ROOT.'img'.DS.'animal-img') ){
mkdir(WWW_ROOT.'img'.DS.'animal-img',0775);
if($name){
$targetPath = WWW_ROOT.'img'.DS.'animal-img'.DS.$name;
$image->moveTo($targetPath);
$animal->image = 'animal-img/'.$name;
}
}
if ($this->Animal->save($animal)) {
$this->Flash->success(__('El animal se ha añadido.'));
return $this->redirect(['action' => 'index']);
}
}
$this->Flash->error(__('El animal no se ha podido añadir, por favor intentalo de nuevo'));
}
$allUsers = $this->getTableLocator()->get('User');
$user = $allUsers->find('list', ['limit' => 200])->all();
$this->set(compact('animal','user'));
}
My table after:
Image after save
The error:
1) App\Test\TestCase\Controller\AnimalControllerTest::testAdd
Possibly related to PDOException: "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value"
…
Failed asserting that 500 is between 200 and 204.
I don't know why this is happening or how to know the reason. In the app the controller works fine. Data in the app:
Data in app
Data in test:
Data in test
I hope someone can help me, I don't know what to try anymore or how to know where the problem is...
I tried to look at the data but it doesn't apear to have any errors so I don't know where the error can be.
It was that the sql file used in the bootstrap didn't have the autoincrement value.

Relation two database and make join yii2

Can you help me. How to relate it and make a join
. i get error has no relation named "project".
i using ActiveRecord with my code :
$posts = MaKantor::find()
->leftJoin('project.track', '`track`.`id_office` = `m_kantor`.`kantor_id`')
->with('project.track')->where(['collecting_id' => $model->collecting_id])
->all();
and config
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=project',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db_master',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
When you use with('relationName') in query, relation function needs to be defined in MaKantor model.
For example :
public function getProject()
{
return $this->hasOne(Project::className(), ['id' => 'project_id']);
}

CakePHP 2 Auth Not Working - Blowfish

I'm using CakePHP 2.8.5. It's not letting me log in "Username or password is incorrect". This seems totally straightforward in the docs but it isn't working for me. I wonder if my model/data structure might be confusing CakePHP. I have a Users model, but the logins are associated with an Admins model. The login form and action are in the Pages model (it has forms for multiple models).
in AppController:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
'userModel' => 'Admin',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),
'loginAction' => array(
'controller' => 'pages',
'action' => 'login',
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'login',
),
'authError' => 'Please log in',
'authorize' => array('Controller')
)
);
My login view, in /View/Pages. "email" is the username field:
<?php
echo $this->Form->create('Admin');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->end('Submit');
?>
PagesController:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Flash->error(__('Username or password is incorrect'));
}
}}
Top of Admin model:
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
Automatic Blowfish encryption in Admin model:
public function beforeSave($options = array()) {
if (isset($this->data['Admin']['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data['Admin']['password'] = $passwordHasher->hash(
$this->data['Admin']['password']
);
}
return true;
}
I notice if I enter the same password for different Admins, I get a different encryption result, but I've read that's normal.
If you want to see anything else, I'll add it.
The userModel key is in the wrong place
Compare the config in the question:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
'userModel' => 'Admin',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),
To the config in the docs:
$this->Auth->authenticate = array(
'Basic' => array('userModel' => 'Member'),
'Form' => array('userModel' => 'Member')
);
In the question userModel is a top-level key, in the docs it is part of the individual authenticate keys. Looking at the api examples (or the doc blocks in the source code) the error is more clear:
... you can define settings that should be set to all authentications objects using the 'all' key:
$this->Auth->authenticate = array(
'all' => array(
'userModel' => 'Users.User',
'scope' => array('User.active' => 1)
),
'Form',
'Basic'
);
It is possible to define a global userModel for all authenticate objects to use, but the syntax is simply different than the question.
Use the all key
Therefore to define a user model to use for all authenticate options, use the all key:
public $components = array(
'DebugKit.Toolbar',
'Flash',
'Session',
'Auth' => array(
//'userModel' => 'Admin', // <- no
'authenticate' => array(
'all' => array(
'userModel' => 'Admin' // <- yes
),
'Form' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'passwordHasher' => 'Blowfish'
)
),

install.php is not being run during installation

My install.php is not being run during installation.I checked everywhere.To be sure,I ran the code in install.php elsewhere and it worked well. But during installation only the install.php is being skipped somehow.My module name is Hotelreservation, hence the code in install.php is as below. Why is there no error display during installation ?
<?php
class Hotelreservation_Installer extends Engine_Package_Installer_Module
{
public function onInstall()
{
$this->_hotelroomsBrowsePage();
parent::onInstall();
}
protected function _hotelroomsBrowsePage()
{
$db = $this->getDb();
// profile page
$page_id = $db->select()
->from('engine4_core_pages', 'page_id')
->where('name = ?', 'hotelreservation_index_browse')
->limit(1)
->query()
->fetchColumn();
if (!$page_id) {
// Insert page
$db->insert('engine4_core_pages', array(
'name' => 'hotelreservation_index_browse',
'displayname' => 'HotelRooms Browse Page',
'title' => 'Browse Rooms',
'description' => 'this page displays rooms',
'custom' => 0,
));
$page_id = $db->lastInsertId();
// Insert main
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'main',
'page_id' => $page_id,
));
$main_id = $db->lastInsertId();
// Insert middle
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'middle',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 2,
));
$middle_id = $db->lastInsertId();
// Insert hotelreservation.browse-menu
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'hotelreservation.browse-menu',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 1,
));
// Insert core content
$db->insert('engine4_core_content', array(
'type' => 'widget',
'name' => 'core.content',
'page_id' => $page_id,
'parent_content_id' => $middle_id,
'order' => 2,
));
// Insert left
$db->insert('engine4_core_content', array(
'type' => 'container',
'name' => 'left',
'page_id' => $page_id,
'parent_content_id' => $main_id,
'order' => 3,
));
$left_id = $db->lastInsertId();
}
return $this;
}
}// end class
Did you add info to mainfest file like this in packages array
'callback' => array(
'path' => 'Your path to php file',
'class' => 'Hotelreservation_Installer',
),
I agree with Arif. Check the file manifest.php inside of //settings:
(info of module Album)
'callback' => array(
'path' => 'application/modules/Album/settings/install.php',
'class' => 'Album_Installer',
),
I had this same issue and got it to work.
It turns out that the installer looks in application/packages/module-yourmodule-x.x.x.json first. around line 35 you'll find:
"callback": {
"path": null,
"class": "Engine_Package_Installer_Module",
"priority": 100
},
change that to:
"callback": {
"path": "application/modules/Yourmodule/settings/install.php",
"class": "Yourmodule_Installer",
"priority": 100
},
now, when you run the installer, your install.php will be called.

CakePHP 2.x Auth with Two Separate Logins

Back in May, I posted this question. I'm trying to do the same thing again on a different app, but I haven't found a solution to this problem. I do have more information and better code, so I'm hoping you guys can help me sort this out.
Use Case:
Doctor's office has a website with admin users. The users login successfully with CakePHP's Auth via User model and UsersController.
Doctors have referring physicians with completely different profiles and actions. Doctors need to login via example.com/physicians/login. However, this login is failing with this
authError => 'You are not authorized to access that location.'
Here is my code in AppController:
class AppController extends Controller {
public $helpers = array('Form', 'Html', 'Time', 'Session', 'Js' => array('Jquery'));
public $components = array(
'Session',
'Auth' => array(
'autoRedirect' => false,
'authorize' => 'Controller'
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view', 'edit', 'display', 'featured', 'events', 'contact', 'signup', 'search', 'view_category', 'view_archive', 'addComment', 'schedule', 'login');
}
}
And here is my UsersController that is working:
class UsersController extends AppController {
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array(
'username' => 'username',
'password' => 'password'
)
)
),
'loginRedirect' => array('controller' => 'users', 'action' => 'admin'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index'),
'loginAction' => array('controller' => 'users', 'action' => 'login'),
'sessionKey' => 'Admin'
)
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'login', 'logout');
}
function isAuthorized() {
return true;
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->Session->destroy();
$this->redirect($this->Auth->logout());
}
Here is my PhysiciansController code that is NOT working:
class PhysiciansController extends AppController {
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'Physician',
'fields' => array(
'username' => 'username',
'password' => 'password'
)
)
),
'loginRedirect' => array('controller' => 'physicians', 'action' => 'dashboard'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index'),
'loginAction' => array('controller' => 'physicians', 'action' => 'login'),
'sessionKey' => 'Physician'
)
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->authorize = array(
'Actions' => array(
'userModel' => 'Physician',
'actionPath' => 'physicians'
)
);
$this->Auth->allow('login', 'logout');
// $this->Session->write('Auth.redirect','/physicians/index');
}
function isAuthorized() {
return true;
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect(array('controller' => 'physicians', 'action' => 'dashboard'));
} else {
$this->Session->read();
debug($this->Auth);
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->Session->destroy();
$this->redirect($this->Auth->logout());
}
I really don't want to start over and switch to ACL -- I'm not sure that's necessary for just two logins. Help would be very much appreciated!
EDIT: Joshua's answer below is awesome and super helpful. I implemented it, but I'm still receiving an unauthorized error when I try to login as a Physician via /phys/physican/login (prefix/controller/action). The Admin setup works great. Here's the debug code when I try to login:
object(AuthComponent) {
components => array(
(int) 0 => 'Session',
(int) 1 => 'RequestHandler'
)
authenticate => array(
'Form' => array(
'userModel' => 'Physician'
)
)
authorize => false
ajaxLogin => null
flash => array(
'element' => 'default',
'key' => 'auth',
'params' => array()
)
loginAction => array(
'controller' => 'physicians',
'action' => 'phys_login'
)
loginRedirect => null
logoutRedirect => '/'
authError => 'You are not authorized to access that location.'
allowedActions => array()
request => object(CakeRequest) {
params => array(
'prefix' => '*****',
'plugin' => null,
'controller' => 'physicians',
'action' => 'phys_login',
'named' => array(),
'pass' => array(),
'phys' => true,
'_Token' => array(
'key' => 'ad1ea69c3b2c7b9e833bbda03ef18b04079b23c3',
'unlockedFields' => array()
),
'isAjax' => false
)
data => array(
'Physician' => array(
'password' => '*****',
'username' => 'deewilcox'
)
)
query => array()
url => 'phys/physicians/login'
base => ''
webroot => '/'
here => '/phys/physicians/login'
}
response => object(CakeResponse) {
}
settings => array()
}
OK I've got a way to do it. You know about prefix routing? If not, read my answer here: CakePHP/MVC Admin functions placement That answer describes how to set up a single routing prefix ('admin'). But you can have any number - just like this:
Configure::write('Routing.prefixes', array('admin','phys','member','user'));
// now we have admin, phys, member and user prefix routing enabled.
What you can do is have all the doctor's methods use 'admin' prefix routing, and all the physicians methods use 'phys' prefix routing.
So the below is code I've hacked together pretty quickly, so it might not be perfect but it should show the concept. Here it is in pseudo code for the before filter method of your app controller:
if (USER IS TRYING TO ACCESS AN ADMIN PREFIXED METHOD) {
Then use the users table for auth stuff
} else if (USER IS TRYING TO ACCESS A PHYS PREFIXED METHOD) {
Then use the physicians table for auth stuff
} else {
It's neither an admin method, not a physicians method. So just always allow access. Or always deny access - depending on your site
}
Here's my app controller code:
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array('Security','Cookie','Session','Auth','RequestHandler');
public $helpers = array('Cache','Html','Session','Form');
function beforeFilter() {
if ($this->request->prefix == 'admin') {
$this->layout = 'admin';
// Specify which controller/action handles logging in:
AuthComponent::$sessionKey = 'Auth.Admin'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session
$this->Auth->loginAction = array('controller'=>'administrators','action'=>'login');
$this->Auth->loginRedirect = array('controller'=>'some_other_controller','action'=>'index');
$this->Auth->logoutRedirect = array('controller'=>'administrators','action'=>'login');
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'User',
)
);
$this->Auth->allow('login');
} else if ($this->request->prefix == 'phys') {
// Specify which controller/action handles logging in:
AuthComponent::$sessionKey = 'Auth.Phys'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session
$this->Auth->loginAction = array('controller'=>'users','action'=>'login');
$this->Auth->logoutRedirect = '/';
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Physician',
)
);
} else {
// If we get here, it is neither a 'phys' prefixed method, not an 'admin' prefixed method.
// So, just allow access to everyone - or, alternatively, you could deny access - $this->Auth->deny();
$this->Auth->allow();
}
}
public function isAuthorized($user){
// You can have various extra checks in here, if needed.
// We'll just return true though. I'm pretty certain this method has to exist, even if it just returns true.
return true;
}
}
Note the lines:
AuthComponent::$sessionKey = 'Auth.Admin'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session
and
AuthComponent::$sessionKey = 'Auth.Phys'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session
What that does is allows a person to be logged in as both a physician, and an admin, in the one browser, without interfering with each other's session. You may not need it in the live site, but it's certainly handy while testing.
Now, in you're respective controllers, you'll need straight-forward login/logout methods, with the appropriate prefix.
So, for admin prefixing, in your users controller:
public function admin_login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
public function admin_logout() {
$this->Session->setFlash('Successfully Logged Out');
$this->redirect($this->Auth->logout());
}
And in your physicians controller:
public function phys_login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
public function phys_logout() {
$this->Session->setFlash('Successfully Logged Out');
$this->redirect($this->Auth->logout());
}
Like I said, that all code I hacked together pretty quickly, so it might not work verbatim, but it should show the concept. Let me know if you have any questions.
Instead of
$this->Session->write('Auth.redirect','/physicians/index');
you should use
setcookie("keys", value);