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();
});
Related
I am making a project in laravel 5.2
I have an issue.
this is a school management system where admin/teachers/students login to see their dashboard.
I have made a login page where username and email is given and users can login.
I have my own table for site users named "systemusers".
login is working fine on localhost but its not working on live server.
Auth is not working and users are redirected to login page again
JQUERY CODE:
function loginForm(formID){
//Empty validation errros
$(".errors").html("");
$(".failure").html("");
//Form error flag
var form_error = false;
var form_id = document.getElementById(formID);
var form_data = new FormData(form_id);
$("#"+formID+" input").each(function(key,value){
//Get ids
var id = $(this).attr('id');
if($.trim(this.value) == '' )
{
$("."+id).html("Empty");
form_error = true;
}
else{
if( id == 'username' )
{
var email = $("#username").val();
if( !isEmail(email) )
{
$("."+id).html("Email not Valid");
form_error = true;
}
}
else{
$("."+id).html("");
}
}
});
if( form_error === false )
{
$("#login-btn").prop("disabled", true);
//Run Ajax
$.ajax({
url:'loginFormSubmit',
method:'POST',
data:form_data,
cache:false,
contentType:false,
processData:false,
success:function(html)
{
//alert(html);
if($.trim(html) == 'ERROR-PASS')
{
$(".failure").html("Ivalid Password");
$("#login-btn").prop("disabled", false);
}
else if($.trim(html) == 'ERROR-EMAIL')
{
$(".failure").html("Email not Registered");
$("#login-btn").prop("disabled", false);
}
else
{
//alert(html);
window.location.replace("schoolsys/dashboard/");
}
}
});
}
return false;
}
LOGIN CONTROLLER FUNCTION CODE
public function postLoginUser()
{
//Get the email address posted via Ajax request.
$ajax_email = $_POST["email"];
$ajax_pass = $_POST["password"];
//Check if the email is registered.
$user = $this->systemuser->where("email", "=", $ajax_email)->first();
//If email is matched
if($user )
{
//Match the passwords
if( Hash::check($ajax_pass, $user->password) )
{
$loggedIn = Auth::login($user);
echo "LOGIN-SUCCESS";
}
else{
echo "ERROR-PASS";
}
}
else{
echo "ERROR-EMAIL";
}
DASHBOARD CONROLLER FUNCTION:
public function index()
{
if(!Auth::check())
{
return redirect()->route("login")->withErrors(["Please Login First"]);
}else{
return view("Dashboard");
}
}
ROUTES:
<?php
//Dashboard Route
Route::group(["middleware" => ["web", "auth"]], function(){
Route::get("/dashboard",
[
"as" => "dashboard",
"uses" => "DashboardController#index"
]);
});
//Login View Route
Route::group(["middleware" => ["web"]], function(){
Route::get("/login",
[
"as" => "login",
"uses" => "ajaxLoginController#loginView"
]);
//Ajax - Login Form
Route::post('/loginFormSubmit', 'ajaxLoginController#postLoginUser');
});
//Post Login Form - Double check
Route::post("/post-user-login",
[
"as" => "postLogin",
"uses" => "DashboardController#doubleCheckpostLoginUser"
]);
//Logout Route
Route::get("/logout",
[
"as" => "logout",
"uses" => "DashboardController#logout"
]);
//Add Admin Route
Route::get("/add-admin",
[
"as" => "add-admin",
"uses" => "DashboardController#addAdmin"
]);
//Ajax - Add Admin Form
Route::post("/create-admin", "DashboardController#ajaxPostAdmin")
?>
I'm building a SPA with Vue. My front-end and my back-end (Laravel) are in the same codebase. I want to approach my API (that is in my back-end) via the Laravel Passport Middleware CreateFreshApiToken. I'm approaching my sign in method in my AuthController via web.php.
My problem:
As soon as I'm successfully signed in via my sign in method I would expect that at this time Passport created the laravel_token cookie. This is not the case. The cookie is created after a page refresh. But as I said I'm building a SPA and that's why I don't want to have page refreshes.
What I want:
I want to sign in via my sign in method then use the Passport CreateFreshApiToken middleware. After that I want to use the (just created in the middleware) laravel_token cookie so that I can correctly and safely speak to my own API in my signed-in section of the SPA.
More information:
Kernel.php
// Code...
protected $middlewareGroups = [
'web' => [
// other middlewares...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
];
// Code...
AuthController.php
// Code...
public function login()
{
if (Auth::attempt(['email' => Input::get('email'), 'password' => Input::get('password')], true)) {
return response()->json([
'user' => Auth::user(),
'authenticated' => auth()->check(),
]);
}
return response()->json(['authenticated' => false], 401);
}
// Code...
Login.vue
// Code...
methods: {
login: function (event) {
event.preventDefault();
this.$http.post(BASE_URL + '/login', {
email: this.email,
password: this.password,
})
.then(function (response) {
localStorage.user_id = response.body.user.id;
router.push({
name: 'home'
});
});
},
},
// Code...
What goes wrong? This:
CreateFreshApiToken.php
// Code...
public function handle($request, Closure $next, $guard = null)
{
$this->guard = $guard;
$response = $next($request);
// I'm signed in at this point
if ($this->shouldReceiveFreshToken($request, $response)) { // returns false unless you refresh the page. That's why it won't create the laravel_token cookie
$response->withCookie($this->cookieFactory->make(
$request->user($this->guard)->getKey(), $request->session()->token()
));
}
return $response;
}
protected function shouldReceiveFreshToken($request, $response)
{
// both methods below return false
return $this->requestShouldReceiveFreshToken($request) &&
$this->responseShouldReceiveFreshToken($response);
}
protected function requestShouldReceiveFreshToken($request)
{
// $request->isMethod('GET') - returns false because it's a POST request
// $request->user($this->guard) - returns true as expected
return $request->isMethod('GET') && $request->user($this->guard);
}
protected function responseShouldReceiveFreshToken($response)
{
// $response instanceof Response - returns false
// ! $this->alreadyContainsToken($response) - returns false as expected
return $response instanceof Response &&
! $this->alreadyContainsToken($response);
}
// Code...
I assume it is possible what I want to achieve right? If yes, how?
I had the same issue, decided to stick to client_secret way. I guess it's not relevant for you now, but I've found 2 ways of receiving the laravel token without refresh:
1) sending dummy get request with axios or $http, whatever you use - token will get attached to response;
2) changing requestShouldReceiveFreshToken method in CreateFreshApiToken.php - replace return $request->isMethod('GET') && $request->user($this->guard); with return ($request->isMethod('GET') || $request->isMethod('POST')) && $request->user($this->guard);
function consumeOwnApi($uri, $method = 'GET', $parameters = array())
{
$req = \Illuminate\Http\Request::create($uri, $method, $parameters, $_COOKIE);
$req->headers->set('X-CSRF-TOKEN', app('request')->session()->token());
return app()->handle($req)->getData();
}
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.
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('/');
}
}
});
I'm just currently trying to switch from CodeIgniter to Laravel.
I have implemented the hybridouth method successful, but it seems to be only working for that route it's specified on.
I've tried searching for tutorials and examples but even they only show the auth is working on 1 route.
How can I give some function along to every route to check if a user is logged in?
Group for which the auth is needed.
Route::group(array('before' => 'auth'), function()
{
// ALL ROUTES WITH AUTH NEEDED
});
This seems to call the normal auth and i'm using the hybridauth
Route::get('social/{action?}', array("as" => "hybridauth", function($action = "")
{
if ($action == "auth") {
try {
Hybrid_Endpoint::process();
}
catch (Exception $e) {
return Redirect::route('hybridauth');
}
return;
}
try {
$socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
$provider = $socialAuth->authenticate("facebook");
$userProfile = $provider->getUserProfile();
}
catch(Exception $e) {
return $e->getMessage();
}
echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";
}));
If you are going to run the request at every route, use a filter
App::before(function($request)
{
//check if user logged in here
});
or create filter and group your routes
Route::group(array('before' => 'auth'), function()
{
});