Authenticate extends Middleware redirect me if i have permission - laravel

Hello please can explain me why it happedned . i hve make middleware and was work ok but suddenly stop and redirect me any way problem in method where Authenticate .php
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
this return me to login if i logged not allow for user he have permisson to go this
middleware
class AdminMiddleware
{
/**
* 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)
{
if (Auth::check()){
if (Auth::user()->user_type == 1){ //Any Manger Can Access only Not Users
return $next($request);
}else{
return redirect()->back();
// abort(403);
}
}else{
return redirect()->back();
}
}
}
and user_type == 1 was try in middle ware dd(Auth::user()); but if put it in side method redirectTo
dd(Auth::user());
return info bout user but not return nothing direct go to login in Authenticate ,
Route::group(['middleware' => 'auth:admin'], function () {
Route::get('admin/dashboard', function () {
return view('admin.index');
})->name('admin.dashboard');
and befor it was work ok . what problem !

Related

Can't access user object

I am trying to handle roles in my application but I have a problem: when I clear cache or logout from the app and log in again I want to be redirected to the login but it sends me the following error
Trying to get property 'rol' of non-object.
<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->rol == 'Admin') {
return $next($request);
}
return redirect()->guest('login');
}
}
you have to check if user is logged in, and then ask if user have rol
use Illuminate\Support\Facades\Auth;
public function handle($request, Closure $next)
{
if (Auth::check()) {
if (Auth::user()->rol == 'Admin') {
return $next($request);
}
return redirect()->guest('login');
}
return redirect()->guest('login');
}

My Middleware redirects to home page everytime

I have made a quiz when the user unlocks the quiz then only the user can access the quiz page suppose 127.0.0.1:8000/quiz1. But I have unlocked the quiz, then too my middleware takes me to /home page.
I have tried this logic but it didn't worked.
<?php
namespace App\Http\Middleware;
use Closure;
use App\Theme_User;
use App\User;
use Auth;
class UnlockMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = auth()->user()->id;
$theme_user = Theme_User::find($user);
if($theme_user->unlocked == 1){
return $next($request);
}
else {
return redirect('/login');
}
}
}
In my Theme_User there is user_id and unlocked stored but that is not working for me.
You need to check if they are logged in first, like so with \Auth::check()...
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(\Auth::check()) {
$user = \Auth::user()->id;
$theme_user = Theme_User::find($user);
if($theme_user->unlocked == 1){
return $next($request);
}
// Logged in but not unlocked
}
else {
return redirect('/login');
}
}
I have no idea what the logic is meant to be behind logged in but not unlocked, you'll need to fill that gap
It might be worth checking if user is logged in before trying to get user id from auth.
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user = auth()->user()->id;
$theme_user = Theme_User::find($user);
if($theme_user->unlocked == 1){
return $next($request);
}else{
return redirect('whatever_page_if_user_is_logged_in_but_not_unlocked');
}
}else {
//this only happens if user is not logged in
return redirect('/login');
}
}

Webpage routing according to user type in laravel

I have used make:auth command to create basic register and login. I have created an extra field in register page which gets user type*(admin,employee or visitor)*.
Now my problem is I need to navigate to three different page for each of them by accessing that user type from the users table in database. Any help any suggestion are most welcome.
As far as I know, Laravel 5 comes with \App\Http\Middleware\RedirectIfAuthenticated middleware class which intended to do redirection once user logged in.
So in this case, the handle function of the middleware would be
/**
* 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()) {
$userType = Auth::user()->type;
if ($userType == 'admin') {
return redirect('/admin');
} else if ($userType == 'employee') {
return redirect('/employee');
} else if ($userType == 'visitor') {
return redirect('/visitor');
}
}
return $next($request);
}
Laravel too, has leave out a blank authenticated method which you can fill out on \App\Http\Controllers\Auth\LoginController which is inherited from Illuminate\Foundation\Auth\AuthenticatesUsers trait
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$userType = $user->type;
if ($userType == 'admin') {
return redirect('/admin');
} else if ($userType == 'employee') {
return redirect('/employee');
} else if ($userType == 'visitor') {
return redirect('/visitor');
}
}

Middleware for user roles in Laravel

I am creating an Admin Panel and I have problem with the access , I am using One-to-Many relation and I have the table user with role_id=3.
This middleware works correctly but I need to protect the routes correctly.
class Administrador
{
/**
* 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)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/administrador');
}
}
return $next($request);
}
}
The routes are correctly set, but I don't know how to send the user's role in this Middleware.
...
EDIT
If you want to combine in one middleware Administrador it would be:
class Administrador
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $roles = null, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/administrador');
}
}
$roles = explode('|', $roles);
if (! in_array(Auth::guard($guard)->user()->role_id, $roles) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
Example usage on route:
Route::group(['middleware' => 'administrador:1|2'], function () {});
administrador:1|2 replace the value with your role ids separated by |, if you want to use another guard then you can pass it as second parameter, example: administrador:1|2,custom_guard. This way you can define multiple roles that able to access your admin screen.
If you would rather want to use one fixed role:
class Administrador
{
/**
* 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)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('/administrador');
}
}
if (Auth::guard($guard)->user()->role_id !== 3) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}

Laravel 5 authentication weird behaviour

Before explaining the problem. Let me explain, things i have tried out.I ran the command
php artisan make:auth
it created files like HomeController, a directory auth which had register & login pages. in my application i have a directory Pages. i opened up AuthenticatesUsers trait and changed
return view('auth.login'); to my view return view('Pages.login');
After that: i changed view of showRegistrationForm methods view return view('auth.register'); to return view('Pages.register'); from RegistersUsers.php
Here is UserController
lass UserController extends Controller {
//constructor
public function __construct() {
}
//Admin: return view
public function showCommunity() {
$Community = Community::latest()->get();
$Ideas = Idea::latest()->get();
return view('privatePages.communities', compact(array('Community', 'Ideas')));
}
Routes that were generated by php artisan make:auth
Route::auth();
//Auth Controller
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Now coming back to the problem. yesterday morning. When i opened up localhost/auth/register. Registration process was working fine and data was storing in DB. But there was an issue with login view. Neither it was throwing an error on wrong credentials nor logged the user in on correct credentials. Later in the evening. Login view was working and throwing an error even upon entering correct credentials it said Credentials does not match record. But registration process was not working and data was not storing in DB. It really confusing.
Here is AutheticatesUsers File
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
//use App\Http\Requests\UserRequest;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();
}
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$view = property_exists($this, 'loginView')
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {
return view($view);
}
return view('Pages.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
return $this->login($request);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
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());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* #return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* #return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
One more thing for registration process. I am not using laravel's Request rather my own created 'UserRequest`. If any other information is needed. i would provide that. Any help would be appreciated.

Resources