Hey guys i am newly working on Laravel. I am facing a problem regarding authentication.
Its that whenever i try to authenticate a user and redirect it to a view of a specific controller it works fine but then when i try to open the other view the user authentication does not work ( user logs out ). basically the issue is i have two controllers so if i redirects from authentication to any one of them the other one doesnt have the user.
I hope i have explained my problem clearly
Route List : Result
Route List
Main page routes are the ones that i am working with... others are just dummy as for now
This is my authentication class
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/');
}
}
return $next($request);
}
}
This is the Index Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class IndexPageController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user()->firstOrFail();
return view('index')
->with(compact('user'));
//
}
This is the UserProfileController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user()->firstOrFail();
return view('profile.index')
->with(compact('user'));
//
}
Routes
<?php
use Illuminate\Support\Facades\Mail;
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for 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.
|
*/
/*Welcome Page routes */
Route::get('/' , function(){
return view('auth.login');
});
Route::get('user/logout' , function(){
Auth::logout();
return redirect('/');
});
Route::post('user/do-login' , 'Auth\AuthController#doLogin');
Route::get('user/create' , 'Auth\AuthController#createUser');
/*---------------------------*/
/*Welcome Page AJAX routes*/
Route::get('/checkAvailibility' , 'WelcomePageController#usercheck');
/*---------------------------*/
/*Images Routes*/
Route::post('image/do-upload' ,'GalleryController#doImageUpload');
Route::post('gallery/save' , 'GalleryController#saveGallery');
Route::get('gallery/list' , 'GalleryController#viewGalleryList');
Route::get('gallery/view/{id}' , 'GalleryController#viewGalleryPics');
Route::get('gallery/delete/{id}' , 'GalleryController#deleteGallery');
/*---------------------------*/
/*Event Routes */
Route::post('create/Image-Upload' , 'CreateEventFormController#ImageUpload');
Route::post('create' , 'CreateEventFormController#store');
Route::get('create/event-image' , 'CreateEventFormController#createEventFormImage');
Route::post('create/event-image' , 'CreateEventFormController#UploadEventImg');
Route::get('create' , 'CreateEventFormController#create');
Route::get('event/{id}' , [ 'as' => 'event_list' , 'uses' => 'CreateEventFormController#show']);
/*---------------------------*/
/*-------------- Main Page Routes -------------------*/
Route::get('event/{id}' , [ 'as' => 'event_list' , 'uses' => 'CreateEventFormController#show']);
Route::get('index' ,[ 'as' => 'index' , 'uses' => 'IndexPageController#index']);
/*-------------- END -------------------*/
/*-------------- Main Page Routes -------------------*/
Route::get('profile' , 'UserProfileController#index');
Route::get('profile/{id}' , 'IndexPageController#show');
/*-------------- END -------------------*/
Route::get('/email', function () {
$data = array(
'name' => "Learning Laravel",
);
Mail::send('emails.test', $data, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('yourEmail#domain.com')->subject('Learning Laravel test email');
});
return "Your email has been sent successfully";
});
It is possible that there is something with your AuthController.php.
Are you by any chance using Auth::attempt() to authenticate? If so, I have experienced problems in the past where echoing something out after authenticating causes problems.
Another possibility is that something is going wrong with storing the session. It could be something as simple as the session not being saved/written.
Related
I am studying multiple authentication.
In particular I have 3 users:
a User user who must be redirected to /home when logging in
an Admin user who must be redirected to /admin/home when logging in
a Manager user who must be redirected to /manager/home when logging in
The problem I am having is when I log in as Admin and as Manager I am redirected to the route /home and then I get the error
["You do not have permission to access for this page."]
However, once I log in, if I manually enter the route of interest I can log in without problems.
So the problem is the route addressing once I try to log in as Admin or as Manager.
For the User user I'm not having any problems.
This is my code:
Route.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
/*------------------------------------------
--------------------------------------------
All Normal Users Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:user'])->group(function () {
Route::get('/home', [HomeController::class, 'index'])->name('home');
});
/*------------------------------------------
--------------------------------------------
All Admin Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:admin'])->group(function () {
Route::get('/admin/home', [HomeController::class, 'adminHome'])->name('admin.home');
Route::get('/admin/link', [HomeController::class, 'adminHello'])->name('admin.hello');
});
/*------------------------------------------
--------------------------------------------
All Admin Routes List
--------------------------------------------
--------------------------------------------*/
Route::middleware(['auth', 'user-access:manager'])->group(function () {
Route::get('/manager/home', [HomeController::class, 'managerHome'])->name('manager.home');
});
LoginController
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;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function login(Request $request)
{
$input = $request->all();
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
{
if (auth()->user()->type == 'admin') {
return redirect()->route('admin.home');
}else if (auth()->user()->type == 'manager') {
return redirect()->route('manager.home');
}else{
return redirect()->route('home');
}
}else{
return redirect()->route('login')
->with('error','Email-Address And Password Are Wrong.');
}
}
}
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function adminHome()
{
return view('adminHome');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function managerHome()
{
return view('managerHome');
}
}
UserAccess
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class UserAccess
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, $userType)
{
if(auth()->user()->type == $userType){
return $next($request);
}
return response()->json(['You do not have permission to access for this page.']);
/* return response()->view('errors.check-permission'); */
}
}
Can you kindly help me?
In most of my applications I have an admin panel.
Here's how I do the redirect logic:
I use the default Auth/AuthenticatedSessionController class from the breeze install.
My store method looks like this:
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
if (Auth::user()->hasRole('admin')) {
return redirect()->intended(RouteServiceProvider::ADMIN_HOME);
}
return redirect()->intended(RouteServiceProvider::HOME);
}
And of course in the RouteServiceProvider I hav my routes defined:
public const HOME = '/myorders';
public const ADMIN_HOME = '/admin/pages';
Solution 1:
On your App\Http\Controllers\Auth\LoginController, just override the method:
use Illuminate\Support\Facades\Auth;
public function redirectPath()
{
if (Auth::user()->role == 'Admin') {
return "/admin/home";
// or return route('admin.home');
}
elseif (Auth::user()->role == 'Manager') {
return "/manager/home";
// or return route('manager.home');
}
return "/home";
// or return route('home');
}
N.B: If something issue happenes with the method redirectPath, then please try with the method redirectTo. And must remove the property named redirectTo as well.
Solution 2:
App\Http\Controllers\Auth\LoginController.php
use Illuminate\Support\Facades\Auth;
protected function authenticated(Request $request, $user)
{
if (auth()->user()->hasRole(['Admin'])) {
return redirect("/admin/home");
}
elseif (auth()->user()->hasRole(['Manager'])) {
return redirect("/manager/home");
}
return redirect("/home");
}
N.B: If you are using Laravel Spatie Permission package, then the permission checking would work in this way.
I am working with laravel RestfulApi project. I am facing an unexpected trouble. When I try to send an API request to api.php route, it goes to the web.php route. But if I don't use validation in my controller file, the code runs well. I only get the above problem when using validation. Below is my code.
Api.php Routes
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/showingData','UserContactController#show');
Route::post('/storingData','UserContactController#store');
Web.php Routes
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
UserContactController.php
<?php
namespace App\Http\Controllers;
use App\UserContact;
use Illuminate\Http\Request;
class UserContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name'=>'required|max:5'
]);
$userContact=new UserContact();
$userContact->name=$request->input('name');
$userContact->email=$request->input('email');
$userContact->description=$request->input('description');
$userContact->visibility=$request->input('visibility');
$userContact->created_by=$request->input('created_by');
$userContact->save();
return response()->json([
"message"=>"student record created"
],201);
}
}
UserContac.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserContact extends Model
{
//
}
----------
My Postman url
http://amaderproject.test/api/storingData
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'], /*...*/);
Here is my routes.php file
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for 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.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/login', function(){
return view('auth.login');
});
Route::post('/login', 'Auth\AuthController#authenticate');
Route::get('/home', 'HomeController#index');
Here is my AuthController.php file
<?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;
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 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']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'user_name' => 'required|max:255|unique:users',
'full_name' => 'required|max:255',
'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 User::create([
'user_name' => $data['user_name'],
'full_name' => $data['full_name'],
//'password' => bcrypt($data['password']),
'password' => $data['password'],
]);
}
//Auth::attempt(['user_name' => $user_name, 'password' => $password])
public function authenticate()
{
if (Auth::attempt($request->all()) {
var_dump(Auth::user())
if(Auth::user()->type == 'admin') {
return "Welcome company admin let's create some user for your company";
# code...
} elseif(Auth::user()->type == manager) {
return "Welcome manager let's manage your coaches";
}elseif(Auth::user()->type == 'counterman'){
return "Welcome counter person let's sell some ticket's";
}else
{
return "Welcome online user let's make a relationship with me";
}
return "Gonnnaaa";
//return redirect()->intended('dashboard');
}else
{
return "you are fucked";
}
}
}
In my project I want redirect my user to different pages according to there type . I tried to implement this in different ways . At last I tried to use authenticate method inside AuthController as suggested in laravel doc's but I am getting AuthController not exist error . What wrong I am doing and what can be better approach in my case ? thanks in advance . I have not edited anything except AuthController and routes.
If you don't want to implement something new by yourself, you could create a new TypeBasedAuthController that extends the AuthController.
Then, you would decorate its parent by implementing a postLogin method that calls the parent postLogin. After the login logic, you could change the $redirectTo property as you wish.
It should make sense... :)
EDIT: take a look to this link if you want to know something more about the decorator pattern in PHP :)
EDIT2 - Important: after another deeper search, I have found a better solution. All you have to do is to overwrite this method in your new TypeBasedAuthController.
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
// HERE: control the user that has logged in and change the value
// of $this-redirectTo property accordingly.
return redirect()->intended($this->redirectPath());
}
It should be quite clear now.
I am new in laravel app development. When I am using auth middleware, then it works fine for unregistered user(redirecting to login page). But when logged user going to visit that page, then its redirecting to home page (root directory).
below the route from routes.php code is
Route::group(['middleware' => 'auth'], function () {
Route::resource('/edit', 'userController#edit');
});
Below my userController.php code is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\allUsers;
class userController extends Controller
{
public function index(){
}
public function show($id){
}
public function edit(){
return view('auth.user_edit');
}
}
Below my authController code is
<?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 = '/dashboard';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Anyone help me please.
You can overwrite the $redirectTo variable in your AuthController:
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/dashboard';
Update:
Try Changing your route:
Route::group(['middleware' => 'auth'], function () {
Route::get('edit', 'userController#edit');
});
Route::resource creates all CRUD routes for your automatically.
https://laravel.com/docs/5.1/controllers#restful-resource-controllers
Yes Problem solved. Just changed the route
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/edit', 'userController#edit');
});