I am trying to do something that I believe to be simple, I'm just having some trouble along the way. My code below includes my routes.php and my verify.php that authenticates a user. Basically, I want the routing to the homepage to change based on if the user is authenticated or not.
So first, I have the controller (verify.php)
<?php
namespace App\Http\Controllers;
use App\Email;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Google_Client;
use Auth;
use App\User;
class verify extends Controller
{
public function verifyIdToken(Request $request)
{
$user = User::where('name', 'Molly')->first();
Auth::login($user);
return;
}
}
This script is hit in an ajax request when the user first satisfies some conditions to be logged in, but that is client-side logic and not important at this point. The idea is that once the script is hit, the user is logged in.
To add more detail:
The header of my routes.php is this:
use Auth;
use Illuminate\Http\Request;
Is there something I am missing?
My routes.php logic is now this:
if (Auth::guest()) {
Route::get('/', function () {
return view('welcome');
});
} else {
Route::get('/', function () {
return view('mainview');
});
}
But it still doesn't work, even though in verify.php I have added in the following confirmation:
if (Auth::check($user))
{
return view('aviewII')->with(['verify' => json_encode("Yes!")]);
}
Which I am getting returned in my ajax requests.
So even though that tells me I am authenticated, I still can't get the authenticated view. What should I try next?
Edit: My routes.php in its entirety:
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
use App\punsmodel;
use Illuminate\Http\Request;
if (Auth::guest()) {
Route::get('/', function () {
return view('welcome');
});
} else {
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return view('mainview');
});
Route::get('mainview', function () {
return view('mainviewMolly');
});
});
}
Route::get('puns', function () {
return view('puns');
});
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken'
]);
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
//
});
I’d just have a conditional in routes.php:
if (Auth::guest()) {
Route::get('/', function () {
return view('home.logged_out');
});
} else {
Route::get('/', function () {
return view('home.logged_in');
});
}
Also, a couple of styling tips:
Classes should have “StudlyCased” names, so class verify should be class Verify.
Order your use statements alphabetically, makes scanning much easier ;)
UPDATE:
If you want to check the authentication status of a user, you need to make sure those routes are inside the group with middleware applied:
Route::group(['middleware' => 'web'], function () {
if (Auth::guest()) {
return view('home.logged_out');
} else {
return view('home.logged_in');
}
});
Ok so if you're on L5.2, this is a bit different. Check this article.
From what I got, you have to add an api_token field to your users table. Then when you want to check if a User is logged in, you can do this Auth::guard('api')->check().
When you log your user, you have to return the api_token in your response and add this field to any of your Ajax requests.
Hope that helped ;)
Related
I'm making an application which requires a user and password for access. Every user should face the login view. Currently, writing the URL manually, I can access all the routes without login. What I want is to redirect every unauthenticated user to the login view, so that they can't see anything else until they log in.
LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
public function redirectTo() {
$isAuth = Auth::check();
if ($isAuth) {
return redirect('dashboard');
} else {
return redirect('login');
}
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function logout(Request $request)
{
Auth::logout();
return redirect('/login');
}
}
Routes
<?php
Route::get('/', function () {
return view('home');
});
Route::resource('project','ProjectController');
Route::resource('client','ClientController');
Route::resource('task','TaskController');
Route::resource('people','PeopleController');
Route::get('/login', function () {
return view('login');
});
Route::get('logout', '\App\Http\Controllers\Auth\LoginController#logout');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
You should use a middleware for that. To get info on what a middleware is check here laravel.com/docs/master/middleware
Let's see how you can use the default Laravel's auth middleware for this purpose:
First of all get rid of your AdminBaseController and use only AdminController
Then you have to check that the auth middleware is enabled in the file app\Http\Kernel.php
You should have the line:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
This means that the middleware is active and usable for your routes.
Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :
this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
//check here if the user is authenticated
if ( ! $this->auth->user() )
{
// here you should redirect to login
}
return $next($request);
}
Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('admin/home', 'AdminController#index');
});
You should move your Auth::routes() before your first route
<?php
Auth::routes()
Route::get('/', function () {
return view('home');
});
And use auth middleware in your controllers where you want only authenticated user.
public function __construct()
{
$this->middleware('auth');
}
Move your Auth:Routes(); right after
Route::get('/', function () {
return view('home');
});
Then all your routes will be auth protected.
I'm using laravel's Auth to do a login process and keep my application authenticated using username and password in my database. Here is my login function:
public function doLogin(Request $req) {
if (Auth::attempt(['email' => $req->email, 'password' => $req['password']])) {
return redirect('/');
} else {
return redirect('/login')->with('statusFail', 'true');
}
}
I'm creating my routes like this:
Route::group(['middleware' => ['login']], function() {
/*All my authenticated routes here ..*/
}
Route::group(['middleware' => ['guest']], function() {
/*All my non-authenticated routes here ..*/
}
And my middleware like this:
Guest:
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
use Auth;
class GuestMiddleware
{
public function handle($request, Closure $next)
{
if (Auth::check())
return redirect('/');
return $next($request);
}
}
LoggedIn:
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
use Auth;
class LoggedInMiddleware
{
public function handle($request, Closure $next)
{
if (!Auth::check())
return redirect('/login');
return $next($request);
}
}
At first, I can login using correct username and password, then after surfing some of pages, my auth credentials gone missing and redirected me back to the login back. Sometimes, it only takes 1 website redirection then my auth credentials gone missing.
Anyone can help ?
Use web middleware:
Route::group(['middleware' => 'web'], function () {
///your routes goes here
Route::group(['middleware' => ['login']], function() {
/*All my authenticated routes here ..*/
});
Route::group(['middleware' => ['guest']], function() {
/*All my non-authenticated routes here ..*/
});
});
Is that typo :
class GuestMiddleware => Name of the both middlewares ?
Rename it and register it accordingly.
I have multiple URLs going to a single Laravel application:
www.mydomain.com
panel.mydomain.com
Within this I have several routes configured:
<?php
Route::group(['middleware' => ['web']], function () {
Route::get('/page', 'App\MyApp\Page\Controllers\PageController#index')->name('home');
});
Route::group(['middleware' => ['web'], 'domain' => 'panel.mydomain.com'], function() {
Route::get('/page', 'App\MyApp\Page\Controllers\ControlPanelPageController#index')->name('controlpanel.dashboard');
});
So anyone going on panel.mydomain.com gets a ControlPanelPageController index method, everyone else gets the PageController method.
However I'm having difficulty generating a link from a named route.
For example:
<?php
namespace App\MyApp\Page\Controllers;
use App\Http\Controllers\Controller;
class ControlPanelPageController extends Controller
{
public function index()
{
echo route('home');
// output: /page
echo url( route('home') );
// output: panel.mydomain.com/page
// required output: www.mydomain.com/page
}
}
In my web.php I have the following route set up. What I was wanting to know is there something specific that I need to follow to get a sub domain of a sub domain to work?
The domain I am using is blah.blah.domain.tld
web.php:
Route::group(['domain' => '{blah}.blah.domain.tld'], function (){
Route::get('', 'DealsFrontEnd#index' );
});
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class DealsFrontEnd extends Controller
{
public function index()
{
return view('front.deals');
}
}
Too long for a comment: Try using a closure for debugging:
Route::group(['domain' => '{blah}.blah.domain.tld'], function (){
Route::get('', function() {
echo "Hello World";
});
});
Make sure you have debug enabled to make use of Laravel's error handling/reporting.
As I said in the comments, you shouldn't wrap the subdomain in brackets unless you want it to be dynamic.
{blah}.blah means it will capture anything.blah and the route variable $blah will be equal to anything.
I'm trying to build a web app using laravel for the backend! I used the php artisan make:auth command to generate the basic login logic and views. Now I'm trying to redirect users according to the admin field in the users table in the database. The problem is this : it think i don't get the right values from the db so the redirect never works...
here is the routes.php
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/register', function () {
return redirect('/step1');
});
route::get('/dashboard', function () {
return view('admin.dashboard');
});
// after login --> else "welcome"
Route::get('/home', 'HomeController#index');
// register user + agency
Route::get('/step1', 'AgencyController#showStep1');
Route::post('/step1', 'Auth\AuthController#register');
// complete registration step 2 --> 9
Route::get('/step{stepId}', ['middleware' => 'auth', 'uses' => 'AgencyController#show']);
Route::post('/step{stepId}', 'AgencyController#store');});
Here is the code for the redirect (in AuthController.php)
<?php
namespace App\Http\Controllers\Auth;
use App\Agency;
use App\Http\Controllers\Controller;
use App\User;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Validator;
class AuthController extends Controller {
/*
|------------------------------------------------------------------- -------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function login() {
if (Auth::check()) {
if (Auth::User()->admin != '1') {
return redirect('/dashboard');
} else {
return redirect('/step1');
}
} else {return 'doesnt work :(';}
}
when i run this and login i always get the 'doesnt work' text.
NOTE: the Auth command generated routes :
$this->get('login', 'Auth\AuthController#showLoginForm');
$this->post('login', 'Auth\AuthController#login');
$this->get('logout', 'Auth\AuthController#logout');
// Registration Routes...
$this->get('register', 'Auth\AuthController#showRegistrationForm');
$this->post('register', 'Auth\AuthController#register');
thanks in advance !
Are you using laravel 4.2?
It seems like you're login manually, if you want to login a user,
you shoule
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
if(Auth::User()->admin != 1){
#your logic
}
return Redirect::intended('dashboard');
}