More than only one methods to authentication middleware on laravel - php

I am having this on my laravel project and i want to add more methods to the exept array. And i could not figure it out how i should write it?
public function __construct()
{
$this->middleware('auth', [ 'except' => 'index' ]);
}

Just add such an array like that:
public function __construct()
{
$this->middleware('auth', [ 'except' =>['index','fooAction'] ]);
}
You can see more about here: https://laravel.com/docs/5.1/controllers#controller-middleware

try this
public function __construct()
{
$this->middleware('auth', [ 'except' => ['index','home'] ]);
}

Related

Route is redirecting before calling the controller method

I am using Laravel 5.5.40 along with the Zizaco\Entrust Pacakge
In my routes/web.php file i have the following route setup.
Route::group(['prefix' => 'order'], function() {
Route::get('', 'OrderController#getMe');
});
It is supposed to call the getMe() method inside the OrderController.php but it instead redirects to www.mydomain.co.uk/home
namespace App\Http\Controllers;
class OrderController extends Controller
{
public function getMe() {
return "You got me!";
}
}
As a test, I added a __construct function to the OrderController.php to see if the class was even been loaded.
public function __construct() {
dd("Testing");
}
When accessing www.mydomain.co.uk/order i now get
"Testing"
I can't seem to work out why it is not running the getMe() method. Could anyone possibly shine some light on this please?
I have also tried changing the route to use ClientController#list which works fine.
Contents of ClientController.php
namespace App\Http\Controllers;
use App\Client;
class ClientController extends Controller
{
public function __construct() {
//
}
// Display all the clients
public function list() {
$tabContent = [
'display_type' => 'list',
'data' => Client::orderBy('name', 'asc')->get(),
'view_params' => [
'columns' => [
'name' => 'Client Name',
'address_line_1' => 'Address Line 1',
'town' => 'Town',
'county' => 'County',
'post_code' => 'Post Code'
],
'links' => 'client',
'controls' => True
]
];
return view('tables.list', ['data' => $tabContent]);
}
}
It has become apparent that if the controller does not have the constructor function in it, it will automatically redirect to the root of the URI with no error.
public function __construct() {
//
}

use both beforeAction() and behaviors() method in controller in Yii2

I want to use both beforeAction() and behaviors() method in my controller.
If i add beforeAction() method in my code than behaviors() method is not working.
And if i remove beforeAction() method than behaviors() method is working.
I dont want to remove beforeAction() as it is use to disable csrf token for ajax calls.
public function beforeAction($action)
{
if($action->id =='ignore' || $action->id =='accept')
{
$this->enableCsrfValidation = false;
}
return true;
}
And i want to use behaviors() method for authentication.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['create','index','update','change','view','page','active','list'],
'rules' => [
[
'actions' => ['create','index','update','change','view','page','active','list'],
'allow' => true,
'roles' => ['#'],
'matchCallback' => function ($rule, $action)
{
echo "string";
die;
},
],
],
'denyCallback' => function ($rule, $action) {
return $this->redirect(Yii::$app->request->baseUrl);
}
],
];
}
Is there any way to use both method in same controller.
public function beforeAction($action)
{
if($action->id =='ignore' || $action->id =='accept')
{
$this->enableCsrfValidation = false;
}
//return true;
return parent::beforeAction($action);
}
you need to return the parent beforeAction()

Laravel Route Redirection Problems

I'm having problem redirecting my admin page to a Route::resource(); so that I could display my CRUD from the BookController
What am I doing wrong?
This is my AdminLoginController:
public function __construct(){
$this->middleware('guest:admin');
}
public function showLoginForm(){
return view('auth.admin-login');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('books.index'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
BookController
public function index()
{
$books = Book::orderBy('id','desc')->paginate(3);
return view('books.index')->withBooks($books);
}
web.php
Route::prefix('admin')->group(function(){
Route::get('/login','Auth\AdminLoginController#showLoginForm')>name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')>name('admin.login.submit');
Route::get('/books/','BookController#index');
});
I think you should update your books route:
Route::get('/books/','BookController#index')->name('books.index');
OR
Route::group(['prefix' => 'admin'], function () {
Route::resource('/books','BookController#index');
});
and check your route name in php artisan route:list
update your code like:
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('admin.books.index'));
}
Hope this work for you!

Yii2 - How to exclude methods from authenticator behaviors

i am building an API with Yii2 framework, i need to tell yii some actions act as public action.
i added except in my controller's behaviors function but its not works
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'except' => ['NotifyOrder'],
];
return $behaviors;
}
public function actionNotifyOrder() {
echo 1;
}
i am always getting following error when i call my /notify-order url
<response><name>Unauthorized</name><message>Your request was made with invalid credentials.</message><code>0</code><status>401</status><type>yii\web\UnauthorizedHttpException</type></response>
according to the docs you need to tell it the action IDs (the dash-separated format used in urls)
you should have
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'except' => ['notify-order', 'another-action', 'and-so-on'],
];

Yii::configure does not work in module init()

I have a module calls API, and i want to load config file for it. The guide says that i have to use function \Yii::configure. I use it, but it doesn't apply any new configs. And i tried to use array instead config file, the result is same
class API extends \yii\base\Module
{
public $controllerNamespace = 'api\client\controllers';
public function init()
{
parent::init();
// \Yii::configure($this, require(__DIR__ . '/config/main.php'));
\yii::configure($this, [
'components' => [
'user' => [
'class' => 'yii\web\UserTest',
'identityClass' => 'api\client\models\User',
],
]
]);
echo \yii::$app->user->className();
die();
}
}
How I can override config in my module ?
UPDATE
You have to use setComponents method of Yii::$app
Yii::$app->setComponents(
[
'errorHandler'=>[
'errorAction'=>'forum/forum/error',
'class'=>'yii\web\ErrorHandler',
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\modules\profile\models\User',
],
]
);
OLD ANSWER
Didn't it give you errors? Your casing are wrong and so instead of "yii" in small letters use "Yii" capitalized
class API extends \yii\base\Module
{
public $controllerNamespace = 'api\client\controllers';
public function init()
{
parent::init();
\Yii::configure($this, [
'components' => [
'user' => [
'class' => 'yii\web\UserTest',
'identityClass' => 'api\client\models\User',
],
]
]);
echo \Yii::$app->user->className();
die();
}
}
I see no reason to override the application components here. I'd use #StefanoMtangoo trick but to set the component to the Module itself instead of Yii::$app:
public function init()
{
parent::init();
$this->setComponents([
'db' => [
'class' => 'yii2tech\filedb\Connection',
'path' => '#app/builder/data',
]
]);
}
Then the tricky part is to differentiate between any app's components and your module's own components. For example if my Module had a model extending yii\db\ActiveRecord I'd override its getDB() as follow (original code here):
public static function getDb()
{
return Yii::$app->getModule('api')->get('db');
// instead of: return Yii::$app->getDb();
}
So whatever the app that is using my module has or hasn't a db component it won't matter.

Categories