Call to a member function addUnauthenticatedActions() on null (CakePHP Authentication) - authentication

I am trying to implement the CMS Tutorial - Authentication for CakePHP and I am only trying to implement the login page up till now but it is giving me an error on this line
$this->Authentication->addUnauthenticatedActions(['login']);
Error:
Call to a member function addUnauthenticatedActions() on null
UsersController:
public function beforeFilter(\Cake\Event\EventInterface $event){
parent::beforeFilter($event);
// Configure the login action to not require authentication, preventing
// the infinite redirect loop issue
$this->Authentication->addUnauthenticatedActions(['login']);
}
public function initialize() :void{
$this->loadComponent('Flash');
$this->loadComponent('Authentication.Authentication');
}

in your appController use $this->Authentication->addUnauthenticatedActions(['someactions']);
and if you want to use UnauthenticatedActions in your controller you nit to put
public function beforeFilter(EventInterface $event)
{
parent::beforeFilter($event);
$this->Authentication->allowUnauthenticated(['actions']);
}

Related

Get authentication data inside of Constructor issue in Laravel5.3.19

I have upgrade Laravel from 4.2 to laravel5.3 but I can't access Authentication data inside of Constructor of Controller
I have as below Middleware but it never work for me
use App\Http\Controllers\BaseController;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Redirect;
use Auth;
use App\User;
class DashboardController extends BaseController
{
public $user;
public function __construct(Guard $guard, User $user)
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
//$this->userID = Auth::user()?Auth::user()->id:null;
dd($user);// Result attributes: []
dd($guard);
dd($this->user);
}
}
The result after DD()
dd($guard);
DD($this->user);
NULL
It will return Null when I dd user property.
This is to be expected. The reason you have to assign the user inside the middleware closure is because the session middleware hasn't run yet. So, the closure you have above won't actually be called until later in the execution process.
If you move the dd($this->user) to inside the middleware closure or in to your one of you route methods in that controller it should be working absolutely fine.
Also, just FYI, in your middleware closure you can get the user instance from the request i.e. $request->user() will give you the authenticated user.
Hope this help!

Redirect user after login in laravel 5.1

I am trying to implement a feature where, after logging in, a user gets redirected to a URL depending on their role. I have the roles part set up, but I'm having trouble testing the user's properties immediately after login.
I followed the instructions here to create a user login page. I have an AuthController that looks like this:
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/test';
...
}
My __construct() function validates the user, but I don't know how to access the user object only immediately after login. This is what I presently have:
public function __construct() {
$this->middleware('guest', ['except' => 'getLogout']);
if ( \Auth::check() ) {
$user = \Auth::user();
if ( $user->admin() ) {
// an admin
$this->redirectTo = '/admin';
} else {
// it's a client
$this->redirectTo = '/client/dashboard';
}
}
$user = \Auth::user();
if ( is_object($user) ) {
} else {
$this->redirectTo = '/auth-not-object';
}
}
When I first attempt to log in with an administrator account, I get to the path /auth-not-object, because there isn't any authenticated user object at that point.
After having attempted to log in, but getting a bad redirect, when I revisit the /login url, I get redirected to /home, which I believe is the default $redirectTo in the traits this class uses. So that means we've passed the AuthController __construct() method without having changed the $redirectTo, even though there is an authenticated user.
I've found other questions, such as How to add extra logic on login condition in Laravel 5.2 and laravel redirect to url after login, but I don't understand how to apply those answers. For instance, the accepted answer to the second question shows new methods, getCredentials() and login(), which don't exist in the poster's original class. I am not sure in what class to add them, or where to call them from, in my codebase.
Other similar answers show a radically different way of authenticating users, such as this. It seems that, to use that solution, I would need to re-write my code, and forgo the use of the traits, which include bonus features like login throttling and so on.
Is there a way I can redirect users based on role after login, while still using these built-in traits?
Im not sure if the 5.1 auth is the same as the 5.2 auth, but if it is, remove all that from the construct and add this method:
protected function handleUserWasAuthenticated( Request $request, $throttles, $guard )
{
if ($throttles) {
$this->clearLoginAttempts( $request );
}
if ( method_exists( $this, 'authenticated' ) ) {
return $this->authenticated( $request, Auth::guard( $guard )->user() );
}
return redirect()->intended( $this->redirectTo );
}
this is the method that will determine the redirect and you have access to the user object.
EDIT
I take the above back, just add the following to your controller;
protected function authenticated( $request, $user ) {
return redirect()->intended( $user->admin() ? '/admin' : '/client/dashboard' );
}
That should work nicely

LARAVEL 5: Need to keep query string after auth redirects

I have a link I am sending via email. For example, www.swings.com/worker?id=3382&tok=jfli3uf
In this case I want the person to click the link, get sent to the login page(which it does) and then be directed to a controller method WITH the $id and $tok variables. I can't get that part to work. Any ideas? I am only using the RedirectIfAuthenticated class and this is what it looks like:
public function handle($request, Closure $next)
{
$user = $request->user();
if ($this->auth->check()) {
if($user && $user->hasRole('worker'))
{
return redirect('worker');
}
return redirect('home');
}
return $next($request);
}
hasRole is a method I created in the User model that checks the role of the logged in user
You can flash data to the session when redirecting by chaining the with() method:
// in your handle() method:
return redirect('home')->with($request->only('id', 'tok'));
// then in home controller method:
$id = session('id');
$tok = session('tok');
AFTER SOME HOURS I WAS ABLE TO HAVE A SOLUTION:
ReturnIfAuthenticated wasn't changed. I just added the following within my controller that this link should go to:
for instance, the route would be:
Route::get('worker', 'WorkerController#methodINeed');
Within this method:
public function methodINeed() {
$id = Input::get('id');
$tok = Input::get('tok');
// Do what I need this variables to do
}
What I didn't understand and what could not be properly understood is that the auth controller in Laravel 5 is triggered when a user is a guest it will still redirect to the actual method with all its original data once auth is successful. Hope this is helpful.

How to change the redirect url when logging out?

I'm working with Laravel 5 authentification system provided by default.
After logging out, a user is redirected to the root page but I'd like to change that.
I managed to do it for the "login" and "registering" process by defining "$redirectTo" in "AuthController.php". But for "logout", I defined "$redirectAfterLogout" at the same place but it seems to not be taken into account.
Could anyone explain me where is the problem and how to fix it please?
Thanks a lot.
For Laravel 5,
Open AuthController class : app/Http/Controllers/Auth/AuthController.php
Add below property to the class
protected $redirectAfterLogout = 'auth/login';
you can change auth/login with any url.
The redirect after logout is hard coded in the trait AuthenticatesAndRegistersUsers. You can override it in your AuthController by adding this:
public function getLogout()
{
$this->auth->logout();
return redirect('logout');
}
If you don't provide the $redirectAfterLogout attribute, it will use the default which is '/'.
This logic can be found in this class: \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
Having said that, just add this attribute in your AuthController:
protected $redirectAfterLogout = '/afterRedirectURL';
For Laravel 5.5 override logout method inside LoginController. In my case I am redirecting to home route after login.
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect()->route('home');
}
using the built in laravel Auth in the controllers I just override the loggedOut method which triggers after logout to redirect
in the "LoginController.php" which uses
use AuthenticatesUsers;
in the AuthenticatesUsers Trait is a logout method, you can optionally override this or you will see that it triggers a loggedOut method
You can override the logged out method which is default blank and have that redirect
/**
* The user has logged out of the application.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
protected function loggedOut()
{
return redirect()->route('login.show');
}
In App\Controllers\Auth\AuthController, add the following two variables.
protected $redirectTo = '/private_dashboard';
protected $redirectAfterLogout = '/public_homepage';
You get the idea.
I have a same problem in Laravel 5.0. Override a method does the trick.
1) Go to app/Http/Controllers/Auth/AuthController.php
2) Add a new method :
// Override Logout method (define custom url)
public function getLogout()
{
$this->auth->logout();
return redirect('auth/login'); // Your Custom URL
}
it'only laravel versi 5.4 if you want custom redirect url logout,
open /your-project-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
and edit redirect based on you needed
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}

Yii Rest api url manager

I am not able to find the logic behind the url manager. Can any body tell me about the given url calling in Rest pattern. I have too many get methods in my Controller with single parameter.
This is my Original url : localhost/project/api/event/getevent/event_id/1
api is Module
event is Controller
getevent is Controller action name
event_id is parameter 1
I want to convert this to Rest pattern localhst/project/api/event/1
//Updated code..
all are related to same Model..............
//Search by Event id
public function actionByEventId(){
$model->byEventId();
}
//Retrieve user's events by User id
public function actionByUserId()
{
$model->userEvents();
}
//Search for event by code
public function actionByEventcode()
{
$model->byEventCode();
}
Add this rule:
'api/<controller:\w+>/<action:\w+>/<id:\d+>' => 'api/<controller>/by<action>'
And add the $id your actions:
public function actionByEventId($id) {
}
public function actionByUserId($id) {
}
Now if you call localhst/project/api/event/eventid/1 Yii will call the actionByEventId in your event-Controller with $id as 1