How to check user status while login in Laravel 5? - laravel

I have used Laravel Authentication (Quickstart). But I need to check the status of the user (approved/pending). If not approved, then an error will be shown in the login page. I need to know in which file I have to make the change and what is the change. Currently I am working on Laravel 5.3.

You can create a Laravel Middleware check the link for additional info
php artisan make:middleware CheckStatus
modify your middleware to get
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
//If the status is not approved redirect to login
if(Auth::check() && Auth::user()->status_field != 'approved'){
Auth::logout();
return redirect('/login')->with('erro_login', 'Your error text');
}
return $response;
}
}
then add your middleware to your Kernel.php
'checkstatus' => \App\Http\Middleware\CheckStatus::class,
and finally add the middleware to your route
Route::post('/login', [
'uses' => 'Auth\AuthController#login',
'middleware' => 'checkstatus',
]);
I hope it helps

I found a simple solution for this. Artisan create App\Http\Controllers\Auth\LoginController, in this default controller just add this code if you have some conditions to login, for example I have a field state, you posibbly have status, email_status or other.
// Custom code for Auth process
protected function credentials( Request $request )
{
$credentials = $request->only($this->username(), 'password');
$credentials['state'] = 1;
return $credentials;
}

upper answer saves me
if (Auth::attempt(['email'=>$input['email'],'password'=>$input['password'], 'user_status'=>1 ]))
this will check the status

Just Add following method in my LoginController works like charm
protected function authenticated(Request $request, $user)
{
if ($user->yourFirldName != "Active") {
Auth::logout();
return redirect('/login')->with('error', 'Looks Like Your status is InActive');
}
}

I don't agree with upper answer, which will lead to your application performance is very low, and also don't recommend to modify the Laravel's source code.
So you can rewrite getCredentials function to your app\Http\Controllers\Auth\AuthController.php file like this:
<?php
//app\Http\Controllers\Auth\AuthController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
//you need add this function
protected function getCredentials(Request $request)
{
$data = $request->only($this->loginUsername(), 'password');
$data['is_approved'] = 1;
return $data;
}
}
then you can use Laravel Authentication (Quickstart) directly.
Hope this will help.

The pinned answer is the best approach.
Just a note: if you are using Laravel 5.8+ you need use:
//Default Auth routes
Auth::routes();
//Override and add middleware
Route::post('/login', [
'uses' => 'Auth\LoginController#login',
'middleware' => 'checkstatus',
]);

Follow the steps...
First add a column in your user table (suppose is_approved)
In App/Http/Controllers/Auth/LoginController file
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'is_approved'=>1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
Hope this will help

Auth/LoginController
Though it is a long time from the question created date. You can go this way.
Go to Auth/LoginController and add this line.
protected function credentials(Request $request)
{
return [
'email' => $request->email,
'password' => $request->password,
'status' => 1,
];
}
For this to work you have to have a column named 'status' in users table. 1 is for active and 0/2 is for inactive user.
Hope this will work for you.

public function login(Request $request){
if ($request->isMethod('post')) {
$data= $request->all();
$roles=[
'email' => 'required|email|max:255',
'password' => 'required',
];
$customessage=[
'email.required' =>'Email is required',
'email.email' => 'Email is not vaild',
'password.required' => 'Password is required',
];
$this->validate($request,$roles,$customessage);
if(Auth::guard('admin')->attempt(['email'=>$data['email'],'password'=>$data['password'],'status'=>1])) {
return redirect('admin/dashboard');
} else {
Session::flash('error_message','You are not Active by Admin');
return redirect()->back();
}
}
return view('admin.admin_login');
}

Related

Class App\Http\Controllers\API\UserController does not exist

I am Having the issue of not getting token in postman as well as the following problem
ReflectionException
…\vendor\laravel\framework\src\Illuminate\Container\Container.php790
user controller does not exist
my route file;
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController#details');
});
My controller file;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\Request;
class UserController extends Controller {
//
public $successStatus = 200;
/**
* login api
*
* #return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]); if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
} $input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name; return response()->json(['success'=>$success], $this-> successStatus);
}
/**
* details api
*
* #return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this-> successStatus);
}
}
How can I Solve this?
If your controller path is /App/Http/Controllers/API, you need to adjust it's namespace :
namespace App\Http\Controllers\API;
If your controller path is /App/Http/Controllers, you need to adjust your routes:
Route::post('login', 'UserController#login');
simply just write folder extension in namespace
for example in your case
namespace App\Http\Controllers\API;
And in route you just write
Route::post('register','api\UserController#register');
It could be because you are not calling the right middleware on the user route that directs to that controller. You would have to create a user middleware.
You can do this by navigating to your App\Http\Middleware and add the user middleware with the name UserMiddleware.php and some code to it.
Firstly, you would need to import the following files;
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
Then you create a class called; class UserMiddleware
Add a handle function to it like so; public function handle($request, Closure $next)
Inside this function include the following code;
if (Auth::user()->usertype == 'user')
{
return $next($request);
}
Next up, head over to you App\Http\Kernel.php and add the following code at the bottom of the protected $routeMiddleware section;
'user' => \App\Http\Middleware\UserMiddleware::class,
Then go over to your route (API) and include this predefined user middleware to your URLs.
Route::group(['middleware' => 'user'], function () {
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::post('details', 'API\UserController#details');
});
});
For this to work you would need to have a usertype field in your users table that is set to user by default. Your usertype column should look like this;
$table->string('usertype')->nullable()->default('user');
1. Copy the existing functions of your controller and delete it.
2. Recreate your controller but this time specifying the location of were you want to place it, in the Controllers directory. e.g.
php artisan make:controller NameOfYourSubFolder\YourControllersName
3. Paste you functions.
Laravel has web route and API route, with different namespace/path configuration, where the issue such as "Class App\Http\Controllers\API\UserController does not exist" comes from.
Web route:
in controller:
<?php
namespace App\Http\Controllers;
use Auth;
use App\Application;
use Illuminate\Http\Request;
class HomeController extends Controller
{
in web.php route file:
Route::get('/home', 'HomeController#index')->name('home');
API route:
in controller:
the namespace should be App\Http\Controllers\API if you put your API controllers in \API path.
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
in api.php route file, add API\ to the controller path.
Route::get('/carts', 'API\CartController#index');

How to remove Laravel Auth Hashing (to replace it by mysql hashing)?

I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration

laravel UserRequest $request error

laravel5.2,I create a UserRequest.php under Requests directory,but in controller,public function add(UserRequest $request) show error,but use public function add(Request $request) is normal.
UserRequest
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRequest extends Request
{
/**
* 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 [
'user_sn' => 'required|unique',
'user_name' => 'required',
'email' => 'required|unique',
'password' => 'required',
];
}
}
UserController
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function add(UserRequest $request)
{
if ($request->get('dosubmit')) {
$validator = Validator::make($request->all(), $request
->rules(), $request->messages());
if ($validator->fails()) {
return redirect('user/add')->withErrors($validator)
->withInput();
}
}
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', ['corporation_list' => $corporation_list, 'department_list' => $department_list]);
}
}
Route
Route::group(['middleware'],function (){
Route::any('user/add',['as'=>'user.add','uses'=>'UserController#add']);
});
There are usually 2 reasons you could be having this issue.
You've not added the use statement for the UserRequest.
At the top of your controller (above the class) add:
use App\Http\Requests\UserRequest
assuming that is the correct namespace.
You may need to run composer dump-autoload to make sure the class has been added to the autoloader.
Edit
Firstly, replace the add() method with the following methods:
public function create()
{
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', compact('corporation_list', 'department_list'));
}
public function store(UserRequest $request)
{
// If you get to this point the validation will have passed
// Process the request
}
Then change your routes from:
Route::any('user/add',['as'=>'user.add','uses'=>'UserControl‌​ler#add'])
to:
Route::get('user/add', ['as' => 'user.add', 'uses' => 'UserControl‌​ler#create']);
Route::post('user/add', ['as' => 'user.store', 'uses' => 'UserControl‌​ler#store']);
Obviously, feel free to change the as in the Routes to whatever, they should unique though.
Lastly, I would suggest looking at Resource Controllers which is a RESTful approach.
The problem is that you have not identified UserController that you are using UserRequest file
use App\Http\Requests\UserRequest
It will solve the problem

Login using laravel5.2

Hi I'm new to laravel and I'm using the laravel5.2 version.
Actually I have this registration form too. But no problem in registration.
My question is that I'm looking for a simple and understandable code in login. I've seen it somewhere while googling but I think that one is not laravel5.2.
I just get the reference code in some examples and test it into my login app. I'm using a repositories on it. I've got some errors. It says
Whoops, looks like something went wrong.
1/1 FatalErrorException in EloquentUserProvider.php line 126: Class '\App\User' not found
I'm not sure why the error says app user not found. Here is my code below
<?php
namespace App\Repositories;
use App\Repositories\Contracts\loginRepositoryInterface;
use Illuminate\Http\Request;
use App\Users;
use DB;
use Session;
use Auth;
class loginRepository implements loginRepositoryInterface{
protected $request;
//Initialize request instance
public function __construct(Request $request){
$this->request = $request;
}
public function loginAuth(){
//validate login
$validator = app('validator')->make($this->request->all(), [
'emailAddress' => 'email|required',
'password' => 'required']);
//if validator fails then return response error
if($validator->fails())
return redirect()->route('get.login')->withErrors($validator)->withInput();
try{
$pwd = $this->request->get('password');
$sha1 = sha1($pwd);
$userdata = array(
'emailAddress' =>$this->request->get('emailAddress'),
'password' =>$sha1
);
if(Auth::attempt($userdata)){
return redirect()->intended('get.dashboard');
}else{
return redirect()->route('get.login')->withErrors($validator)->withInput();
}
}catch(\Exception $e){
return redirect()->route('get.login')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
//postCreate
public function postCreate($screen){
switch($screen){
case 'auth':
return $this->loginAuth();
break;
}
}
//getLoginView
public function getCreate(){
return view('login');
}
}
In method public function loginAuth()
My routes
//postLogin
Route::post('/login/{screen}', [
'as' => 'post.login.auth',
'uses' => 'loginController#postCreate'
]);
//getLoginView
Route::get('/login', [
'as' => 'get.login',
'uses' => 'loginController#getCreate'
]);
Can some one help me on this?
Thanks.
Make sure you have the \App\User model in app/User.php from the looks of the code you posted above, you seem to have \App\Users not \App\User

Laravel 5 Auth - Change Login Route

I'm trying to redirect my user to 'homepage' after successful login.
I've been able to redirect after logout by adding the following to AuthController:
protected $redirectAfterLogout = 'homepage';
However, adding the following to AuthController does not work after login. It directs me to 'home."
protected $redirectPath = 'homepage';
I then changed the default redirect in the handle() function in RedirectIfAuthenticated to:
return redirect('homepage');
Not only does that not work, it gives me the following error:
This webpage has a redirect loop
ERR_TOO_MANY_REDIRECTS
Does anyone know how I can achieve redirecting to 'homepage' after login?
Edit - Adding Routes:
Route::get('/', function () {
return view('welcome');
});
Route::get('home', 'HomepageController#getIndex');
Route::get('homepage', 'HomepageController#getIndex');
Thanks for any guidance!
Dude the attribute should be named as $redirectTo:
$redirectTo = "homepage";
now if you got more than one rule like admin and user, stored within your user model as type field, you may override the value of this attribute within postLogin() function, override the function first then do your changes. i.e:
// AuthController.php
/**
* #param Request $request
* #return $this|\Illuminate\Http\RedirectResponse
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
$user=User::find($this->auth->user()->id);
if($user->type == "ADMIN")
$this->redirectTo = "/dashboard";
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
I got around this by simply modifying the existing Route::get('/') to the following:
Route::get('/', 'HomepageController#getIndex');
I really didn't need the Welcome View any longer, so this solution made the most sense.
Also, after modifying this Route, I was able to remove my previous 'home' and 'homepage' Routes.

Resources