Laravel route group middleware issue - laravel-5

I keep some laravel routes in the middleware auth group as:
Route::group(['middleware'=>'auth'],function(){
Route::controller('Activities', 'ActivitiesController');
Route::get('foo','FooController#getFoo');
.....
});
When I try to login to access these page, I am unable to login and url redirect to login page again and again. But If I use constructor as:
public function __construct()
{
$this->middleware('auth');
}
In those controllers It works perfectly. What is route group problem?

Route has a ::middleware class that you can use:
Routes > web.php
Route::middleware(['auth'])->group(function(){
Route::get('/activities', 'ActivitiesController#index');
});
You can also use Route::resource(); which I prefer. If you don't know what it does, here are the docs: https://laravel.com/docs/5.8/controllers#resource-controllers

This works for me , in route
Route::group(['middleware'=>'auth'],function(){
Route::controller('activities', 'ActivitiesController');
});
then controller
<?php namespace App\Http\Controllers;
class ActivitiesController extends Controller {
public function getIndex() {
return 'you are in;
}
}
on attempt to visit /activities I was redirected to login page , and on success back to \activities with 'you are in'.

In web.php:
$roleGeneral = role1.'~'.role2.'~'.role3.'~'.role4;
Route::group(['middleware' => ['permission.role:'.$roleGeneral]], function() {})
In Kernel.php:
protected $routeMiddleware = [...,
'permission.role' => \App\Http\Middleware\CheckPermission::class,
];
In CheckPermission.php:
public function handle($request, Closure $next, $role)
{
$roleArr = explode('~', $role);
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$roleLogin = SysRoleModel::where('id', $user->role_id)->first();
if (in_array($roleLogin['name'], $roleArr)){
return $next($request);
}else{
return \Redirect::back()->withMessage('You are not authorized to access!');
}
}

Related

Laravel API: Illuminate\Contracts\Container\BindingResolutionException: Target class

i am working on API. I want to create login api. i have created UsersController in API folder it in controllers. when i run in postman i shows an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController] does not exist. in file F:\University_Data\xamp\htdocs\stylooworld\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 835`
I don't now why its duplicated the routing path Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController]
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
UsersController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
class UsersController extends Controller
{
//
public function loginUser(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
echo "<pre>";
print_r($data);
die;
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
// check email is activated or not (Only Work Online Server)
/* $userStatus = User::where('email', $data['email'])->first();
if ($userStatus->status == 0) {
Auth::logout();
$message = "Your account is not activated yet! Please confirm your email to activate!";
Session::flash('error_message', $message);
return redirect()->back();
}*/
//update user cart with user id
if (!empty(Session::get('session_id'))) {
$user_id = Auth::user()->id;
$session_id = Session::get('session_id');
Cart::where('session_id', $session_id)->update(['user_id' => $user_id]);
}
return redirect('/');
} else {
$message = "Invalid Username or Password";
Session::flash('error_message', $message);
return redirect()->back();
}
}
}
}
I don't know why this happen?
Update the routes.
For details please check (ref link) https://laravel.com/docs/8.x/upgrade and https://laravel.com/docs/8.x/releases#routing-namespace-updates
Use like this
api.php
If not working
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
Then Use like this
use App\Http\Controllers\API\UsersController;
Route::post('login', [UsersController::class, 'loginUser']);
import method Request
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
on click (import method) always ready.
are you ok.

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

Laravel: Redirect login & register if logged in?

I'm struggling to get the login/register pages to redirect the user if already logged in.
in routes.php
Route::group(array('before' => 'auth'), function()
{
Route::get('hud', 'HomeController#index')->name('hud');
Route::get('search', 'HomeController#search')->name('search');
Route::get('profile', 'UsersController#index')->name('profile');
Route::get('clients', 'ClientsController#index')->name('clients');
Route::delete('clients/{id}', 'ClientsController#destroy');
Route::resource('projects', 'ProjectsController', array('only' => array('show')));
});
I've tried no_auth and it just breaks. Am I missing something?
You should set the redirect path for when a given visitor is authenticated user.
You can do so in: App\Http\Middleware\RedirectIfAuthenticated
Example:
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return redirect('/dashboard');
}
return $next($request);
}
Stackoverflow: laravel redirect if logged in
You want to redirect already registered user to Homepage whenever they try to hit /login.
Here's how laravel tries to achieve that.
Firstly this is achieved through App\Http\Middleware\RedirectIfAuthenticated.
However a key to this middleware is registered to guest in this file app\Http\Kernel.php under array protected $routeMiddleware.
Then in your login controller presumably at app\Http\Controllers\Auth\LoginController.php
In the construct method, We have something like this:
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}

Laravel-redirects even authenticated users to login

Before minus this question, or report a duplicate, please read it completely.
I use a default Laravel Autentification. But for some reason, it's somehow broke down.
When I try to login or register, if auth is success it redirects try to redirects me to a correct link, but but at the same time returns me to /login.
Example with dump
Debugbar after trying auth
Source files
1. My routes:
Auth::routes();
Route::get('/confirm', function () {
return view('confirm');
})->name('confirm');
Route::post('/confirm', 'EmployeeController#store')->name('addworker');
Route::get('users/{id}', 'EmployeeController#show')->where('id', '[0-9]+')->name('account');
Route::get('/home', 'HomeController#index')->name('home');
2. Changes into login and register controllers:
protected function redirectTo()
{
return route('account',['id'=> auth()->user()->id]);
}
3.Methods in a EmployeeController, that action in auth:
public function __construct()
{
$this->middleware('auth');
$this->middleware('confirmated');
}
public function show($id)
{
return view('account');
}
4. My middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\Employee;
class CheckConfirm
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
$id = Auth::id();
$empl = Employee::where('user_id', '=', $id)->first();
Debugbar::info($empl);
if ($empl == null) {
return redirect()->route('confirm');
} else {
dump($empl);
return $next($request);
}
} else {
return redirect()->route('login');
}
}
}
What did not help me
clearing the cache and browser history including the artisan commands: cache:clear and config:clean
Disable my middleware or auth midlleware in controllers constructor
Disable all middleware in contructor led to this
Solutions in question duplicates, or in other forums
If there is not enough information in the question, you can download my entire project on GitHub: https://github.com/Vladislav2018/last.chance/

Laravel 5.4 Route [login] not defined

Hi I have following route and constructor in my controller i want to check if user is authenticated or not if not then redirect to /warehouse/login page. but for some reasons i am getting Route [login] not defined error.
I am migrating my functions from Laravel 4.2 to Laravel 5.4
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if (!Auth::check()) {
$url = URL::current();
$routeName = Route::currentRouteName();
if ($routeName != "AdminLogin" && $routeName != 'admin') {
Session::put('pre_admin_login_url', $url);
}
return redirect('/warehouse/login');
}
return $next($request);
}, array('except' => array('WarehouseAdminLogin', 'WarehouseAdminVerify')));
}
Routes:
Route::get('/warehouse', 'WarehouseController#index');
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
You didnt define your login function.
make a function
public function login()
{'your code'}
in your WarehouseController
Edited: the problem is that you have not a route named login. This error is caused by:
$this->middleware('auth');
because this code in the auth middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
So what to do is remove auth middleware and try again or make a route with login name.

Resources