Laravel guest middleware - laravel-5

I have a page in my web app that should be blocked from logged in users. Similar to how a login or register page should not be accessible to already logged in users. I accomplished this by using guest middleware in controller constructor.
$this->middleware("guest")->only("page_action"); // like this
In this setup, if logged in user tries to visit that page they get redirected to home page. But I need to show a 404 not found page instead of redirecting. How can I do that?
In short, how can I make a page accessible to guest only and make it look like it does not exist to logged in users?

The guest logic is inside inside App\Http\Middleware\RedirectIfAuthenticated.
if (Auth::guard($guard)->check()) {
abort(404)
}
return $next($request);
Otherwise, you need to create a new middleware like #Atiqur suggested.

In your method just check if the user is loggedIn, if then abort to 404 like below...
if(\Illuminate\Support\Facades\Auth::check()) {
return abort(404);
}
#Rest of the code is for guest user.....
#

Related

Laravel multiauth redirection problem after authentication

I have three different guard with different login page
all working great but there is issue after login
E.g.
There are three Auth:
Default(web)
branch
agent
I logged in into agent account firs time and I logged out
when I enter credentials of branch it redirects to agent login page and when I go back to branch, voila its already logged-in
However it does not happen on first attempt of login right after opening window
It was just cup of tee
here you go.......!
I modified attemptLogin() method in each auth's login controller
protected function attemptLogin(Request $request)
{
if($this->guard()->attempt($this->credentials($request), $request->filled('remember')))
{
return redirect()
->intended(route('agent.dashboard'))
->with('success','You are Logged!');
}
}
in case you get following error
Argument 1 passed to App\Http\Controllers\Auth\LoginController::attemptLogin()
add following on top of controller
use Illuminate\Http\Request;

How to use intended function in Laravel

I need to register in a tournament with the URL:
http://laravel.dev/tournaments/1/register/
This URL is in the middleware 'auth', so if the user is not logged, he is redirected to login / page.
What I need is to redirect to
http://laravel.dev/tournaments/1/register/
After login.
In my routes.php, I have:
Route::get('tournaments/{tournamentId}/register', 'TournamentController#register');
I was told to use
redirect()->intended
but I don't know how to do it.
In the general case, User will be redirected to /admin, but in this case, I want him to keep doing his main action ( Register tournament)...
I'm using the built in trait for login, so I checked what system do when login and it is already using this function:
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
Thing is it will redirect me to a default path, not a dynamic one...
You should to know different between Redirect To and Redirect Intended
Redirect Intended: redirects the user to where they were originally going
Redirect To: Redirect the user to the page **YOU** specify them to go.
Things to check:
Use your browser's inspect element network feature to trace redirects - there may be several, which could help clear up confusion.
The intended() method requires a call to guest() when redirecting previous to the former. This happens in the Authenticate middleware, but
if you're using some other middleware (such as a middleware to catch and redirect admins to an admin area), this might be triggering first and redirecting without using guest().
Does your controller using the AuthenticatesUsers trait implement the authenticated method? If so this will be returned instead of redirect()->intended().

Laravel - Redirect::intended route not working

I have a laravel built blog, and to comment on a post (if you're logged out) you must login. I put a link like this:
login to do this.
This redirects to the login form, which once filled out and user is authenticated, I have this:
return Redirect::intended('/');
Which takes the user to the homepage, not the page they intended to be on, in this case, the page with the post that they clicked the login link from to be able to comment. How can I return them back to the intended url in this case?
Actually, Redirect::intended('/') works if there is a key available in the session as url.intended otherwise it redirects to the default URL which is in your case '/', so definitely you didn't put the URL in the session. To accomplish this, you may put the URL in the session using something like this:
Session::put('url.intended', 'url...');
So, probably, in the login link, you may add a query string like this:
login
So, you can track the redirect and in that route's method (before return View) just put the previous URL in the session, using something like this:
if(Input::get('intended')) {
Session::put('url.intended', URL::previous());
}
Then before you redirect from there, you should remove the URL from the session using something like this:
$intendedUrl = Session::get('url.intended', url('/'));
Session::forget('url.intended');
return Redirect::to($intendedUrl);
This should solve the issue. Also, you may check this answer, could be helpful.
Redirect::intended requires two parts to work. The first is when the user tries to access a restricted page /orders but they aren't logged in you redirect them to the login page via:
redirect()->guest('/login');
Then on your login post-back if authentication is successful you call:
redirect()->intended('/dashboard');

Magento - Redirect back (similar to using setBeforeAuthUrl) when user creates a new account

I have the following controller action, which redirects to the login page if no user is logged in:
public function requireloginAction() {
if(!Mage::getSingleton('customer/session')->isLoggedIn()) {
// Not logged in
// Save requested URL for later redirection
Mage::getSingleton('customer/session')->setBeforeAuthUrl($this->getRequest()->getRequestUri());
header("Status: 301");
header('Location: '.Mage::helper('customer')->getLoginUrl()); // send to the login page
}
else {
// Logged in
.. do something ..
}
}
By using setBeforeAuthUrl, once the user logs in he/she is redirected back to this action.
Problem:
If instead of logging in, the user, creates an account he/she is then redirected to the main page, rather then to the url set in setBeforeAuthUrl.
Question:
Is there something similar to setBeforeAuthUrl that works with Account Creation too? Or how can I achieve the desired effect?
(Magento Version 1.6)
You can try using the following extension. http://www.magentocommerce.com/magento-connect/MagePsycho/extension/3763/custom_login_redirect
Or you can also open app/code/core/Mage/Customer/controllers/AccountController.php and look for the createPostAction() function around line 328 edit:
$url = $this->_welcomeCustomer($customer);
$this->_redirectSuccess($url);
to
$url = 'http://www.mycustomrediurecturl.com';
$this->_redirectSuccess($url);
If you want to do it the nice way override the controller add configuration options and make it a module :)
Cheers
Found solution.
First of all, setBeforeAuthUrl($url) does work for both "Log In" and "New Account Creation"!
The main difference (and the reason I had the problem) is that for a "New Account Creation" Magento checks if $url is within the domain name of the current store and if it is not, it redirects to the "My Account" page. While the redirection for "Log In" redirects to any $url.
I do not know if this is a bug or a feature (I'm using V1.6.0.0).
So just make sure to redirect to a url within the domain name of the current store - especially in a Multi Store configuration.

CodeIgniter only allow access to certain controllers when logged in

I have some CodeIgniter controllers which should only be accessed by users who have logged in (i.e. where $this->session->userdata('username') is not null). If a non-authenticated person attempts to access said controllers they should receive:
header('location: /auth/login');
There has got to be a better way to do this than to put a
if (!$this->session->userdata('username'))
header('location: /auth/login');
else
{
[rest of function]
}
in front of every function in the controller...
I know DX_Auth has a similar functionality, but I am not using an authentication plugin and I am not open to doing so.
Thanks!
Mala
Do the user login check when the class is created, so it doesn't matter what function the user is accessing it will check for the session variable and redirect to the login page on failure:
function className()
{
parent::Controller();
if(!$this->session->userdata('username')) header('location: /auth/login');
}
That's the way of calling the __constructor or it's equivalent in codeigniter when you create controllers/models, or at least that's what I understood!

Resources