I want to add another condition in AuthController but I don't know how to do it.
In my Users table, I have a Active field. If a User has Active == 0, i want to not let he/she login into the system. I don't know where to add that condition in Laravel 5.1 AuthController.
Please help me with that.
Thanks a lot guys!
You can override the postLogin method of the AuthenticatesUsers trait in your AuthController:
public function postLogin(Request $request)
{
/* PLACE HERE VALIDATION CODE... */
//attempt login but not log in the user
if ( ! Auth::attempt($credentials, false, false) )
{
//wrong credentials: redirect to login
}
//CREDENTIALS OK
//get user model from last attempt
$user = Auth::getLastAttempted();
//if user is not active...
if (! $user->active)
{
//do whathever you want: for example redirect to login
}
//USER IS ACTIVE
//login the user
Auth::login($user, $request->has('remember'));
//redirect where you need
}
Check the original: vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers::postLogin method, to see if you need other instructions inside your overrided method (for example input validation)
You can add your custom postLogin() function in your Auth controller which overrides the default postLogin function with this condition
Auth::attempt(array('email' => $email, 'password' => $password, 'active' => 1))
This way you will only do auth of active users only
Cheers!!
Instead of overriding the whole postLogin function, add this to your AuthController
protected function getCredentials(Request $request)
{
$crendentials=$request->only($this->loginUsername(), 'password');
$crendentials['active']=1;
return $crendentials;
}
Related
I have created a login page but I cant get past it because it says Sorry, your session has expired. Please refresh and try again.
This is my controller...
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class loginController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$request = Request::all();
$registers = registers::where('employeeID', $request['employeeID'])
->first();
$validCredentials = Hash::check($request['password'], $request-
>get('password'));
if ($validCredentials) {
Session::flash('login','login Successful!');
return view('dashboard');
}
}
this is my route...
Route::get('/', function () {
return view('register');
});
Route::resource('register', 'registerController');
Route::get('login',function(){
return view('login');
});
Route::resource('login', 'loginController');
Route::resource('login', 'loginController#index');
Route::get('dashboard',function(){
return view('dashboard');
});
I dont have a model because I dont think it is necessary
Though your input will be highly appreciated as I am new to laravel
When trying to authenticate user in laravel use the following syntax (you can modify it to what field do you want it to check). What this code does is it will check with your database then if it's a successful attempt, then it will create User session.
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// redirect or do anything else
}
for more detail you can check here : https://laravel.com/docs/5.7/authentication#authenticating-users
=================================
I will try to exmplain your current syntax (part of it)
$validCredentials = Hash::check($request['password'], $request->get('password'));
if ($validCredentials) {
Session::flash('login','login Successful!');
}
here's my short explaination about your code :
$validCredentials.............
only checks if the password is correct with the hash, doesn't make any sessions or cookies. which doesn't truly authenticate the user. it only checks if the password is true
if ($validCredentials) {
Session::flash('login','login Successful!');
}
it only flash session. what you must understand is that flash session is only short term (only available on the next page and will went away if the user change page / refresh the page).
And flash session ONLY WORKS if you create long-term Session (user is trully logged in) using the code like what I wrote above
I have a users table which consists of multiple users and have successfully created authentication system using middleware. Now i would like to know is there any possibility to allow only specific users to log in and prevent other from logging-in based on their type( i.e i have already defined user_type column in my users table)
You can use custom fields in Auth::attempt:
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'user_type'=>10])) { //<---
// Authentication passed...
}
}
}
Another solution is to log user in, then check which permission he/she has, and then force logout if not authorized.
Try this.
$allowed = User::join('user_types', 'user.id', '=', 'user_types.user_id')
->where('user.email', $email)
->where('user.password', $password)
->where('user_types.type', 'admin') // the type of user
->exists();
if($allowed) {
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// passed
}
return 'not authorized';
}
In 5.3 you can override authenticate() method in the LoginController.php:
public function authenticate()
{
if (auth()->user()->user_type !== 1) {
auth()->logout();
}
}
This code will check user type and if it's not 1 it will use logout() method to sign out authenticated user.
This is my first attempt at a laravel package and have run into an issue where Auth::attempt($credentials) works within my login controller, but upon redirection to a protected route or controller, the user is no longer authenticated. Below is my login controller method with the redirect to dashboard commented out.
public function attempt(Request $request){
$email = strtolower(strip_tags(htmlspecialchars($request->input('email'))));
$password = strip_tags(htmlspecialchars($request->input('password')));
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
// Redirect to dashboard route
//return redirect()->intended('/admin');
if(Auth::check())
print_r(Auth::user());
}
}
A response to valid credentials prints out the correct user record and Auth::check returns true. But, when redirected to the admin controller, the user is not authenticated. Below is the admin controller method that should output the authenticated user, but only returns "not logged".
public function index()
{
if(Auth::check()) print_r(Auth::user());
else echo "not logged";
}
Both controllers use Auth;, their namespaces are consistent with vendor/package/pathToDir, db is setup correctly, and the encryption key has been set. Any ideas on what's going wrong? Thanks
Turns out the issue was with the new web middleware, moved all my routes that require session data in to the route group and everything works as normal.
Route::group(['middleware' => ['web']], function () {
Route::get("/login", ['uses'=>'SiteLogin#index']);
Route::post("/login", ['uses'=>'SiteLogin#attempt']);
Route::get("/logout", ['uses'=>'SiteLogin#logout']);
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
Route::get('/', ['uses'=>'Admin#index']);
});
});
The default behavior of the method attempt is to not keep the user logged.
You should change it to:
if (Auth::attempt(array('email' => $email, 'password' => $password), false, true))
This way you will set remember as false and login as true.
Check more about this here: https://laravel.com/docs/5.2/authentication
I have a custom need where I am trying to connect Laravel with Django app. Currently, I am not using laravel's default login post method to establish user session, instead of that I am trying to access Auth::attempt($credentials);. By this way, I am able to establish user session in my custom login controller whereas in other controllers the session is not established.
Login controller:
$credentials = array('email' => $userjson["email"],'password' => $password);
Auth::attempt($credentials);
if(Auth::guest())
echo "guest";
else
return redirect()->intended('/dashboard');
Result: redirect to the dashboard page (which means session is established)
Dashboard controller
if(Auth::check())
echo "true";
else
echo "false";
Result: false (which means the session is not established)
Can someone help me to resolve this?
Use this code .we'll need to make sure to import the Auth facade at the top of the class .For more help go to https://laravel.com/docs/5.2/authentication and ready topic Manually Authenticating Users. Thanks
namespace App\Http\Controllers;
use Auth;
class OtherController extends Controller
{
/**
* Handle an authentication attempt.
*
* #return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
I'm working in application which requires a custom login.
I've to follow this flow.
User will enter login page.
User submit login page.
Application will check if the user is in database
3.1 (If user not in database | it will send a request to a third-party and check if login succeeded)
3.2 If user is in database verify password.
Now i've done class for the third-party and the code will work as this
$third = new Libraries\ThirdParty();
$third->login($username, $password);
$third->login will return true if login succeeded.
Now the question is how to link this logic. with the laravel pre-defined function Auth::check()
When you install laravel, it comes with a default login, that uses a trait:
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
}
this class use the trait for login stored in: vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.php
you can overwrite the methods from this class to put your own logic, for example in the class AuthController you can define a new:
function postLogin(){
//your new logic for login
}
and it gonna respect your function instead the trait funcion.
anyway, the logic behind the postLogin from auth trait is:
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')))
{ //this if validate if the user is on the database line 1
return redirect()->intended($this->redirectPath());
//this redirect if user is the db line 2
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
//redirect again to login view with some errors line 3
}
you can do two things:
edit the trait itself (bad practice) to put your own logic
define your own postLogin function in AuthController and copy the logic but edit it with your own custom logic.
Edit
to be more conrete with your points:
User will enter login page: you can use the default login page that laravel gives you, or you can overwrite getLogin function and redircet to your own view.
User submit login page: the form action needs to be: {{ url('/auth/login') }} or whatever route you put to postLogin()
Application will check if the user is in database: in the code line 1
3.1 (If user not in database | it will send a request to a third-party and check if login succeeded): in the code line 3
3.2 If user is in database verify password: in the code line 2
custom login 100% wroking without auth
use Hash;
$data->password = Hash::make(($request->password)); Encript Password
public function requestEmployee(Request $request)
{
if ($data = AddEmployee::where('name', $request->name)->first()) {
$pass = Hash::check($request->password, $data->password);
if ($pass) {
echo "sucess";
} else {
echo "Password Not Valid";
}
} else {
echo "Username Not Valid" . "<br>";
}
}