I need help, can someone tell me if my work is correct with the authentication users profiles? I have the next files:
file routes.php (I used only two groups for this example)
<?php
//home
Route::get('/',function()
{
return Redirect::to('login');
});
//login get
Route::get('login','AuthController#showLogin');
//login for form
Route::post('login','AuthController#postLogin');
//routes for admin
Route::group(array('before' => 'adminFilter'),function()
{
Route::get('/adminHomePage',function()
{
return View::make('adminHome');
});
});
//route for common user
Route::group(array('before' => 'commonUserFilter'),function()
{
Route::get('/commonUserPage',function()
{
return View::make('commonPage');
});
});
Route::get('logout','AuthController#logout');
?>
file filters.php
<?php
Route::filter('adminFilter', function($route, $request)
{
if (Auth::user()->profile != 1)
{
return Redirect::to('/logout');
}
});
Route::filter('commonUserFilter',function($route, $request)
{
if (Auth::user()->profile != 2)
{
return Redirect::to('/logout');
}
});
?>
file AuthController.php
<?php
public function showLogin()
{
return View::make('login');
}
public function postLogin()
{
//Get user data from login form
$user = array(
'user' => Input::get('username'),
'password' => Input::get('password'));
if(Auth::attempt($user,true))
{
switch (Auth::user()->profile)
{
case 1:
//home admin
return Redirect::to('/adminHomePage');
break;
case 2:
//home common user
return Redirect::to('/commonUserPage');
break;
}
}
else
{
return Redirect::to('login')
->with('mensaje_error','Incorrect data.')
->withInput();
}
}
public function logOut()
{
Auth::logout();
return Redirect::to('/login')
->with('mensaje_error', 'Your session was closed.');
}
?>
One security issue (If you are using Laravel 4 +)
In routes.php:
Route::post('name', Controller#class);
Change it to:
Route::group(array('before' => 'csrf'), function() {
Route::post('name', Controller#class);
});
In your form, you have to add this: {{ Form::token() }}.
One little tip: I prefer to give all your routes a unique names.. How this works can you find here.
Related
I currently have a booker and admin user groups. A booker user is assigned to 1 event, and an admin user is not assigned to any event.
Both user groups have route groups like this:
Route::group(['middleware' => 'booker'], function() {
Route::controller('event', 'EventController');
});
Route::group(['middleware' => 'admin'], function() {
Route::controller('admin', 'AdminController');
});
Actions in EventController are like this:
getIndex /event
getOverview /event/overview
postOverview /event/overview
getFacilities /event/facilities
postFacilties /event/facilities
etc.
When logged in as admin user group, is it possible for me to use the EventController actions for routes like this:
/admin/events/1
/admin/events/1/overview
/admin/events/1/facilties
/admin/events/1/schedule
etc.
Where, instead of getting the event id from the user, I would get it from the URL.
Thanks
Ok, I managed to get there, although it's quite messy so I'd still love to know if there is a nicer solution:
routes:
Route::group(['middleware' => 'booker'], function() {
Route::controller('event', 'EventController');
});
Route::group(['middleware' => 'admin'], function() {
Route::controller('admin/events/{id?}', 'EventController');
Route::controller('admin', 'AdminController');
Route::get('event', function() { return redirect('admin'); });
});
In EventController (using Sentry):
public function __construct()
{
$user = Sentry::getUser();
if($user->hasAccess('admin')) {
$id = Request::segment(3);
$event = Event::find($id);
if(!$event) {
abort(404);
}
} else {
$event = $user->event;
}
$this->data['event'] = $event;
}
public function getIndex()
{
return view('event.index', $this->data);
}
So as you can see I've had to use the URL segment for the id, as I couldn't find a way to pass the id variable in the route. The route variable just enables me to ignore the id and load the controller.
I found I couldn't use URLs like this within EventController views:
<a href="{{ URL::action('EventController#getOverview') }}">Overview<a>
// /event/overview
// /admin/events//overview
However using other helpers I could hack it in:
<a href="{{ URL::full().'/overview' }}">Overview<a>
// /event/overview
// /admin/events/3/overview
I am trying to create a filter that works for a specific domain and redirects a user from any page they try to visit if they have gone over a quota. So far, the code does not redirect at all.
Here is what I have so far in filters.php:
Route::filter('domain', function () {
if (stripos(Request::root(), Config::get('domains.main')) !== false) {
if (Auth::check()) {
$user = Auth::user();
$max_quota = Plan::where('id', $user->plan_id)->where('is_active', true)->pluck('max_quota');
$quota_used = Quota::where('user_id', $user->id)->count();
if (empty($max_quota)) {
return Redirect::to('account/error/inactive');
} elseif ($quota_used >= $max_quota) {
return Redirect::to('account/error/over_quota');
}
}
}
});
Even if I put this in routes.php under:
Route::group(['domain' => Config::get('domains.main')], function () {
Route::filter('*', function () { /* Same code here... */ });
}
It will then get into the filter function, successfully check the criteria, but the redirect still doesn't happen.
I think I am missing more than one key point here. Ideas?
To make this work, I needed to change:
Route::group(['domain' => Config::get('domains.main')], function () {
To:
Route::group(['domain' => Config::get('domains.main'), 'before' => 'domain'], function () {
I also needed to add redirect loop protection to this line:
if (Auth::check()) {
So that it becomes:
if (Auth::check() && !strpos(Request::fullUrl(), 'account/error')) {
My problem is that if I enter the url http://localhost/login or http://localhost/admin returns infinite loop browser. But income smoothly panel I created.
File routes.php
#Crea la primera para hacer login
Route::get('/', function()
{
return View::make('login');
});
#Permite desloguear al usuario
Route::get('/logout', function()
{
Auth::logout();
#Al desloguear saca al usuario al index
return Redirect::to('/');
});
#Enruta hacia el controlador para hacer el login
Route::controller('check', 'Login');
#No permite el ingreso a panel sin antes estar auntentificado
Route::get('panel', array('before' => 'auth', function() {
return View::make('dashboard.index');
}));
File Login.php in Controllers
Here you enter the login and redirects panel, if replacement by admin panel returns loop.
<?php
class Login extends BaseController {
public function postUser()
{
// get POST data
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if(Auth::attempt($userdata))
{
// we are now logged in, go to admin
return Redirect::to('panel');
}
else
{
return Redirect::to('/')->with('login_errors',true);
}
}
}
Filters.php
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
Hello i create website in laravel but i facing one problem. The problem is that when user is not log in and user type www.test.com/notifications that time showing error like this
ErrorException (E_UNKNOWN)
Undefined variable: messages (View: /home/test/app/views/message-page.blade.php)
But i want to when user is not log in and enter www.test.com/notifications so user automatic redirect to index page. Please help me i very confuse.
I using the some code in base controller is as follows:
public function checkLoggedIn(){
if(Auth::user()->check()){
return;
}
else {
return Redirect::to("/");
}
}
You should do it this way:
public function checkLoggedIn(){
if (!Auth::check()) {
return Redirect::to("/");
}
return true;
}
However I assume you want to use this function in another controller so then you should do it this way:
$result = $this->checkLoggedIn();
if ($result !== true) {
return $result;
}
to make redirection.
But Laravel have filters so you can easily check if user is logged.
You can just use in your routes.php:
Route::group(
['before' => 'auth'],
function () {
// here you put all paths that requires user authentication
}
);
And you can adjust your filter in app/filters for example:
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::to('/');
}
}
});
The laravel session and auth I use have some problem in server, but working really fine in localhost . I will show.
Route
Route::get('/signin', 'PageController#signin');
Route::get('/signup', 'PageController#signup');
Route::get('/terms', 'PageController#terms');
Route::resource('/', 'PageController');
Route::controller('user', 'UserController');
PageController
public function index() {
if (Auth::check()) {
return View::make('user.index');
} else {
return View::make('landing');
}
}
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Redirect::to('/');
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
Auth::check() fails in pagecontoller even after login succeds. But if I change the code to
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
I get the index page and if I click the link of the home I get the landing page not the index page.
I guess I clarify my problem, I have gone through may solution replied earlier in same manner question nothing working.
I don't think its the server problem because another laravel application is working fine in same server.
Please help.
Your query seems to be incomplete, from what i understand you are able to get the index page after passing the authentication check only once, and that is by using this method:
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
}
else {
$data['success'] = false;
}
}
else {
$data['success'] = false;
}
return $data;
}
try using a different browser to make sure there is no cookie storage restrictions in the client side and check the app/config/session.php file and see if you have configured the HTTPS Only Cookies according to your needs.
and just on an additional note this line "return Return View::make(user.index);" looks vague.