I modify the login function in Login controller using credentials function
protected function credentials(\Illuminate\Http\Request $request)
{
return ['email' => $request->email, 'password' => $request->password, 'status' => 1];
}
although the function is work, but i need to return an error message to show that "Account is suspended" in login page if user's status not equal to 1.
How can i modify the error message?
You should make a middleware for that so you can use it. not only in your login function.
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class CheckStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->status != 1) {
return redirect('yourloginpageroute')->withInfo("Account is suspended");
}
return $next($request);
}
}
Assuming that you have a status row in your auth.
Related
I have a payment card. there is a link at the bottom of it that derives guest users to the login page. I want users redirect to the card payment route again after login. can you please help me how can I do that?
by the way I am new in laravel.
thanks for your time guys :X
here is loginController.php :
<?php
namespace App\Http\Controllers\Auth;
use App\Events\LoginLogged;
use App\Rules\Recaptcha;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('throttle:3,1')->only('login');
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
//'g-recaptcha-response' => ['required', new Recaptcha]
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return array_merge(($request->only($this->username(), 'password')), ['usr_is_admin' => 1]);
}
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'usr_name';
}
protected function authenticated(Request $request, $user)
{
event(new LoginLogged($request, $user));
}
}
here is redirectIfAuthenticated.php middleware:
<?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()->route('dashboard');
}
return $next($request);
}
}
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available. For example :
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
My laravel application route configured on routes/api.php is.
<?php
use Illuminate\Http\Request;
Route::post('see_all_product', 'API\ProductController#see_all_product');
?>
Issue is i want to sent list of product but if user authenticated then send product favorite flag 1, and if not authenticated then send return favorite 0
But both case send product list with favorite flag.
If i logged in with my user id and password and send request for see_all_product that time i m getting blank user.
$user = $request->user();
But if i set route like below i m getting user details.
<?php
use Illuminate\Http\Request;
Route::group(['middleware' => 'auth:api'], function(){
Route::post('see_all_product', 'API\ProductController#see_all_product');
});
?>
Now issue is how can i get details if authorization set in the header with same api.
<?php
use Illuminate\Http\Request;
Route::post('see_all_product', 'API\ProductController#see_all_product');
?>
My see_all_product Function
public function see_all_product(Request $request){
try {
$user = $request->user();
} catch (Exception $ex) {
Log::error($ex);
}
}
API is same for both authenticated and guest user.
I pass authorization token in both case but middleware route i get user details but non middleware route i dont get user information.
Please guide me where i can miss something?
I think you can do it by the way instead of $request->user():
if (auth('api')->check()) {
$user = auth('api')->user();
}
Turn off ['middleware'=> 'auth:api']
use: $request->user('api'); in your controller.
Guests can use the api but user is null;
Auth users can use api as a real user.
alt:
Auth::guard('api')->user();
auth('api')->user();
I didn't test this method on old versions of Laravel, but it should work just fine on the latest ones.
You can create another Middleware that allows ether authenticated or guest users to proceed.
If the user is authenticated then the middleware will prepare the Auth object and auth() function for you.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;
class AuthOptional
{
/**
* The authentication factory instance.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$this->authenticate($request, $next, $guards);
return $next($request);
}
/**
* Determine if the user is logged in to any of the given guards.
*
* #param \Illuminate\Http\Request $request
* #param array $guards
* #return void
*
*/
protected function authenticate($request, $next, array $guards)
{
if (empty($guards)) {
$guards = [null];
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
//If unauthenticated allow the user anyway
$this->unauthenticated($request, $next, $guards);
}
/**
* Handle an unauthenticated user.
*
* #param \Illuminate\Http\Request $request
* #param array $guards
* #return void
*
*/
protected function unauthenticated($request, $next, array $guards)
{
return $next($request);
}
}
Import the newly created Middleware under app/Http/kernel.php
protected $routeMiddleware = [
....
'auth.optional' => \App\Http\Middleware\AuthOptional::class
];
And finally use it like this:
<?php
Route::group(['middleware' => ['auth.optional:api']],
});
?>
Now auth()->user() will return the user if user is authenticated and
null if it's not
i am not using the laravel make:auth but instead i have created my own login page.
i have this button "share your adventure" and if the the user click the button he should be redirected to the adventurefor.blade.php if he is already logged in but if he is not currently log in, he will be redirected to the login page with the use of a middleware..
here is my web.php
<?php
Route::get('login','userLog#login');
Route::post('loginsuccess','userLog#submit');
Route::get('share', 'userLog#shareadven')->middleware('user');
Route::post('sharesuccess','userLog#shareit')->middleware('user');
here is my controller
public function login(){
return view('logs.login');
}
public function submit(Request $request){
$this->validate($request,[
'email' => 'required',
'password' => 'required'
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']]))
{
return Redirect::to(URL::previous())
-> with('info', 'Logged In Successfully!');
}
else{
return redirect('logs.login') -> with('infos', 'Incorrect Email/Password!');
}
public function shareadven(){
return view('adventure.adventureform');
}
here is my middleware that i created
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class User
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if( Auth::check()){
return $next($request);
}
return redirect('login');
}
}
and here is the code for my button
<a class="btn btn-primary btn-lg" href="{{ url('share') }}" role="button">Share your ADVENTURES</a>
my problem is im getting redirected to the login page after login. it should redirect to the original path that the user wants to go
You can follow the logic of the Laravel trait AuthenticateUsers that redirects to the intended path after the login.
This is the source from Laravel:
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
And change your controller from
return Redirect::to(URL::previous())->with('info', 'Logged In Successfully!');
to
return Redirect::intended('your-path')->with('info', 'Logged In Successfully!');
Another way is to use the middleware as you where doing, but checking if the request has a "special attributes" that defines where the user should be redirected.
I have a fresh project of Laravel 5.6 installed. I changed create_users_migration, added $table->boolean('is_active'); field. Now, I want when user is trying to login, to check if is_active field is set to true.
I tried to rewrite standard AuthenticatesUsers method :
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
After password I added line 'is_active' => true, , and now, when I press Log In button, it returns me an array_map(): Argument #2 should be an array error.
I tried to just copy-paste this method in LoginController, but it gives me same error. Any ideas, or may be is here another solution?
Full LoginController code :
<?php
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');
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'is_active' => true,
]);
}
}
You are editing the wrong method. This method validates the request and "true" is not a validation rule, that's why you are getting the error.
Here is a simple solution. Override the credentials method on your LoginController as below.
protected function credentials(Request $request)
{
$data = $request->only($this->username(), 'password');
$data['is_active'] = true;
return $data;
}
So this way only active users can login.
You can also create a middleware and use it to send the users that have not activated their account to activation page.
I did this for one project with a middleware :
<?php
namespace App\Http\Middleware;
use Closure;
class isActiv
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->isActiv()){
return $next($request);
}else{
return redirect()->route('dashboard')->with('errors', 'Votre compte utilisateur n\'est pas activé sur le site. Veuillez contacter un administrateur pour résoudre le problème.');
}
}
}
Then in my route file web.php :
Route::group(['middleware' => ['isActiv'] ], function(){
And in my user model :
public function isActiv(){
if($this->is_activ == 1 || $this->is_admin == 1){
return true;
}
return false;
}
In Laravel 5.2, I have added has_login field in the users table.
Where do I add logic to prevent user logging in if has_login is value 0 in the users table? I use AuthController.php for authentication and use AuthenticatesAndRegistersUsers without using login() / authenticate() functions in AuthController.hp file. Login work fine.
I personally tend to do this in the middleware, but you can also do it outside of that.
Here's a middleware example:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RequireHasLogin
{
/**
* 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())
{
if (!Auth::guard($guard)->user()->has_login)
{
Auth::logout();
if ($request->ajax() || $request->wantsJson())
{
return response('Unauthorized.', 401);
}
return redirect()->guest('/auth/login');
}
}
return $next($request);
}
}
Though I think some people do this too:
Auth::guard()->attempt(["email" => $email, "password" => $password, "has_login" => true])
This should point you in the right direction -
https://laravel.com/docs/master/authentication#authenticating-users