This is my first attempt at a laravel package and have run into an issue where Auth::attempt($credentials) works within my login controller, but upon redirection to a protected route or controller, the user is no longer authenticated. Below is my login controller method with the redirect to dashboard commented out.
public function attempt(Request $request){
$email = strtolower(strip_tags(htmlspecialchars($request->input('email'))));
$password = strip_tags(htmlspecialchars($request->input('password')));
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
// Redirect to dashboard route
//return redirect()->intended('/admin');
if(Auth::check())
print_r(Auth::user());
}
}
A response to valid credentials prints out the correct user record and Auth::check returns true. But, when redirected to the admin controller, the user is not authenticated. Below is the admin controller method that should output the authenticated user, but only returns "not logged".
public function index()
{
if(Auth::check()) print_r(Auth::user());
else echo "not logged";
}
Both controllers use Auth;, their namespaces are consistent with vendor/package/pathToDir, db is setup correctly, and the encryption key has been set. Any ideas on what's going wrong? Thanks
Turns out the issue was with the new web middleware, moved all my routes that require session data in to the route group and everything works as normal.
Route::group(['middleware' => ['web']], function () {
Route::get("/login", ['uses'=>'SiteLogin#index']);
Route::post("/login", ['uses'=>'SiteLogin#attempt']);
Route::get("/logout", ['uses'=>'SiteLogin#logout']);
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
Route::get('/', ['uses'=>'Admin#index']);
});
});
The default behavior of the method attempt is to not keep the user logged.
You should change it to:
if (Auth::attempt(array('email' => $email, 'password' => $password), false, true))
This way you will set remember as false and login as true.
Check more about this here: https://laravel.com/docs/5.2/authentication
Related
(I'm aware that the following example isn't safe)
I have a basic authentication system where a user has to enter his credentials. When the entered credentials are correct I set in my laravel application a session, which indicates that he can perform authenticated requests to the api. I do that the following way:
public function authenticate(Request $request){
$data = array(
'name' => $request->input('UserName'),
'password' =>$request->input('Password'),
'email' => 'test#test.ch'
);
If(Auth::attempt($data)){
$request->session()->put('isAuthenticated',true);
$request->session()->save();
return "success";
}
return "wrong";
}
My middleware where I check if the user is allowed to make requests:
public function handle($request, Closure $next){
if(!empty($request->session()->get('isAuthenticated')) && $request->session()->get('isAuthenticated') === true){
return $next($request);
}
return redirect('/');
}
My routes:
Route::post('/login', 'UserController#authenticate');
Route::group(['middleware' =>['web','check_auth']], function (){
Route::get('/logs','LogController#getAllLogEntries');
Route::get('/logs/{id}','LogController#getLogEntryById');
});
My problem:
Whenever a user logs in with the right credentials the server returns "success" as response, but always directs me back to the base root ('/'). That makes me assume that the session doesn't get set. How can I fix this error?
I've read the laravel 5 documentation https://laravel.com/docs/5.3/authentication to see how i can implement a way to keep users logged in.
But somehow with the code below my function Auth::viaRemember() always returns false. Also after browser restart. However in my database remember_token is set and so is my cookie.
I'm a bit confused right now, can someone explain what probably is happening?
This function is called to login the user
public function doLogin()
{
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata, true)) {
return Redirect::to('aview');
// validation successful!
}
}
This function is called to check logged in user by Auth::viaRemember()
public function checkLogin()
{
if (Auth::viaRemember()) {
return Redirect::to('aview');
} else {
return view('toaview');
}
}
Additional routes file (just in case)
Route::group(['middleware' => ['web']], function () {
Route::get('login', 'UserController#checkLogin');
});
I'm trying to pass a username and password from a form into a controller, check if that user exists (users database table), and then redirect to an authenticated page where only users that are logged in can see their username.
In my routes.php:
$app->post('/', ['uses' => 'AuthenticationController#login']);
$app->group(['middleware' => 'auth'], function ($app) {
$app->post('/tickets', ['uses' => 'TicketsController#getTickets']);
});
Then my AuthenticationController.php login function:
public function login(Request $request) {
$credentials = $request->only(['username','password']);
$user = App\User::find($credentials);
if ($user) {
// I'm assuming you do a redirect() here but am unsure how with Auth
} else {
return 'not logged in';
}
}
At this point, I don't know what I need to put into my getTickets function in my TicketsController.php.
Anyone that knows how to go about doing this, please throw me a bone as to how to proceed.
Ultimately, it'll be great to have the tickets.blade.php view to have {{ user->username }} and to display the username of who's logged in. If the user doesn't log in and visits this view, nothing displays because they're not authenticated.
EDIT: Currently, I'm getting this error:
FatalErrorException in AuthenticationController.php: Class
'App\Http\Controllers\App\User' not found
I do have both of these lines included in my AuthenticationController.php before all functions begin:
use App\User;
use Auth;
Maybe it's the way I'm passing my $credentials into the find function, but that doesn't solve the Authentication side of things.
I'm using Laravel 5.2. I want to check user session in routes file, so that if session is set user can visit dashboard otherwise redirect to login page.
I have used following code for this but it's not working. It's not giving any error and not redirecting him to login page. anyhow if I write same code in controller functioin, it works fine.
Route::group(['middleware' => ['web']], function () {
Route::get('dashboard/index', ['uses' => 'DashboardController#index'], function() {
$value = $request->session()->get('name', 'not_loggin');
if ($value == 'not_loggin') {
return redirect('/user/login');
}
});
});
it also didn't worked if I write it in constructor.
You should use the auth middleware:
Route::get('dashboard/index', [
'middleware' => 'auth',
'uses' => 'DashboardController#index'
]);
I create middleware for an admin role using the following code:
php artisan make:middleware AdminMiddleware
After that, I create a route for the login page:
Route::get('admin/login', ['middleware'=>'web','as'=>'admin.login','uses'=>'AdminController#loginView']);
Route::post('admin/login',['middleware'=>'web','as'=>'admin.login','uses'=>'AdminController#login']);
Route::group(['prefix'=>'admin','middleware' => ['auth.admin','web']], function()
{
Route::get('/', ['as'=>'admin.home','uses'=>'AdminController#index']);
Route::get('/home', ['as'=>'admin.home','uses'=>'AdminController#index']);
});
And the controller is
class AdminController extends Controller
{
//
function index(){
return 'welcome';
}
function loginView(){
return view('admin.login');
}
function login(Request $request){
$error = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:5',
]);
$email = $request->input('email');
$password = $request->input('password');
$remember = $request->input('remember');
if (Auth::attempt(['email' => $email, 'password' => $password,'type'=>'admin'], $remember)) {
// Authentication passed...
Auth::login(Auth::user(), $remember);
return redirect()->route('admin.home');
}
else{//('message', 'Login Failed')
return redirect()->route('admin.login')->withErrors($request->all(), "message")->withInput();
}
}
}
And in AdminMiddleware
public function handle($request, Closure $next)
{
var_dump(Auth::user());
if(!Auth::check()){
return redirect()->route('admin.login')->withErrors('You are not logged in');
}
elseif ($request->user()->type != 'admin'){
dd($request->user());
return redirect()->route('admin.login')->withErrors('You have not authority');
}
return $next($request);
}
The error is: I always get null for each $request->user() or Auth:user in AdminMiddleware.
You're passing the middleware to the route group in an incorrect order.
Right now you have this order ['auth.admin', 'web'] which means that the auth.admin middleware will be executed before the middleware from the web group, and since web contains the StartSession middleware, you won't have any session in auth.admin which is needed to get the authenticated user.
So simply switch the middleware order like so:
Route::group(['prefix'=>'admin','middleware' => ['web', 'auth.admin']], function () {
// now the session is set up in `web` and then you have it in `auth.admin`
});
In my case the actual problem was a blank line before the PHP starting tag.
I used following core PHP function to redirect instead of returning a view file from controller or instead of using Laravel redirect.
header('Location: /');
It printed the actual file which had a blank line. Removing this line fixed my problem.
There were thousands of files in my code base. My assumption was that I had tried different scripts to find such blank lines at start of any file and there was no such file as per those scripts results. I assumed there was no blank line in any of my files. But header('Location: /') proved that my assumption was not wrong, and I was working on the wrong lines.