Laravel 5 ignore Authentication specific route - php

I am new in laravel 5. I have a dashboard page and a login page. whenever I go to localhost:8080/dashboard it always redirect me to localhost:8080/auth/login.
I wanted to show my dashboard localhost:8080/dashboard to be viewed without logging in first. Here is my code in VerifyCsfrToken
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
protected $except_urls = [
'dashboard/dashboard',
];
public function handle($request, Closure $next)
{
$regex = '#' . implode('|', $this->except_urls) . '#';
if ($this->isReading($request) || $this->tokensMatch($request) || preg_match($regex, $request->path()))
{
return $this->addCookieToResponse($request, $next($request));
}
throw new TokenMismatchException;
return parent::handle($request, $next);
}
}
routes.php
Route::get('dashboard', 'ReservationController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
controller :
use App\reservations;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Console\Scheduling\Schedule;
use Carbon\Carbon;
use Request;
class ReservationController extends Controller {
/*
|--------------------------------------------------------------------------
| Welcome Controller
|--------------------------------------------------------------------------
|
| This controller renders the "marketing page" for the application and
| is configured to only allow guests. Like most of the other sample
| controllers, you are free to modify or remove it as you desire.
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application welcome screen to the user.
*
* #return Response
*/
public function schedule()
{
$schedules = schedules::all();
return view('calendar.schedule',compact('schedules'));
}
public function index()
{
return view('dashboard.dashboard');
}
public function create()
{
return view('reserve.reserve');
}
public function update()
{
return view('calendar.update');
}
public function login()
{
return view('login');
}
public function store(Requests\CreateReservationRequest $request)
{
$input = Request::all();
$reservation = new reservations(['user_id' => '13100024',
'status_id' => '1',
'room_id' => $input['room'],
'purpose' => $input['purpose'],
'start_time' => $input['date']." ".$input['hour1'].":".$input['minute1'].":00",
'end_time' => $input['date']." ".$input['hour2'].":".$input['minute2'].":00",
'add_date' => Carbon::now()
]);
$reservation->save();
return "success";
// return redirect('schedule');
}

This is what causes the issue:
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
It restricts access to the page to logged in users. Just remove it from your controller and users will be able to access the page whether they're logged in or not.

public function __construct()
{
$this->middleware('auth', ['except' => ['Whatever You want to Bypass']]);
}

Related

Test laravel sanctum with tokens

I would like to test if a user is logged out,I am using Sanctum with Laravel Breeze, I am trying like this:
public function test_users_can_logout()
{
$this->signIn();
$response = $this->postJson(
'/api/logout'
);
$this->assertGuest();
}
And this is AuthenticatedSessionController .php, This came from Breeze, I modified it:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$token = $request->user()->createToken('MyAuthApp')->plainTextToken;
return response()->json(
[
'access_token' => $token,
'token_type' => 'Bearer',
'user' => $request->user()
]
);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
$request->user()->tokens()->delete();
return response()->json(
[
'message' => 'log out successfully'
]
);
}
}
LoginRequest.php
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
/**
* Attempt to authenticate the request's credentials.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* #return string
*/
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\Sanctum\Sanctum;
use App\Models\User;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
Sanctum::actingAs($user);
return $user;
}
}
EDITED: now I am testing only the logout route, my test fails, maybe because sanctum is using cookies? is it ok use sanctum with breeze?
I would like to test if the token no longer exists, what can I do?

View is not loading after login in laravel

In my laravel project i have a login system from another table named agencie. Login functionality is working but view page is returning '404 error'.
Following is my code in Logincontroller.php
<?php
namespace App\Http\Controllers\Agency\AgencyAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Hesto\MultiAuth\Traits\LogsoutGuard;
use JsValidator;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers, LogsoutGuard {
LogsoutGuard::logout insteadof AuthenticatesUsers;
}
protected $validationRules = [
'email' => 'required|email',
'password' => 'required'
];
/**
* Where to redirect users after login / registration.
*
* #var string
*/
public $redirectTo = '/agencie/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('agencie.guest', ['except' => 'logout']);
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$validator = JsValidator::make($this->validationRules,[],[],'#loginform');
return view('agency.auth.login')->with('validator', $validator);
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('agencie');
}
public function logoutToPath() {
return '/agencie';
}
}
I have created custom roots for agencie to load that, foolowing is the codes in routes/agencie.php
<?php
Route::get('/home', function () {
$users[] = Auth::user();
$users[] = Auth::guard()->user();
$users[] = Auth::guard('agencie')->user();
//dd($users);
// echo "<pre>";print_r($users);exit;
// return view('admin.home');
return redirect()->route('agencie.home');
})->name('home');
Route::group(['prefix' => 'agencie'], function () {
Route::get('/home', 'HomeController#index')->name('agency_home');
});
?>
Following is the code in homecontroller.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
echo "agency page";
}
}
What is the problem here why it is not laoding?
public $redirectTo = '/agencie/home';
Doesn't seem to match:
Route::group(['prefix' => 'agency'], /*...*/);

Trait method hasTooManyLoginAttempts has not been applied

I have upgraded my project from 5.2 to 5.3 in laravel. after that, I have the following error:-
Trait method hasTooManyLoginAttempts has not been applied, because there are collisions with other trait methods on App\Http\Controllers\Auth\AuthController in D:\xampp1\htdocs\clubmart_frontend\
app\Http\Controllers\Auth\AuthController.php on line 19
Following is the code of my AuthController:-
<?php
namespace App\Http\Controllers\Auth;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Voucher;
use App\Services\CartManager;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Validator;
use Illuminate\Http\Request;
use App\Events\UserWasRegistered;
use Event;
use Auth;
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 behaviours. Why don't you explore it?
|
*/
use AuthenticatesUsers, RegistersUsers;
public $guard = 'web';
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/** #var UserRepositoryInterface */
protected $userRepository;
/**
* Create a new authentication controller instance.
*
* #param UserRepositoryInterface $userRepository
*/
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return Validator
*/
protected function validator(array $data)
{
return Validator::make(
$data,
[
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]
);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
return $this->userRepository->create(
[
'name' => $data['email'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => $data['password'],
]
);
}
protected function authenticated(Request $request, User $user)
{
if($user = Auth::user()) {
if(!empty(app(CartManager::class)->getItems())) {
return redirect()->intended('/cart');
}
else {
return redirect()->intended('/');
}
}
else {
return redirect()->intended('/');
}
}
//overwrite for add flash message to session
public function postRegister(Request $request, User $user)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
//login the newly created user
\Auth::login($this->create($request->all()));
//fire up the send user email event
$user_id = $user->find(\Auth::user()->id);
Event::fire(new UserWasRegistered($user_id));
$request->session()->flash('alert-success', 'Registration successful!');
if(!empty(app(CartManager::class)->getItems())) {
return redirect()->intended('/cart');
}
else {
return redirect($this->redirectPath());
}
}
/**
* Log the user out of the application.
* overwrite for clear user from session
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if($request->session()->has('user_id'))
$request->session()->forget('user_id');
\Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
}
This is the code of Controller.php:-
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
// use Illuminate\Foundation\Auth\Access\AuthorizesResources;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
Any help will be appreciated. thanks in advance.
Edit
I have removed the following things as suggested:-
use Illuminate\Foundation\Auth\ThrottlesLogins;
use ThrottlesLogins;
But after that I have the following error:-
Trait method guard has not been applied, because there are collisions with other trait methods on App\Http\Controllers\Auth\AuthController in D:\xampp1\htdocs\clubmart_frontend\app\Http\Controllers\Auth\AuthController.php on line 19
I think use ThrottlesLogins already lives in AuthenticatesUsers trait, so you are getting a collision as techically it's included twice. Can you check if it exists in AuthenicatesUsers trait?
If so, try removing use ThrottlesLogins on your AuthController.
This was the solution:-
I simply added the following method to the AuthController.php.
public function getLogin(){
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('auth.login');
}
I have changed $this->guestMiddleware() to 'guest' in AuthController.php
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
// $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
$this->middleware('guest', ['except' => 'logout']);
}
I also have removed the following:-
use Illuminate\Foundation\Auth\RegistersUsers;
use RegistersUsers;
This solved the problem and me successfully able to log in and the project was updated from 5.2 to 5.3. thanks to all for the help.

Laravel login will not redirect after login

Everyone. I have been stuck with Laravel redirecting after login. The connection works and after I login it redirects to a blank page but if I change the url path I can access the different web pages. Any assistance would be highly appreciated! I am using LDAP to connect and it is working.
On my AuthController I have the protected $redirectTo paths set. See picture below.
Please let me know if there is any other code I should provide.
Thank you!!!
(RedirectIfAuthenticated.php)
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
protected $auth;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/computers/create');
}
return $next($request);
}
}
My Routes
Route::group(['middleware' => ['web']], function () {
Route::auth();
Route::get('login', 'LoginController#index');
Route::post('login', 'LoginController#check_password');
Route::patch('computers/{inventories}', 'InventoriesController#update');
Route::get('computers/search', 'InventoriesController#search');
Route::resource('computers', 'InventoriesController');
});
Route::get('/home', 'HomeController#index');
loginController.php
<?php namespace App\Http\Controllers;
/**
* #class Login
*/
use App\User;
use Illuminate\Http\Request;
class Login extends Controller
{
/**
* Show the application dashboard to the user.
*
* #return Response
*/
public function index()
{
return view('auth.login');
}
public function check_password(Request $req)
{
//die('has to stop here');
$user = User::check_password($req);
//var_dump($user); die;
if ($user)
{
return redirect('/computers/create');
}
else
{
return redirect('login')->with('message', 'Login Failed');
}
}
}
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
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 = '/computers/create';
protected $redirectAfterLogout = '/login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
//$this->auth = $auth;
//$this->registrar = $registrar;
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
//Using Ldap
// protected function validator(array $data)
// {
// return Validator::make($data, [
// 'name' => 'required|max:255',
// 'email' => 'required|email|max:255|unique:users',
// 'password' => 'required|min:6|confirmed',
// ]);
//}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
//Removed b/c LDAP is being usedcd
// protected function create(array $data)
// {
// return User::create([
// 'name' => $data['name'],
// 'email' => $data['email'],
// 'password' => bcrypt($data['password']),
// ]);
// }
}
InventoriesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Inventory;
use App\Http\Requests\InventoryRequest;
class InventoriesController extends Controller
{
public function __construct()
{
//$this->middleware('auth'); //does not allow users to login, redirects back to login when using LDAP credentials
}
public function index(Request $request)
{
$location = $request->input("building");
if ($location != null) {
$inventories = Inventory::where('building', $location)->get();
} else {
$inventories = Inventory::all();
}
return view('computers.index', compact('inventories'));
}
public function show($inventories)
{
$inventories = Inventory::findOrFail($inventories);
return view::make('computers.show')
->with('inventory', $inventories);
}
public function create(){
//flash('Hello World', 'This is the message');
return view('computers.create');
}
/**
* Store a newly created resource in storage.
*
* #param inventory $request
* #return Response
*
*/
public function store(InventoryRequest $request)
{
Inventory::create($request->all());
flash('Success!', 'Inventory Successfully Updated!');
//s
// return redirect()->back(); //temporary
return back();
}
public function edit($inventories)
{
$inventories = Inventory::findOrFail($inventories);
return view('computers.edit', compact('inventories'));
}
public function update(InventoryRequest $request, Inventory $inventories){
$inventories->update($request->all());
flash('Success!', 'Inventory Successfully Updated!');
return back();
}
public function search()
{
$search = \Request::get('q'); //<-- we use global request to get the param of URI
// $search = Input::get('search');
$inventories = Inventory::where('lastName','LIKE','%'.$search.'%')
-> orwhere('firstName', 'LIKE','%'.$search.'%' )
-> orwhere('department', 'LIKE','%'.$search.'%' )
-> orwhere('building', 'LIKE','%'.$search.'%' )
-> orwhere('room', 'LIKE','%'.$search.'%' )
-> orwhere('manufacturer', 'LIKE','%'.$search.'%' )
-> orwhere('device', 'LIKE','%'.$search.'%' )
-> orwhere('model', 'LIKE','%'.$search.'%' )
-> orwhere('tag', 'LIKE','%'.$search.'%' )
-> orwhere('macAddress', 'LIKE','%'.$search.'%' )
-> orwhere('status', 'LIKE','%'.$search.'%' )
-> orwhere('comments', 'LIKE','%'.$search.'%' )
->get();
return view('computers.search',compact('inventories'));
}
}
Check the RedirectIfAuthenticated.php Middleware. It should look like this by default:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
Make sure that what is returned is the good page!! If you don't have that Middleware maybe take a look at Laravel's doc to create one!

Laravel 5.2 \Illuminate\Support\Facades\Auth::logout() or $this->auth->logout() not working

I am creating an web application using Laravel 5.2. I have login successfully into the application, but when i tried to logout. It does not allow me to do so.
When i investigate, i came to know that \Illuminate\Support\Facades\Auth::logout() returning null using dd(\Illuminate\Support\Facades\Auth::logout());. I have also tried $this-auth->logout(); this statement also return null.
I am not using default laravel scaffolding, instead i have create my usercontroller and doing the same thing.
Effort:
Route.php
Route::get('/', 'HomeController#index');
Route::get('logout/','UserController#logout');
Route::group(['middleware' => ['web']], function () {
Route::get('login/','UserController#loginForm');
Route::post('login/','UserController#login');
Route::get('register/','UserController#register');
Route::post('register/','UserController#store');
Route::get('home/',['as' => 'home', 'uses' => 'HomeController#index']);
});
UserController.php
namespace App\Http\Controllers;
use App\User;
use App\Profile;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* User model instance
* #var User
*/
protected $user;
protected $profile;
/**
* For Guard
*
* #var Authenticator
*/
protected $auth;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct(Guard $auth, User $user)
{
$this->user = $user;
$this->auth = $auth;
$this->middleware('guest', ['except' => 'logout']);
}
public function login(Request $request)
{
if ($this->auth->attempt($request->only('email', 'password'))) {
// dd(\Illuminate\Support\Facades\Auth::user());
dd(\Illuminate\Support\Facades\Auth::user());
return redirect()->route('home');
}
return redirect('login')->withErrors([
'email' => 'The email or the password is invalid. Please try again.',
]);
}
/**
* Log the user out of the application.
*
* #return Response
*/
protected function logout()
{
// \Illuminate\Support\Facades\Auth::logout();
dd(\Illuminate\Support\Facades\Auth::logout());
$this->auth->logout();
\Session::flush();
return redirect('login');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function loginForm()
{
return view('user.login', ['title' => 'Login Page']);
}
....
}
I am lot able to understand why user is not getting logout ? Please help Me.

Categories