I have a problem with the cookie session driver. I need to create an app that works with only cookies. With my configuration, the session is not persisting in Laravel 5.2 with the cookie driver. If I use the file session driver, it works.
.env file:
SESSION_DRIVER=cookie
I also created a middleware that checks if a custom session value exists (only handle() function):
public function handle($request, Closure $next)
{
//dd(session('auth')) // null
if (!session('auth')) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('/');
}
}
return $next($request);
}
I added the middleware to the $routeMiddleware array in app/Http/Kernel.php:
'cookies' => \App\Http\Middleware\CheckCookies::class,
My routes are:
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'LoginController#index');
Route::post('login', 'LoginController#login');
Route::group(['middleware' => 'cookies'], function () {
Route::get('home','HomeController#index');
Route::get('logout','HomeController#logout');
});
});
Here's my LoginController#login method:
public function login()
{
session([
'auth' => ['name' => 'John Doe']
]);
return redirect('/home');
}
How can I fix this?
Just use Cookie Facades in laravel.
Cookie::queue('key', 'value', $minutes);
To make cookie forever
Cookie::forever('key', 'value');
Modify your code and try this.
LoginController#login
public function login(){
$cookieValue=json_encode(array('name'=>'John Dow'));
Cookie::queue('auth', $cookieValue, 60);
return redirect('/home');
}
CheckCookies Middleware
public function handle($request, Closure $next){
if (!Cookie::get('auth'))
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('/');
}
return $next($request);
}
}
Related
But when authentication was success, it shown error Route [/db1] not defined. I hace declared db1 route, but this route can access only if user has session. Anyone can tell me what wrong with my code?
this is my route:
Route::group(['middleware' => ['userSession']], function() { Route::get('/db1', [WasteController::class, 'db1'])->name('db1'); });
this is my kernel in middlewareGroup:
'userSession' => [ \App\Http\Middleware\CheckUserSession::class, ],
this is my middleware:
public function handle($request, Closure $next) {
if ($request->session()->get('status') != 'true') {
//status user cannot be found in session
return redirect('/');
}
return $next($request);
}
i have tried but it show error db1 route not defined
Did you try this?
public function handle($request, Closure $next) {
if ($request->session()->get('status') = 'true') {
//status user cannot be found in session
return $next($request);
}
return redirect('/');
}
Web.php
Route::group(['middleware'=>'auth:admin'], function(){
Route::resource('dashboard', 'DashboardController');
Route::group(['prefix'=>'users','namespace'=>'User','as'=>'u.'], function(){
Route::resource('list', 'ListController');
Route::resource('segments', 'SegmentController');
});
Route::group(['prefix'=>'sales','namespace'=>'Sales','as'=>'s.'], function(){
Route::resource('credits', 'CreditController');
Route::resource('packages', 'PackageController');
});
});
RedirectIfAuthenticated
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard)
{
if(Session::has('admin_session')){
return redirect('admin/dashboard');
}
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
return $next($request);
}
}
AuthController
public function login(Request $request)
{
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/firebaseKey.json');
$firebase= (new Factory)->withServiceAccount($serviceAccount)->create();
$this->database = $firebase->getDatabase();
$auth = $firebase->getAuth();
// if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
// return redirect('admin/dashboard');
// }
try {
if($user = $auth->verifyPassword($request->email,$request->password)){
Session::put('admin_session',$user);
return redirect('admin/dashboard');
}
} catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) {
echo 'wrong password'; die();
} catch (\Kreait\Firebase\Auth\SignIn\FailedToSignIn $e) {
echo 'invalid email'; die();
}
}
How to put only session authentication on above-mentioned routes?
As I want to put firebase authentication so laravel's wouldn't work here,
So I just want to implement simple isset(session('admin_session')) functionality which will be common for all routes...
Anyone, please suggest me how to implement it... it keeps redirecting!
Change the middleware group to a new middleware name:
Web.php
Route::group(['middleware'=>'role'], function(){ //or the name you want to use
Route::resource('dashboard', 'DashboardController');
Route::group(['prefix'=>'users','namespace'=>'User','as'=>'u.'], function(){
Route::resource('list', 'ListController');
Route::resource('segments', 'SegmentController');
});
Route::group(['prefix'=>'sales','namespace'=>'Sales','as'=>'s.'], function(){
Route::resource('credits', 'CreditController');
Route::resource('packages', 'PackageController');
});
});
Create a new middleware by php artisan make:middleware Role :
Role.php (Middleware)
<?php
namespace App\Http\Middleware;
use Session;
use Closure;
class Role
{
public function handle($request, Closure $next)
{
if(Session::has('admin_session')) {
return $next($request);
}
return redirect()->route('login');
}
}
Modify the RedirectIfAuthenticated middleware to this:
RedirectIfAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Session::has('admin_session')) {
return redirect('admin/dashboard');
}
return $next($request);
}
}
Modify AuthController to this:
AuthController.php
public function login(Request $request)
{
if ($auth = $this->firebase->getAuth()) {
try {
$user = $auth->verifyPassword($request->email, $request->password);
Session::put('admin_session',$user);
return redirect('admin/dashboard');
}
catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) {
return back(); // code for wrong password
}
catch (\Kreait\Firebase\Auth\SignIn\FailedToSignIn $e) {
return back(); //code for user doesn't exists
}
}
return back(); // something went wrong
}
how to create middleware redirect about role. I have 2 middleware, first Admin, next User. Need redirect after login, if role Admin, example redirect to /admin, if User redirect to /user.
Admin middleware:
if(Auth::check() && Auth::user()->isRole() == "Admin"){
return $next($request);
}
return redirect('login');
User middleware:
if(Auth::check() && Auth::user()->isRole() == "User"){
return $next($request);
}
return redirect('login');
WEB routes
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'DashboardController#index');
Route::group(['middleware' => ['auth' => 'admin']], function (){
Route::resource('/admin', 'AdminController');
});
Route::group(['middleware' => ['auth' => 'user']], function (){
Route::resource('/user', 'AdminController');
});
});
You can make your admin/user middleware to inherit laravel's Authenticate middleware: Illuminate\Auth\Middleware\Authenticate, then have their definitions as below.
Admin Middleware-
public function handle($request, Closure $next, ...$guards)
// Ensure auth - this will automagically re-direct if not authed.
$this->authenticate($request, $guards);
if(Auth::user()->isRole() == "Admin")
return $next($request);
return redirect('/user-default-page')
}
// You can define this for your un-authenticated redirects
protected function redirectTo($request)
{
return '/login';
}
User middleware will then be:-
public function handle($request, Closure $next, ...$guards)
// Ensure auth - this will automagically re-direct if not authed.
$this->authenticate($request, $guards);
if(Auth::user()->isRole() == "User")
return $next($request);
return redirect('/admin-default-page')
}
// You can define this for your un-authenticated redirects
protected function redirectTo($request)
{
return '/login';
}
For routes:
Route::group(['middleware' => 'admin'], function () {
// Put here admin routes, e.g
Route::resource('/admin', 'AdminController');
}
Route::group(['middleware' => 'user'], function () {
// Put here user routes, e.g
Route::resource('/users', 'UserController');
}
// You can still use the default auth routes, say for routes that (somehow), both admin and user can access
Route::group(['middleware' => 'auth'], function () {
Route::resource('/dashboard', 'DashboardController');
}
// Admin Middleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id == 1)
{
return $next($request);
}else {
return redirect()->route('login');
}
}
// User Middleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id == 2 )
{
return $next($request);
}else {
return redirect()->route('login');
}
}
// Admin Route Group
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
})
// User Middleware
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
});
Hi I have following route and constructor in my controller i want to check if user is authenticated or not if not then redirect to /warehouse/login page. but for some reasons i am getting Route [login] not defined error.
I am migrating my functions from Laravel 4.2 to Laravel 5.4
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if (!Auth::check()) {
$url = URL::current();
$routeName = Route::currentRouteName();
if ($routeName != "AdminLogin" && $routeName != 'admin') {
Session::put('pre_admin_login_url', $url);
}
return redirect('/warehouse/login');
}
return $next($request);
}, array('except' => array('WarehouseAdminLogin', 'WarehouseAdminVerify')));
}
Routes:
Route::get('/warehouse', 'WarehouseController#index');
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
You didnt define your login function.
make a function
public function login()
{'your code'}
in your WarehouseController
Edited: the problem is that you have not a route named login. This error is caused by:
$this->middleware('auth');
because this code in the auth middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
So what to do is remove auth middleware and try again or make a route with login name.
call back route: (I test it with google)
Route::namespace('Auth')->group(function (){
$this->get('login/{provider}/callback', 'LoginController#handleProviderCallback');
...
}
in the LoginController class
public function __construct()
{
$this->middleware('guest')->except('logout');
}
and callback function
public function handleProviderCallback(Request $request, $provider)
{
$social_user = Socialite::driver($provider)->stateless()->user();
$user = User::whereEmail($social_user->getEmail())->first();
auth()->loginUsingId($user->id);
$request->session()->flash('alert', 'hello '.$user->name;);
return back();
}
It always redirect to home page and without alert session.
I found because of this code in
app\Http\Middleware\RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
return redirect('/home');
}
how can do it? I want run this piece of code
$request->session()->flash('alert', 'hello '.$user->name;);
return back();
not this:
return redirect('/home');
You can comment out 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, line in your app/Http/Kernel.php file and you won't be having that redirect