Laravel 5.8 authentication - laravel

Hi i've a problem with laravel authentication system (5.8) The problem is that I need to login two times to enter my site
My routes file is
Route::get('/', 'RefundsController#index');
Route::get('/polizza', 'RefundsController#indexRefunds')->name('polizza');
Auth::routes();
--------------other routes------------------
RefundsController
public function __construct()
{
$this->middleware('auth');
}
public function index(){
return view('auth.login');
}
public function indexRefunds(Request $request){
DB::enableQueryLog();
$grafici = 1;
$getAverageLiquidati = DB::table('refunds')
->select(DB::raw("AVG(DATEDIFF(date_liq, date_ref)) AS avgliq"))
->where([
['disactive','=', 1],
['date_liq','<>','0000-00-00'],
['status_ref','>', 5]
])
->get();
$getAverageRifiutati = DB::table('refunds')
->select(DB::raw("AVG(DATEDIFF(date_status, date_ref)) AS avgrif"))
->where(function($q) {
$q->where('status_ref','=', 2)
->orWhere('status_ref','=', 3)
->orWhere('status_ref','=', 4);
})
->where([
['disactive','=', 1],
['date_liq','<>','0000-00-00'],
])
->get();
//dd(DB::getQueryLog());
//dd($getAverageRifiutati);
return view('pages.modify', compact('grafici','getAverageLiquidati','getAverageRifiutati'));
}
login blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<!--<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{-- old('remember') ? 'checked' : '' --}}>
<label class="form-check-label" for="remember">
{{-- __('Remember Me') --}}
</label>
</div>
</div>
</div>-->
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
{{--#if (Route::has('password.request'))--}}
<!--<a class="btn btn-link" href="{{-- route('password.request') --}}">
{{-- __('Forgot Your Password?') --}}
</a>-->
{{--#endif--}}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
my 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 = '/polizza';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
In my Middleware
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('/polizza');
}
return $next($request);
}
}
When i connect to https://www.example.com/refunds/ because of definition in RefundsController it takes me to https://www.example.com/refunds/login but when i insert credentials it takes me to https://www.example.com/refunds/ with again login form then when i insert credentials it finally takes me to https://www.example.com/refunds/polizza
I dont understand why :(

The first redirect happens because in your Controller constructor, you are setting the middleware to auth. Hence, all unauthorized requests to any methods in that Controller will be redirected to default log in page. (https://www.example.com/refunds/ redirects to https://www.example.com/refunds/login)
When you enter your credentials there, Laravel takes you to your intended route (the route you tried to access without being authenticated, and that is https://www.example.com/refunds/).
This time you are authenticated, so in your controller, your index method is set to return log in view, so the view is being returned and rendered, and the form is being shown for the second time now. Now, that you log in for the second time, the Log In controller will redirect you to https://www.example.com/refunds/polizza, as there intended route does not exists, and it uses the default route which is correctly set to /polizza.
How to resolve this issue?
In your controller's constructor, change the line with:
$this->middleware('auth')->except(['index']);
This way, you will exclude the index function from the auth middleware and it can be accessible to the public. The request should no longer redirect you to the default log in page. Now, going to https://www.example.com/refunds/ will just render a log in form, as you specified in your controller. When you log in with that form, it will take you to /polizza route.

Related

Laravel 8 Form Request Validation Redirect to Index page instead same page and show error

On localhost all is good, but when I deploy the application to the server not working. If form request validation fails instead of bringing me back to the same page and showing an error, it redirects me to the index page.
config.blade.php
<form method="POST" action="{{ route('config.update', $config->id) }}">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col">
<label class="col-form-label">Name</label>
<input id="name" type="text" class="form-control" name="name" value="{{ $config->name }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Address</label>
<input id="address" type="text" class="form-control" name="address" value="{{ $config->address }}">
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">Phone</label>
<input id="phone" type="tel" class="form-control" name="phone" value="{{ $config->phone }}" required>
</div>
</div>
<div class="form-group row mt-3">
<div class="col">
<label class="col-form-label text-md-right">E-mail</label>
<input id="email" type="email" class="form-control" name="email" value="{{ $config->email }}" required>
</div>
</div>
<div class="form-group row mt-4 mb-0">
<div class="col-md-12">
<button type="submit" class="btn btn-primary button-full-width">Save changes</button>
</div>
</div>
</form>
web.php
Route::resource('/admin/config', 'Admin\ConfigController');
ConfigController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\ConfigServices;
use App\Http\Requests\ConfigRequest;
use App\Models\Config;
class ConfigController extends Controller
{
protected $configServices;
public function __construct(ConfigServices $configServices) {
$this->middleware('auth');
$this->configServices = $configServices;
}
...
public function update(ConfigRequest $request, $id)
{
$config = $this->configServices->updateConfigById($request, $id);
return redirect()->back();
}
...
}
ConfigRequest - here is the problem
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConfigRequest 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 [
'name' => 'required|string|max:255',
'address' => 'nullable|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:9|max:15',
'email' => 'required|email:rfc',
];
}
}
Form Request return to index page instead same page. On localhost working everything, but when I deploy the app to server a problem arises.
When data on form request validated correct return me back on the same page and show success, but when form request failing redirect mine for some reason to the index page.
A problem arises in Laravel 8, this code worked well in previous Laravel versions.
Can someone help me, please?
In your custom request you need:
/**
* The URI that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirect = '/dashboard';
or
/**
* The route that users should be redirected to if validation fails.
*
* #var string
*/
protected $redirectRoute = 'dashboard';
You can find more in the docs.
In the docs for older versions of Laravel these properties don't exist.
Do you have error parts in your blade?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#if ($message = Session::get('unique'))
asdsad
#endif
#endforeach
</ul>
</div>
#endif

Why typing incorrect password shows incorrect login error?

I have used php artisan ui bootstrap --auth to install authentication in my app. When I type right login, wrong password and submit my login form, the login input lights red as invalid and invalid login message is showing and zero information about wrong password. Have you any idea, why it happens?
That's my form, I can provide any other part of code, but I don't know, where should I look for mistakes.
<form method="POST" action="{{ route('login') }}" class="mt-4">
#csrf
<div class="form-group row">
<div class="col-md-6 offset-md-3">
<input placeholder="{{ __('Login') }}" id="login" type="text" class="form-control #error('login') is-invalid #enderror" name="login" value="{{ old('login') }}" required autocomplete="login" autofocus>
#error('login')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
#php dump($errors); #endphp
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-3">
<input placeholder="{{ __('auth.Password') }}" id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('auth.Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-3 text-right">
<button type="submit" class="btn btn-success">
{{ __('auth.Log in') }}
</button>
</div>
</div>
</form>
Controllers/Auth/LoginController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
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');
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'login';
}
}
Because the password is correctly formatted.
If you type an empty password, you will see the password formatting validation trigger.
If you look at the AuthenticatesUsers trait, you will see the following code.
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
When authentication fails (look-up in the database), this will send back a validation exception on the username key.

Why can't I redirect to home after logging in in laravel 8?

I'm having trouble with laravel 8, I'm using the default laravel authentication, but it seems that after I log in I can't redirect to the Home page. I just added this to the LoginController public function username() { return 'username'; }
Here is my table protected $table = 'TO_USER_LOGIN';, I also added the fillables.
my HomeController is fine it just that it won't let me redirect to the Homepage. The protected $redirectTo = RouteServiceProvider::HOME; also has a default value '/home'
LoginView
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9 col-sm-12">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">TRAVEL ORDER SYSTEM</h1>
</div>
<form method="POST" class="user" action="{{ route('login') }}">
#csrf
<div class="form-group">
<input id="username" type="text" placeholder="Username" class="form-control form-control-user #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="off" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group">
<input id="password" type="password" placeholder="Password" class="form-control form-control-user #error('password') is-invalid #enderror" name="password" required autocomplete="off">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<hr>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
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 redirectTo(){
Redirect::route('home');
}
public function username()
{
return 'username';
}
public function __construct()
{
$this->middleware('guest',['except' => ['logout', 'userLogout']]);
}
public function userLogout(){
Auth::guard('web')->logout();
return redirect('/');
}
}
I finally found the problem! It was with my table all along, laravel was looking for a column id which my table doesn't have instead it has an incremented UserID so I changed it to id and it worked! There was no error so basically, I tried thinking as much as I could even tried making a new project just to see if I have a problem with my current one.

Laravel login not working properly after changing the default username and password

I have a custom table for users named 'iw_users' and inside, i have also a custom column for email and password named 'iu_email' and 'iu_password'. What i want to do here is to set my iu_email as the email and iu_password as a password on login, register, and forgot password (basically all functionalities that laravel Auth provides).
I have followed the answer on this thread: Laravel: How can i change the default Auth Password field name
But when i try to login (with correct credentials) the page is just refreshing and redirecting me again to log in page (I can confirm that laravel did not authorize me using Auth::check()).
Also, the color of the error and input are not red whenever i try to login with wrong credentials.
This is my App\User code:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'iw_users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'iu_user_id', 'iu_last_name', 'iu_first_name', 'iu_email', 'iu_mobile_no', 'iu_password', 'iu_gender', 'iu_country', 'iu_role', 'iu_photo', 'iu_status', 'iu_ipaddress'
];
public function getAuthPassword()
{
return $this->iu_password;
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// Commented. i don't have 'password' and 'remember_token' in iw_users
// protected $hidden = [
// 'password', 'remember_token',
// ];
}
This is my LoginController.php
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 = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'iu_email';
}
}
This is my login.blade.php form
<form class="form-horizontal" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="iu_email" value="{{ old('iu_email') }}" required autofocus>
#if ($errors->has('iu_email'))
<span class="help-block">
<strong>{{ $errors->first('iu_email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
I would suggest you to check https://scotch.io/#sukelali/how-to-create-multi-table-authentication-in-laravel
Have you got any error while debugging this? I doubt, it's unable to override their default fields.

Prevent login if user isnt approved laravel 5.4

I checked all around for information about how to check on login if user is approved or not and then redirect to logged in or give an error. Now i am little confused because in internet there are a lots of posts and every one is different. So can anyone can help me to deal with this? Also it would be really nice to explain how it works (sintaxes and all other stuff)
User.php:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'companyname', 'email', 'password', 'VAT', 'companyphone',
'companystreet', 'companycity', 'companycountry', 'companypostcode'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
LoginController :
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
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 = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
login.blade.php :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
#if($status = Session::get('status'))
<div class ="alert alert-info">
{{$status}}
</div>
#endif
<form class="form-horizontal" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Also in my DB is boolean field "activated" default 0
#Karlis Pokkers
Middleware is one option but, I would like to go for little hack provided by Laravel documentation.
You can override Laravel's attemptLogin method.
Add this code to your app > Http > Controllers > Auth > LoginController:
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return Auth::attempt(['username' => $request->username, 'password' => $request->password, 'activated' => 1 ]);
}
No need to write you own LoginController. Use Laravel's default authentication Controllers.
You can check out different sites for that. Answer on Laracast
With laravel its very simple. You have to create a new middleware or extend the app/Http/Middleware/RedirectIfAuthenticated.php middleware.
A good documentaion you can find here: https://laravel.com/docs/5.5/middleware
For example:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::user()->activated) {
return redirect('/home');
}
return $next($request);
}

Resources