Laravel 5.3: How to authenticate only active users - laravel-5

I want to laravel 5.3 loged in users table status='Active' but status='Inactive' can't loged in.
Please help me with that. Thanks a lot guys!

Go to \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
then change credentials functions.
And see this link https://laracasts.com/discuss/channels/laravel/allowing-only-active-users-to-login.
example function link
protected function credentials(Request $request)
{
$crendentials = $request->only($this->username(), 'password');
$crendentials['status']='Active';
return $crendentials;
}

Add this function in Auth/LoginController.php
use Illuminate\Http\Request;
protected function credentials(Request $request)
{
return [
$this->username() => $request->get($this->username()),
'password' => $request->get('password'),
'active' => 1
];
}
By doing this, you actually override it. This function is in the AuthenticatesUsers trait.
Another way for getting the same result is to override the validateLogin() function by adding
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
}),
],
'password' => 'required',
]);
}
to the LoginController.php

You can try like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 'Active'])) {
// The user is active, not suspended, and exists.
}

Related

Assigning the role while user registration Laravel

I'm trying to make a register page with role as a radio button(consumer, supplier, Admin)
but it show me this error when I test the query in postman
Error: Class "App\Http\Models\Role" not found in file
my controller:
public function register(Request $request)
{
$request->validate([
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|string|unique:users',
'password'=>'required|string|min:6',
'phone_number'=>'required|string|min:10',
'role_name'=>'required|string'
]);
$role_a = $request->role_name;
if ($role_a == 'صاحب متجر'){
$role=Role::select('role_id')->where('role_name','صاحب متجر')->first();
$user->roles()->attach($role);
return response()->json($user);
}
elseif ($role_a == 'مشتري'){
$role=Role::select('role_id')->where('role_name','مشتري')->first();
$user->roles()->attach($role);
return response()->json($user);
}
$user=User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone_number' => $request->phone_number,
]);
And my use statement:
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Role;
use Illuminate\Support\Facades\Hash;
And my route:
Route::post('/register','App\Http\Controllers\AuthController#register');
and this what I have in tables:
Note: I didn't use custom packages like spatie for example
Thank you for trying to help!
You miss adding the Request class as an argument into your method. Your method should look like this:
public function register(Request $request)
{
//after validation
$data = $request->validated();
}
Dont forget to add use Illuminate\Http\Request; in your use statement.

Laravel redirecting a user after register doesn't work when Registered event is fired

My register method of the RegisterController:
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
If I go through this flow the user is authenticated and the event is fired, but the user is not redirected... Now for the confusing part: if I move the redirect line above the event line, it does work (but obviously the event doesn't fire):
Auth::login($user);
return redirect()->route('account.index'); // User is correctly redirected here
event(new Registered($user));
What's happening here?
Full RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data, array $ua)
{
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
]);
return $user;
}
}
Try to authenticate user with id :
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::loginUsingId($user->id);
event(new Registered($user));
return redirect()->route('account.index');
}

Laravel - Can't upload the user in multiauth system

I am using multi auth login system. I made register, login and mail system. But i don't know how to make update function. Every member needs to update own profile. My problem is i can't get the related users details. id, name, etc...
In my auth.php customer guards was created:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
]
Also this is the CustomerLoginController:
class CustomerLoginController extends Controller{
public function __construct()
{
$this->middleware('guest:customer')->except('logout', 'userLogout');
}
public function showLoginForm(){
return redirect()->route('homepage');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('homepage'));
}
return redirect('/')->with('error_login', 'Login Fail');
}
public function logout(Request $request) {
Auth::guard('customer')->logout();
return redirect('/');
}
I added the function show($id) and function update(Request $request)
But as i told. Can't get the related user.
My last try is:
$user = Customer::find($id);
this is the right way to doing this i think. But i can't connect them.
ps: i am not using --resources (crud). I must do that manually.

Laravel 5.2 add one more condition to login in standard Auth controller

I'm trying to add one condition to laravel standard auth. I have found a lot of forums with this question. Most of them make change in vendor folder, what I don't want to do. I also found a way of adding credentials(Request $request) function in AuthController.php, but I have no luck. It looks like this:
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'),
['Type' => 1]);
}
Does anyone solve this issue or can advice me what to do? Thanks
Below is the function your can use in AuthController to override the login function:
public function login(Request $request)
{
$validator = Validator::make(
$request->all(),
array(
'user_name' => 'required',
'password' => 'required',
),
array(
)
);
if($validator->fails()){
return redirect()->back()->withInput()->withErrors($validator->errors(),'invalid_credentials');
}
if (!\Auth::validate(['user_name' => $request->user_name, 'password' => $request->password])) {
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Incorrect Username or Password',
],'invalid_credentials');
}
$credentials = array('user_name' => $request->user_name, 'password' => $request->password);
if (\Auth::attempt($credentials, true)){
/* Check your user type condition */
if(\Auth::User()->type == '1'){
return redirect()->intended($this->redirectPath());
}
else{
\Auth::logout();
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Your type validation message',
],'invalid_credentials');
}
}
return redirect()->back()->withInput($request->only('user_name'))->withErrors([
'user_name' => 'Incorrect email address or password',
],'invalid_credentials');
}
Hope this helps you.. :)

How to add extra logic on login condition in Laravel 5.2

I just wanted to say if the user is not active, don't allow to login. I have made the controller as below, I am not sure what I am missing or what else I have to do here to make this work!
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
My thinking was authenticate() method should do the trick!
The below code worked for my case:
protected function getCredentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
for Laravel 5.3 need to add following code to LoginController
protected function credentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
i think you should create method to check if user passed your credentials, here's my suggestion :
protected function getCredentials(Request $request)
{
return [
'username' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
and your login method:
public function login(Request $request) {
$this->validate($request,['email' => 'required|email','password' => 'required']);
if (Auth::guard()->attempt($this->getCredentials($request))){
//authentication passed
}
return redirect()->back();
}
hope you get basic idea.
In LoginController.php file write this function
protected function credentials(Request $request) {
$extraFields = [
'user_type'=> 'customer',
'user_entry_status' => 1
];
return array_merge($request->only($this->username(), 'password'), $extraFields);
}
Go to this path :
your-project-folder/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php
$credentials=$request->only($this->loginUsername(), 'password');
$credentials['status'] = '1';
return $credentials;
Change getCredantials works fine, but it is good practice to let user know, that the account was suspended (credentials are OK, but the account status is not). You can easily override login method in Auth/LoginController.php to your own copy, add your own logic to login process and raise own exception.
in Auth/LoginController.php create login and sendAccountBlocked function
/*load additional classes to LoginController.php*/
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Auth;
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.
if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
//check user status
if (Auth::user()->user_status == 'A') return $this->sendLoginResponse($request);
// if user_status != 'A' raise exception
else {
$this->guard()->logout();
return $this->sendAccountBlocked($request);
}
}
// 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.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
//
}//
protected function sendAccountBlocked(Request $request){
throw ValidationException::withMessages([
$this->username() => ['Your account was suspended.'],
]);
}

Resources