Laravel 5 viaRemember() always false - php

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');
});

Related

session for authenticated user is not being set

(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?

Laravel didn't remember login

I use the manual authentication in Larave, here is my function of code
public function doLogin(){
// create our user data for the authentication
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata,true)) {
return (Auth::check() ? 'true' : 'false');
}
else {
// validation not successful, send back to form
return (Auth::check() ? 'true' : 'false');
}
}
After logging in, the Auth::check returned true. But after browsing to protected routes, which have this construct function
public function __construct()
{
$this->middleware('auth');
}
the middleware redirects me to the login page again, even after login.
Auth middleware has never been modified. Are there any modifications I needed to do?
I also tried my custom middleware:
class LoginCheck
{
public function handle($request, Closure $next)
{
if (!Auth::check()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('login');
}
}
return $next($request);
}
}
Still not working, means Auth::check() is returning false.
Cookies are configured to store session, and still not working, too.
This is weird, but...
I created a new Laravel project. Copied all the MVC and routes (only that) but excluding everything about auth. Then I did php artisan make:auth, and it worked, and I have literally no idea why.
Seems like I must have messed with something really, bad.
By the way, thanks for all the help!

I get Auth::user is null in Laravel

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.

User Auth not persisting within Laravel package

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

Laravel PHP: Using Filters with Routes to grant admin access only

I'm trying to protect some of my web pages by only allowing administrators to access them. I've been trying to use a filter to protect these pages but it isn't working as intended. For instance, if a user tries to enter an admin URL into their web browser, the browser still grants the unauthorized user access.
EDIT: Made changes to my code below so that the admin pages are only accessed after successfully logging in.
Routes.php:
// All users have access to this home page
Route::get('/', ['as' => 'home', function()
{
// Default home page
return View::make('index');
}
]);
//Admin access only
Route::get('admin/index', ['before' => 'auth',function()
{
//Only allow admin access to this page
return View::make('admin_index');
}
]);
filters.php (The default filters.php file):
/* Default 'filters.php' is fine. */
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Controller (SesssionsController.php):
public function index()
{
return View::make('sessions.index');
}
/*
Show the form for creating a new resource
*/
public function create()
{
return View::make('sessions.create');
}
public function store()
{
// validate
$input = Input::all();
$attempt = Auth::attempt([
'email'=> $input['email'],
'password' => $input['password']
]);
// If authentication passes, take the user back to the homepage (For Now)
/* EDIT: Changed 'Redirect::intended(admin/index)' to 'Redirect::to('admin/index')... since that was giving me problems */
if ($attempt) return Redirect::to('admin/index')->with('flash_message', 'Welcome ' . $input['email']. ', you are logged in!');
return Redirect::back()->with('flash_message', 'Invalid credentials.')->withInput();
}
After making these changes, I ran 'php artisan dump-autoload' in order for the changes in my Controller to take effect and now my 'admin/index' page can only be accessed after successfully logging in.
Hope this information helps people out!

Categories