Laravel Classroom image

osdyui
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4 | 5|Last
Lessons:-Authentication

14.4 Protecting Routes
Ok, we are almost done here! There is a slight bug, a security issue that we need to take care of
first. Logout of the system, (no not the machine you are reading this on, just the site) and head
over to the home URL by hand.
Uh oh, now the grey squirrels can see our attack plans without even logging in! We will need to
fix this. Also because we don’t have a user logged into the system, we get an undefined index
(or something similar) error when trying to access the user’s username.
Cast your mind way back, the solution is there lurking in the shadows near the start of the book.
What? No shadows? I paid the publisher to put them in… never mind let’s carry on. Do you
remember route filters? Using filters we can run a snippet of code before the route is executed,
and if we return something it will be used in place of what we return from our route. Woah, lots
of potential there.
It’s even easier than that, you see Taylor has a degree in amateur mind reading, he knew we
would be writing this chapter, and he knew we would need to protect a route from non-logged
in users. That is why he created the ‘auth’ filter, which is included with Laravel as standard.
Let’s have a look at the filter itself. (You can find this in routes.php)
1 <?php
2
3 Route::filter('auth', function()
4 {
5 if (Auth::guest()) return Redirect::to('login');
6 });Neat!
You see the Auth::guest() method? It’s a nicely expressive method which returns true only
if the current request has no logged in user. Very handy! You can also use Auth::check() to
perform the opposite check, to see if a user is currently logged in. We know these methods do
exactly the same thing, but by providing clean expressive method names, using the right one
will appear much clearer within your source.
As you can see, if no user is logged in the auth filter returns a redirect to the login page,
overwriting the view supplied by our route. All we need to do is attach this to our home route.
1 <?php
2
3 Route::get('home', array('before' => 'auth', 'do' => function() {
4 return View::make('home');
5 }));
There we go, now the home route is protected, the undefined notices will never be seen, and
unauthorised squirr… users will no longer be able to see the home page. Please remember not to
apply the auth filter to your login URI, you will experience a terrible loop!

 
 
 

osdyui

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)