I am using the below code to redirect to the root page.
return Redirect::to('/');
I have defined the home page route as below.
Route::get('/', 'PagesController#home');
When the page is redirect to root page, I expect the url to be http://localhost/crafts/public/ but its http://localhost/crafts/public/home. I am not sure where does that /home gets added. I have the home function defined in the PagesController file.
This is the PagesController section.
public function home()
{
return view('home');
}
All other routes shown below work fine except the main route.
Route::get('about', 'PagesController#about');
Route::get('contact', 'PagesController#contact');
Route::get('auth/{provider}', 'Auth\AuthController#login');
Route::get('auth/{provider}/callback', 'Auth\AuthController#callback');
Please explain what I am doing wrong?
If you look at
app/http/Middleware/RedirectIfAuthenticated.php
it has this code:
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return redirect('/home');
}
return $next($request);
}
So when you are using Redirect, it probably authenticates first which then calls the handle function above which is clearly adding a /home
I do notice one thing that you said you are using Laravel-5 in the question label. In that case, replace the Redirect code with:
return redirect('/');
The syntax Redirect::To is for version 4.x or earlier.
Related
I have created a Middleware to check if users with google2fa_enabled = 1 have a google2fa_secret and when they don't, they need to create one.
In the Middleware, I have defined the handle function with an if-statement and when true, it redirects the user to /2fa/create. It didn't work, so I made the if-statement like if(true), but the user is not being redirected. When I replace the return statement after that with return redirect('/2fa/create'), it does redirect, so the middleware is used (also confirmed with the Laravel debugbar)
The Middleware itself:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class checkTwoFactor
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(true){
redirect('/2fa/create');
}
return $next($request);
}
}
And the routes:
Route::get('/', function () {
return view('layouts/master');
})->middleware(['auth', 'check2fa']);
I expect the user to be redirected to /2fa/create at all times (and later on, if user is logged in, has google2fa_enabled = 1 & google2fa_secret == "")
Oops, I found the mistake already.
I need a return statement in that if-statement to work, so redirect() had to be return redirect()
i have two links
one for login (www.xxx/login/)
one for download file (www.xxx/download/)
if already login, link to www.xxx/download/ will download file automatically,
if not the page will redirect to www.xxx/login/
So how can i write the php code? to login first then go to download file
If you are working on Laravel provided login functionality then this is default provided by Laravel.
You can check this here
Illuminate\Foundation\Auth\AuthenticatesUsers
This is the trait and check function sendLoginResponse. Below is the code written in sendLoginResponse function:-
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
If you are using custom login functionality follow this.
you just need the middleware
so add the _construct method in top of controller
public function __construct()
{
$this->middleware('auth');
}
public function dowloadMethod($fileName)
{
//your code
}
if You are using the Closure method in route
Route::get('YourdowloadUrl/{fileName}',function($fileName)
{
//yourcode goesrhere
}
)->middleware(['web', 'auth']);
I wrote a very simple middleware, like this:
class CheckToken
{
private $token='xxx';
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (! $request->tokenz == $this->token) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
Then I register it trough kernel.php, like this:
protected $routeMiddleware = [
.....
'CheckToken' => \App\Http\Middleware\CheckToken::class,
];
then Ive a very simple function in a controller guarded by this controller:
public function __construct()
{
$this->middleware('CheckToken');
}
public function push()
{
return view('home');
}
Now starts what is not clear to me:
how can i "protect" my page using this simple method?
I've tried to put this tag on the header of page but it seems to not works, maybe im in the wrong path:
<meta name="tokenz" content="xxx">
I put it even in the body but no results.
what ive misunderstood?
I believe you need to add the middleware call to the actual route:
use App\Http\Middleware\CheckAge;
Route::get('admin/profile', function () {
//
})->middleware(CheckAge::class);
This was extracted from the Laravel 5.7 documentation: Middleware - Assigning Middleware to Routes
sorry i can't create a comment. but just want to help.
does $request passed a tokenz?
you can use ?tokenz=blablabla
or you can change your method to get the tokenz
There is a table users in my website and a user is allowed to update a user if it is admin or it is his/her account. I can put this rule inside a middleware and impose it on the route but I want to create separate middlewares and OR among them. Can I do that?
The following code
Route::group(['middleware' => ['admin','Owner']],
function () {
Route::resource('roles', 'RoleController');
Route::resource('locations', 'LocationController');
Route::resource('recipients', 'RecipientController');
Route::resource('classifications', 'ClassificationController');
});
has AND behavior. I think it is possible to do this using some if ... else ... statement inside the web.php or the UserController but I need to know if there is any other way out.
Thanks in advance
update
Here is Owner middleware
class OwnerMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $id)
{
if(Auth::guest())
return abort(403, 'Access Denied');
if(Auth::user()->id != $id)
return abort(403, 'Access Denied');
return $next($request);
}
}
Then I pass the $id parameter to it.
There really isn't an "OR" for middleware. It either acts or passes. You have to expand the current middleware to check ownership or permission to edit.
However, I'd recommend using a policy with middleware to resolve this:
See: https://laravel.com/docs/master/authorization#via-middleware
I am using hesto/multi-auth package
as default if i have assigned the auth middleware to a route the so after login it should redirect me back to the intended page but it's doing only the first time..
everything working exactly i want only the first time but once i logout and try to access the route again it does go to login page and than redirects to the user/home, but first time it works perfect see the 40 sec video
http://neelnetworks.org/video/laravel.mp4
any solution for this?
these are my web routes
Route::get('/', 'PagesController#getIndex')->middleware('user');
Route::group(['prefix' => 'user'], function () {
Route::get('/login', 'UserAuth\LoginController#showLoginForm');
Route::post('/login', 'UserAuth\LoginController#login');
Route::post('/logout', 'UserAuth\LoginController#logout');
Route::get('/register', 'UserAuth\RegisterController#showRegistrationForm');
Route::post('/register', 'UserAuth\RegisterController#register');
Route::post('/password/email', 'UserAuth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/password/reset', 'UserAuth\ResetPasswordController#reset');
Route::get('/password/reset', 'UserAuth\ForgotPasswordController#showLinkRequestForm');
Route::get('/password/reset/{token}', 'UserAuth\ResetPasswordController#showResetForm');
});
here is my Pages Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function getIndex()
{
return "hello";
}
}
first time it works perfectly why not after we logged in once?
it works again if i clear all my cache and cookies, is this a default behaviour or is this a bug in laravel? can you please clarify or is it a issue with the package
the issue has been raised in github https://github.com/Hesto/multi-auth/issues/46
Make your showLoginForm method like this inside your UserAuth/LoginController.php
public function showLoginForm()
{
session()->put('url.intended',url()->previous());
return view('user.auth.login');
}
Because it changes the previous url when posting form to /user/login and you will be redirected to /user/home if you logged in
after so much of digging i found out the correct solution
in RedirectIfNot{guard-name} eg RedirectIfNotAdmin
we need to add this line
session()->put('url.intended', url()->current());
so the middleware will look like this
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
session()->put('url.intended', url()->current());
return redirect('/admin/login');
}
return $next($request);
}
}
Default redirect for laravel after login is to go to /home set in the LoginController:
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
and there is default middleware RedirectIfAuthenticated
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
and in app/Http/Controllers/Auth/RegisterController.php
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
So that is where you need to make changes in order to work your way...