SSL cake PHP form - ssl

I spent the site in https, I have 2 questions, the site is redirected but is it a 301 redirect? I did not write anything in the .htaccess file, how come the site is redirected in https?
I'm afraid of dupicate content.
The problem I have is that emails do not work anymore ...
here is the code:
public function initialize()
{
parent::initialize();
$this->loadComponent('Security', ['blackHoleCallback' => 'forceSSL']);
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'finder' => 'auth'
]
],
'loginAction' => ['controller' => 'Users', 'action' => 'login', 'prefix' => 'manager'],
'loginRedirect' => ['controller' => 'Pages', 'action' => 'index', 'prefix' => 'manager'],
'logoutRedirect' => ['controller' => 'Users', 'action' => 'login', 'prefix' => 'manager'],
// 'authorize' => 'Controller'
]);
}
public function forceSSL()
{
return $this->redirect('https://' . env('SERVER_NAME') . $this->request->here);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Security->requireSecure();
$this->checkManager();
$this->set('settings', Configure::read('Settings'));
}
Thank you

here is the solution:
public function initialize()
{
parent::initialize();
$this->loadComponent('Security', ['blackHoleCallback' => 'forceSSL']);
}
public function forceSSL()
{
return $this->redirect('https://' . env('SERVER_NAME') . $this->request->here);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Security->requireSecure();
$this->Security->config('unlockedActions', ['contact']);
}
AND :
Change statut in Controller.php
public function redirect($url, $status = 302)
Becomes :
public function redirect($url, $status = 301)

Related

Cakephp 3 Redirect when session expires

I use the AuthComponent and I want when the session expires and the user press a link or refreshes, to redirect him on the login page.
However for some actions I don't want above redirect, even if user is logged out, as they are used as an API by another application also.
For example, I want to allow the 'view' action for logged-out users, but redirect the 'index' action.
My AppController.php is:
$this->loadComponent('Auth', [
'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginAction' => [
'plugin' => false,
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'index',
'plugin' => 'Pages'
],
'logoutRedirect' => [
'plugin' => false,
'controller' => 'Users',
'action' => 'login'
],
]);
If I add below, 'index' is also working if user is logged-out, even though it should be in deny state.
MyController.php
public function beforeFilter(\Cake\Event\Event $event)
{
$this->Auth->allow('view');
The only way I managed to do what I want is to add it in the controller action as:
MyController.php
public function index()
{
if (empty($this->auth_user['username'])) {
return $this->redirect($this->Auth->logout());
}
Is there a better way to do this?

access to subfolders controller and view in YII2

hi i built a controller in a folder inside controllers folder
i tryed to access my controller and its view but i couldnt always error 404
please tell me what is the problem
here is the details
this is SiteUserController in Controllers/userzone/ folder
namespace app\controllers\userzone;
use yii\web\Controller;
use app\models\UserZone;
/**
* Default controller for the `dashboard` module
*/
class SiteUserController extends Controller
{
/**
* Renders the index view for the module
* #return string
*/
public function actionIndex()
{
$id = \Yii::$app->user->id;
$model = UserZone::find()->where(['id_zone'=>$id])->with('user')->one();
// $model->joinWith('companiesCompany');
return $this->render('siteuser/index',[
'model'=>$model
]);
}
}
the view file is in Views/siteuser/index.php directory .
i changed url manager to
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'userzone/<controller:\w+>/<action:\w+>'=>'userzone/<controller>/<action>',
],
],
In Controller:
return $this->render('index',[
'model'=>$model
]);
Its Working
You need to change you controllerNamespace in config/main file i.e. below code for config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\controllers\userzone', //here is your controller path
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#frontend/views' => '#themes/frontend/views',
],
],
],
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];

Not able to submit form inside footer in Yii2

I've a subscribe newsletter form inside footer that display on all page. To do this I've created a subscriber widget like this:
SubscriberWidget.php
<?php
namespace frontend\components;
use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use frontend\models\SubscribeNewsletterForm;
class SubscriberWidget extends Widget
{
public function run()
{
$subscriber_model = new SubscribeNewsletterForm();
return $this->render('_subscribe-newsletter-form.php', [
'subscriber_model' => $subscriber_model
]);
}
}
?>
Here's the SubscribeNewsletterForm model code:
SubscribeNewsletterForm.php
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
class SubscribeNewsletterForm extends Model
{
public $email;
public function rules()
{
return [
[['email'], 'required'],
['email', 'email']
];
}
}
?>
Here is the code of my _subscribe-newsletter-form.php
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
?>
<h3>Subscribe to Newsletter</h3>
<?php $form = ActiveForm::begin(['id' => $subscriber_model->formName(), 'action' => ['project/subscriber'], 'validateOnBlur' => false, 'validateOnType' => false]); ?>
<div class="input-group">
<?= $form->field($subscriber_model, 'email')->textInput()->label(false); ?>
<span class="input-group-btn">
<?php echo Html::submitButton('Sign Up', ['class' => 'btn btn-primary subscribe-btn']); ?>
</span>
</div>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
$('#{$subscriber_model->formName()}').on('beforeSubmit', function(e){
var form = $(this);
$.post(
form.attr("action"),
form.serialize()
).done(function(data){
form.trigger("reset");
})
return false;
});
JS;
$this->registerJs($script);
?>
Inside ProjectController.php I've created the action as follow:
public function actionSubscriber()
{
$subscriber_model = new SubscribeNewsletterForm();
$request = Yii::$app->request;
if($request->isAjax && $subscriber_model->load($request->post())){
$subscriber = new Subscriber([
'email' => $subscriber_model->email
]);
$subscriber->save();
}
}
Here's the Subscriber model code.
Subscriber.php
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Subscriber extends ActiveRecord
{
public static function tableName()
{
return 'subscriber';
}
}
?>
frontend/config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
?>
With above code validation is working but i'm not able to save the email in database. Please tell what i'm doming wrong.
You need rules on your Model. Also, I always replace the generated tables names with the table prefix supported method. Also, I always like to use the Timestamp behavior to log when things are created or updated. Especially when your grabbing contact info for the use of leads, I would record the timestamps as well as their IP Address.
Subscriber.php
use yii\behaviors\TimestampBehavior;
// ...
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%subscriber}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\Subscriber', 'message' => 'This email address has already been taken.'],
[['created_at', 'updated_at'], 'integer'],
];
}

Laravel 5.4 custom Auth::attempt always return false even my credential is true

I try to create auth::guard('profile') and using profiles table and Profile model but when I tried to do Auth::attempt($credential) it's always returning false even if my credentials is true.
Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('ProfileID');
$table->string('Name');
$table->string('UserId')->unique();
$table->string('Email')->unique();
$table->string('Password');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Profile extends Authenticatable
{
use Notifiable;
protected $fillable =
[
'Name', 'UserId', 'Email', 'Password'
];
public $timestamps = false;
protected $hidden =
[
'Password'
];
}
config\auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'profile' => [
'driver' => 'session',
'provider' => 'profiles'
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'profiles' => [
'driver' => 'eloquent',
'model' => App\Profile::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
ProfileController
public function postLogin(Request $r){
$credential = array(
'UserId' => $r->input('UserId'),
'Password' => $r->input('Password')
);
if(Auth::guard('profile')->attempt($credential)) {
echo "success";
}else{
Session::flash('error', 'Username or password is incorect');
return redirect('/');
}
}
Please help me, I cant find where the problem is.

Authentication in CakePhp 3

I think I got a mistake in the Authorization of my App. I want only to allow to add Pages by users with an admin role. But I can access the add function with no problem. So here is what I did.
AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Moves',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display', 'english', 'italian', 'german']);
$this->Auth->loginAction = array('controller'=>'pages', 'action'=>'home');
$this->loadModel('Menus');
$main_de = $this->Menus->find('all', array(
'conditions' => array('Menus.action' => 'main_de')
));
$this->set('main_de', $main_de);
$main_us = $this->Menus->find('all', array(
'conditions' => array('Menus.action' => 'main_us')
));
$this->set('main_us', $main_us);
}
public function isAuthorized($user)
{
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
Pages
public function isAuthorized($user)
{
// All registered users can add articles
if ($this->request->action === 'add') {
return false;
}
// The owner of an article can edit and delete it
if (in_array($this->request->action, ['edit', 'delete'])) {
$articleId = (int)$this->request->params['pass'][0];
if ($this->Articles->isOwnedBy($articleId, $user['id'])) {
return false;
}
}
return false;
}
I fixed the problem by adding 'authorize' => 'Controller', to the Auth Array
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Moves',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
// **'authorize' => 'Controller',**
]);