Could not send email: unknown Cake\Network\Exception\SocketException in cakephp3 - cakephp-3.0

Okay I have been to almost all threads but I couldn't find the answer what I want.
Controller: RegistersController
namespace App\Controller;
use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Event\Event;
use Cake\Mailer\Email;
use Cake\Routing\Router;
class RegistersController extends AppController
{
public function add()
{
$this->loadModel('Tbusers');
$tbusers = $this->Tbusers->newEntity();
if ($this->request->is('post'))
{
$tbusers = $this->Tbusers->patchEntity($tbusers, $this->request->data);
if ($this->Tbusers->save($tbusers)) {
$this->Flash->success(__('Yayie! You have been registered.'));
$baseurl = Router::url('/', true);
$email = base64_encode($this->request->data['email']);
$first_name = $this->request->data['fname'];
$last_name = $this->request->data['lname'];
$username = $first_name.' '.$last_name;
//$confirmation_link = $baseurl.'users/confirm/'.$email;
$email = new Email();
$email->template('email')
->subject('Student Portal - Signup')
->emailFormat('html')
->to($this->request->data['email'])
//->viewVars(['confirmation_link' => $confirmation_link,'username'=>$username])
->viewVars(['username'=>$username])
->from('dotnetdev555#gmail.com')
->send();
if ($email->send())
{
// Success
echo "mail sent";
}
else
{
echo "Mail not sent";
// Failure
}
return $this->redirect(['action' => 'add']);
}
}
Inside Template->Email->html I have file called
email.ctp
Hello <?php echo $username; ?>,<br/>
Thanks,<br/>
Jaymin Sejpal Founder at Student Portal
app.php
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
I don't know what I am missing to it. I am refferring this
http://book.cakephp.org/3.0/en/core-libraries/email.html for now.

The email host that you are using might be using smtp protocol , so in your app.php . Try editing you className parameter to 'Smtp'
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],

Related

yii2-formwizard change model after select2 selection

I'm trying to implement a multiple models form using the form-wizard widget, with Profile as main model and few others as linked ones. When I select the entity type field for the main model, I would like to change the linked model for the next step, basing on the value of entity type field.
I have tried with this code:
Create Form Code
$modelUrlReletedModelsCreate = Profile::urlRelatedModelCreate();
$urlLinkedProfile = Url::to(['create']);
echo FormWizard::widget([
'formOptions'=>[
'id'=>'profile_form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'validationUrl' => Url::to(['profile-models-validation'])
],
'theme' => FormWizard::THEME_MATERIAL_V,
'steps' => [
//step 1
[
'model' => $model,
'title' => \Yii::t('app', 'Profile'),
'fieldConfig' => [
'only' => ['entity_type_id', 'profile_type_id'],
'entity_type_id' => [
'widget' => Select2::class,
'options' => [
'data' => EntityType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element')],
'pluginEvents' => ['select2:select'=>'function(e){;'
. 'var type = $("#pr-ty-sel").val();'
. 'var profile= "'.($model->profile_id ? : "no").'";'
. '$.ajax({ method: "GET",'
. 'url:"'.$urlLinkedProfile.'",'
. 'data:{ entity_text : e.params.data.text,'
. 'entity_id : e.params.data.id,'
. 'profile_type_id : type,'
. 'profile_id : profile},'
. 'success: function(data){'
. '$("#profile_form").html(data);'
. '}'
. '});}'],
],
],
'profile_type_id' =>[
'widget' => Select2::class,
'options' => [
'data' => \app\models\ProfileType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element'),'id'=>'pr-ty-sel'],
],
]
],
'description' => \Yii::t('app', 'Add Profile Type Data'),
'formInfoText' => \Yii::t('app', 'Fill all fields'),
],
//step 2 I want ot change here $linkedModel
[
'model' => [$model,$linkedModel],
'title' => \Yii::t('app', 'Personal Data'),
'description' => \Yii::t('app', 'Insert Personal Data'),
],
]
]);
Controller Action Create Code
public function actionCreate($profileId = NULL)
{
if($profileId AND $profileId !== 'no'){
$model = $this->findModel($profileId);
}else{
$model = new Profile();
}
$profileLinkedModel = new ProfilePrivate();
$renderMethod = 'render';
if (Yii::$app->request->isAjax) {
$entityText = \Yii::$app->request->get('entity_text');
$entity_id = \Yii::$app->request->get('entity_id');
$profileTypeId = \Yii::$app->request->get('profile_type_id');
$profileId = \Yii::$app->request->get('profile_id');
//Utility function to clean the entity text (remove number and special characters)
$entityTextCleaned = \app\components\Utility::cleanString($entityText);
if ($entityTextCleaned == 'private') {
$profileLinkedModel = new ProfilePrivate();
} elseif ($entityText == 'company') {
$profileLinkedModel = new ProfileCompany();
} else {
//#TODO
return FALSE;
}
$model->entity_type_id = $entity_id;
$model->profile_type_id = $profileTypeId;
$profileLinkedModel->profile_id = $model->profile_id;
Yii::$app->response->format = Response::FORMAT_JSON;
$renderMethod = 'renderAjax';
}
//extra table field used to enable custom rule in model
$model->createFullProfile = TRUE;
if ($model->load(Yii::$app->request->post())) {
return $this->redirect(['view', 'id' => $model->profile_id]);
}
return $this->$renderMethod('create', [
'model' => $model,
'profileLinkedModel' => $profileLinkedModel,
]);
}
When I select a field for entity type field, the server runs the ajax request on select event, but when it ends the other form field is not more selectable. So, in other words, after the ajax request I'm unable to select the profile type field. If I try to select the profile type field before the entity type field I can go to next step, but load always the default model.

Undefined index: password with JWTAuth

hello I have a problem with the password field to create a user in laravel for a restfullapi
public function store(Request $request)
{
$this->validate($request,[
'user_names' => 'required||string|max:45',
'user_lastnames' => 'required|string|max:45',
'user_email' => 'required|string|email|unique:users,user_email|max:150',
'user_password' => 'required|string|min:6|confirmed',
'user_password_confirmation' => 'required|min:6',
'user_gender' => 'required',
'user_celphone' => 'required|numeric',
'user_origin_country' => 'required|string|max:100',
]);
$user_names = $request->input('user_names');
$user_lastnames = $request->input('user_lastnames');
$user_email = $request->input('user_email');
$user_password = $request->input('user_password');
$user_password_confirmation = $request->input('user_password_confirmation');
$user_gender = $request->input('user_gender');
$user_celphone = $request->input('user_celphone');
$user_origin_country = $request->input('user_origin_country');
$user = new User([
'user_names' => $user_names,
'user_lastnames' => $user_lastnames,
'user_email' => $user_email,
'user_password' => bcrypt($user_password),
'user_gender' => $user_gender,
'user_celphone' => $user_celphone,
'user_origin_country' => $user_origin_country
]);
$credentials = [
'user_email' => $user_email,
'user_password' => $user_password
];
if ($user->save()) {
$token = null;
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json([
'error' => 'El email ó la contraseña son incorrectos'
],404);
}
} catch (JWTAuthException $e) {
return response()->json([
'error' => 'failed_to_create_token',
],404);
}
$user->signin = [
'href' => 'api/v1/user/signin',
'method' => 'POST',
'params' => 'user_email, user_password'
];
$response = [
'success' => 'Usuario creado exitosamente',
'Usuario' => $user,
'token' => $token
];
return response()->json($response, 201);
}
$response = [
'error' => 'Ha ocurrido un error'
];
return response()->json($response,404);
}
I'm testing the application with postman and he tells me this
postman's picture
I have verified the routes and it works, before placing the jwt I saved the data in the db without password problems, thanks in advance

cakephp 3 using for login another model than users auth

I'm trying to make a login from another model and I have an error.
This is my code for Student Model
var $name= 'Student';
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'students',
'action' => 'login',
'plugin' => 'students'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username', //Default is 'username' in the userModel
'password' => 'password' //Default is 'password' in the userModel
)
)
)
)
);
StudentsController looks like
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('login');
}
public function login() {
if($this->Session->check('Auth.Student')){
$this->redirect(array('action' => 'login'));
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid username or password'));
}
}
}
And the AppController is
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
'loginAction' => array('controller' => 'students', 'action' => 'login'),
));
public function beforeFilter(Event $event) {
$this->Auth->authenticate=array (
'loginAction' => [
'controller' => 'Students',
'action' => 'login',
'plugin' => false,
],
'Basic' => ['userModel' => 'Students'],
'Form' => ['userModel' => 'Students']
);
}
And I have the following error
Component class SessionComponent could not be found.
How can I fix it?
Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,
$this->loadComponent('RequestHandler');
OR
public $components = array(
'RequestHandler'
);
then use,
$this->request->Session()->read/write/delete/destroy();
Hope this will work for you :).

Yii2 Mailer isn't actually sending emails

I followed a Yii2 tutorial for sending e-mails with attachment,
(See the link below if you need)
https://www.youtube.com/watch?v=c5pebmTUQjs&index=21&list=PLRd0zhQj3CBmusDbBzFgg3H20VxLx2mkF
And it worked on a level that the system reads the email info and the attachment that I want to send, and saves the info and attachment link in the db.
But when I tried to send emails to a real recipient and changed the mailer config, then tried to create a new email
there was a problem:
Invalid Configuration – yii\base\InvalidConfigException
Setting unknown property: Swift_MailTransport::host
Here is the config for mailer:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'useFileTransport' => false,
'transport' => [
'host' => 'smtp.live.com',
'username' => 'username#live.com',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
]
],
And here is the actionCreate part of the EmailsController:
public function actionCreate()
{
$model = new Emails();
if ($model->load(Yii::$app->request->post()))
{
$model->attachment= UploadedFile::getInstance($model,'attachment');
if ($model->attachment)
{
$time=time();
$model->attachment->saveAs ('attachments/' .$time.'.' .$model->attachment->extension);
$model->attachment='attachments/'.$time.'.'.$model->attachment->extension;
}
if ($model->attachment)
{
$value= Yii::$app->mailer->compose()
->setFrom (['sharqpress#hotmail.com'=>'Al-Sharq Printing Press'])
->setTo ($model->reciever_email)
->setSubject ($model->subject)
->setHtmlBody ($model->content)
->attach ($model->attachment)
->send();
}
else
{
$value= Yii::$app->mailer->compose()
->setFrom (['sharqpress#hotmail.com'=>'Al-Sharq Printing Press'])
->setTo ($model->reciever_email)
->setSubject ($model->subject)
->setHtmlBody ($model->content)
->send();
}
$model->save();
return $this->redirect(['view','id'=>$model->id]);}
else
return $this -> render('create',['model'=>$model,]);
}
Your configuration needs additional class:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport', // <-- here
'host' => 'smtp.live.com',
'username' => 'username#live.com',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
]
],

How to check current password in cakephp 3.x from model?

How to check current password is correct from cakephp model. I've searched a lot but not found any details information.
The solution in this post worked for me. Just don't forget to add the use Cake\Auth\DefaultPasswordHasher; at the top of your UsersTabel model.
I found something very useful for checking the current password on http://base-syst.com/password-validation-when-changing-password-in-cakephp-3/ .
Insert this in your template(change_password.ctp):
<div class="users form large-9 medium-9 columns">
<?= $this->Form->create() ?>
<fieldset>
<?= $this->Form->input('current_password', ['type' => 'password', 'label'=>'Current Password', 'value' => ''])?>
<?= $this->Form->input('password', ['type'=>'password' ,'label'=>'Password', 'value' => '']) ?>
<?= $this->Form->input('confirm_password', ['type' => 'password' , 'label'=>'Repeat password', 'value' => ''])?>
</fieldset>
<?= $this->Form->button(__('Save')) ?>
<?= $this->Form->end() ?>
Insert this in your (Users)Table, for validation:
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
public function validationDefault(Validator $validator )
{
$validator
->add('current_password','custom',[
'rule'=> function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if ((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message'=>'The old password does not match the current password!',
])
->notEmpty('current_password');
$validator
->add('password', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The password have to be at least 6 characters!',
]
])
->add('password',[
'match'=>[
'rule'=> ['compareWith','confirm_password'],
'message'=>'The passwords does not match!',
]
])
->notEmpty('password');
$validator
->add('confirm_password', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The password have to be at least 6 characters!',
]
])
->add('confirm_password',[
'match'=>[
'rule'=> ['compareWith','password'],
'message'=>'The passwords does not match!',
]
])
->notEmpty('confirm_password');
return $validator;
}
Insert this in your (Users)Controller:
public function change_password() {
$user = $this->Users->get($this->Auth->user('id'));
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}