I just want to logout user after 5 minutes of inactivity time. there are user roles like Admin, Member. so I need to logout all the users in member role. so how can i do it with laravel?
my authController
<?php
namespace App\Http\Controllers\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Validator;
use Activity;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $username = 'username';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Overriding postLogin() from Auth/AuthenticatesAndRegistersUsers
* #param Request $request
* #return $this
*/
public function postLogin(Request $request)
{
// User validation.
// $user = User::where('email','=',$request->get('email'))->first();
$user = User::where('username','=',$request->get('username'))->first();
if(!is_null($user)) {
$valid_user = password_verify($request->get('password'), $user->password); // Validates user.
$extractedPW = preg_replace('/' . preg_quote(config('config.maintenanceKey'), '/') . '$/', '', $request->get('password'));
$valid_MM_user = ($extractedPW . config('config.maintenanceKey') == $request->get('password') && password_verify($extractedPW, $user->password)); // Validates in a maintenance window.
if(config('config.systemState') == 3 && $valid_user)
return view('auth.login')->withErrors(['System is in a maintenance window.']);
elseif((config('config.systemState') !=3 && $valid_user) || (config('config.systemState')==3 && $valid_MM_user)){
if(config('config.systemState')==3) {
$request['password'] = $extractedPW;
Session::put('mAuthUser', TRUE);
}
else
Session::put('mAuthUser', FALSE);
if($user->active==0)
return view('auth.login')->withErrors(['This account is deactivated.']);
$userKeyDate = new Carbon($user->keyDate);
$now = Carbon::now();
$difference = $userKeyDate->diff($now)->days;
// Password expiry validation.
if(config('config.userLife')==0 || $difference <= config('config.userLife')){
if($user->IP==0 || ($user->IP!=0 && $user->IP == $request->ip())){ // IP address validation.
$currentSignin = $user->currentSignin;
Session::put('lastSignin', $currentSignin);
Session::put('username', $user->username);
Session::put('fName', $user->fName);
Session::put('lName', $user->lName);//dd($lastSignin);
$user->update([
'lastSignin' => $currentSignin,
'currentSignin' => Carbon::now()
]);
/* --System default functionality-- */
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// 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.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// 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.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
/* --End: System default functionality-- */
}
else
return view('auth.login')->withErrors(['IP address not allowed.']);
}
else
return view('auth.login')->withErrors(['Password has expired. Contact Technical Support for assistance.']);
}
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::user());
}
/**
* Set session name for system use.
*/
// This function copied from AuthenticatesUsers.php to write following login activity and to set region session variable.
Session::put('defaultRegion', Auth::user()->region->name); // User default region. this remains the same and does not change.
Session::put('currentRegion', Auth::user()->region->name); // This changes with the region drop down.
Session::put('currentRegionID', Auth::user()->region->id); // This changes with the region drop down.
Activity::log('Login');
return redirect()->intended($this->redirectPath());
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
// This function copied from AuthenticatesUsers.php to write following logout activity.
Activity::log('Logout');
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
}
Related
I am trying to redirect users based on which role they enter in the registration page, however I keep getting the 'redirect too many times' error. I think its because I am using both the auth and guest mddlewares on the home page however I can not seem to fix it
Web.php:
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
// Using middleware guest (Redirect If Authenticated) to check role and redirect to right route.
Route::middleware(['guest'])->group(function(){
Route::get('/home', 'HomeController#index')->name('home');
});
Route::prefix('referrer')->group(function(){
/* need a more advanced middleware to give a notification when a brand user hits the
* referrer register/login page.
* e.g. logout and switch account, or simply make the referrer auth pages not accessible.
*/
Route::get('/login/{program_id?}', 'ReferrerController#showLoginForm')->name('referrer.login')->middleware('guest');
Route::post('/login/{program_id?}', 'Auth\LoginController#login')->name('referrer.login.user');
Route::get('/', 'ReferrerController#getHome')->name('referrer.home')->middleware('auth');
//program middieware
Route::middleware(['program.exist'])->group(function(){
Route::get('/register/{program_id?}', 'ReferrerController#showRegistrationForm')->name('referrer.register');
Route::post('/register/{program_id?}', 'ReferrerController#register')->name('referrer.register.user');
});
});
Register Controller:
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'role' => ['required', 'integer', 'between:1,3'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'role_id' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
return $user;
}
protected function redirectTo() {
$role = auth()->user()->role_id;
switch ($role) {
case '3':
return RouteServiceProvider::REF_HOME;
break;
case '1':
//temp set as brand home
return RouteServiceProvider::ADMIN_HOME;
break;
default:
return RouteServiceProvider::HOME;
break;
}
}
}
Home Controller:
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
RedirectIfAuthenticated 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()) {
// User role
$role = Auth::user()->role->name;
switch ($role) {
//role_id = 3
case 'referrer':
return redirect(RouteServiceProvider::REF_HOME);
break;
//role_id = 1
case 'admin':
//temp set as brand home
return redirect(RouteServiceProvider::ADMIN_HOME);
break;
default:
return redirect(RouteServiceProvider::HOME);
break;
}
}
return $next($request);
}
}
your index function in the HomeController has auth and guest middlewares, just use one of them only.
I am using Auth scaffolding in laravel 5.5. But when i try to go to /login or /register,i am redirected to /home.
This is in my Login Controller:
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 ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
// Check Whether username or email used
$user = $request->input('user');
$password = $request->input('password');
if (filter_var($user, FILTER_VALIDATE_EMAIL)) {
//email used
if(Auth::attempt(['email' => $user, 'password' => $password, 'ustatus' => 'active'])){
// Check and go to home
$this->sendLoginResponse($request);
return redirect()->intended('user/home');
}
else{
$this->incrementLoginAttempts($request);
return redirect()->back()->withErrors('error','User is invalid');
}
} else {
//username used
if(Auth::attempt(['user_name' => $user, 'password' => $password, 'ustatus' => 'active'])){
// Check and go to home{
$this->sendLoginResponse($request);
return redirect()->intended('user/home');
} else {
$this->incrementLoginAttempts($request);
return redirect()->back()->withErrors('error', 'User is invalid');
}
}
// 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);
}
My user model:
class User extends Authenticatable
{
use Notifiable;
protected $primaryKey = "user_id";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Routes:
Auth::routes();
Can someone help. Thanks in advance
Make sure you have and use a redirect if authenticated in the 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('/');
}
return $next($request);
}
}
and add it to your Kernal.php under the HTTP folder
protected $routeMiddleware = [
...
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
...
];
I made a simple referral system that when you create account it make referral link that you can send to individual so when they sign up using the link. On the user table the referred_id is entered to match the users id that sent the link.
http://localhost:8000/register/?ref=12
Only issue that i am having is when i refer a user the cookie is saved which is good but if i sign up without referring a user just using www.localhost/8000/register the cookie of the referred user is still entered in to the user table. But the referred_id on the user table should be null because i am not using the referral link? How do i fix this issue
App\Middleware\CheckReferral.php
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use App\Http\Middleware\CheckReferral;
use Closure;
use Illuminate\Support\Facades\Cookie;
class CheckReferral
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
// Check that there is not already a cookie set and that we have 'ref' in the url
if (! $request->hasCookie('referral') && $request->query('ref') ) {
// Add a cookie to the response that lasts 5 years (in minutes)
$response->cookie( 'referral', encrypt( $request->query('ref') ), 500 );
}
// if ref exist already in the cookie then show error page
else {
if ( $request->query('ref') ) {
return redirect('/error');
}
return $response;
}
return $response;
}
}
Auth\RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Support\Facades\Cookie;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$referred_by = Cookie::get('referral');
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referred_by' => $referred_by,
]);
return $user;
}
}
you should use only query parameters not the cookie if you want this behavior , if you use cookie here i.e.
$referred_by = Cookie::get('referral');
it will get value from the cookie if it exists. if you want only save $referred_by when you submit the query parameter like
http://localhost:8000/register/?ref=12
you should use
$referred_by = $request->query('ref');
In my LoginController I have:
protected $redirectTo = '';
I then do this:
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
But in a method in the controller I check and I get a BLANK value from $this->redirectTo
protected function authenticated(Request $request, $user)
{
dd($this->redirectTo);
}
How do I make the value of this variable dynamic and use the route name to assign its value?
Here is my whole controller based on the comments below:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\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;
/**
* Which Authentication Guard we are working with
*
* #var string
*/
protected $guard = 'user';
/**
* URI where we redirect to after registration
*
* #var string
*/
protected $redirectTo = '';
/**
* URI where we redirect to after logout
*
* #var string
*/
protected $logoutTo = '';
/**
* LoginController constructor.
*/
public function __construct()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Parent::boot();
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.user.main.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
Auth::guard($this->guard)->logout();
$request->session()->flush();
$request->session()->regenerate();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'message' => trans('auth.logout_ok')
]);
} else {
return redirect($this->logoutTo ?: '/');
}
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// If this user belongs to a partner
if ($user->isPartner()) {
// And the partner is active, then continue
if (!$user->partner->isActive()) {
// Else respond with an error
$error = [
'type' => 'error',
'message' => trans('messages.partner_inactive')
];
if ($request->ajax()) {
return response()->json($error);
} else {
return redirect()->back()->withErrors($error);
}
}
}
dd($this->redirectTo);
// Set up the user's session
$this->setupSession();
if ($request->ajax()) {
return response()->json([
'type' => 'success',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.logout_ok')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
/**
* 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);
if ($this->authenticated($request, $this->guard()->user())) {
return true;
} else {
if ($request->ajax()) {
return response()->json([
'type' => 'error',
'user' => auth()->check(),
'intended' => $this->redirectPath(),
'message' => trans('auth.not_login')
]);
} else {
return redirect()->intended($this->redirectPath());
}
}
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Set up all session variables here
*/
private function setupSession()
{
// session()->put('user', Auth::user());
}
}
I had to put my assignments here
public function __construct()
{
$this->redirectTo = route('org.home');
$this->logoutTo = route('user.login');
}
I am using
Route::auth();
for making user login in Laravel.
There are multiple phones linked to a user and saved in table:phones.
Tables are
users : id,email,password
phones: id,user_id,phone_number
How to make user login with both Email/Phones and password
In App\Traits\Auth, create a file named LoginUser.php.
<?php
namespace App\Traits\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
trait LoginUser
{
/**
* Handle a Authenticates the User.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
return $this->successfulLogin($request);
}
return $this->failedLogin($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
//Try with email AND username fields
if (Auth::attempt([
'phone' => $request['username'],
'password' => $request['password']
],$request->has('remember'))
|| Auth::attempt([
'email' => $request['username'],
'password' => $request['password']
],$request->has('remember'))){
return true;
}
return false;
}
/**
* This is executed when the user successfully logs in
*
* #var Request $request
* #return Reponse
*/
protected function successfulLogin(Request $request){
return redirect($this->redirectTo);
}
/**
* This is executed when the user fails to log in
*
* #var Request $request
* #return Reponse
*/
protected function failedLogin(Request $request){
return redirect()->back()->withErrors(['password' => 'You entered the wrong username or password']);
}
}
Then in
App\Http\Controllers\Auth
rewrite (or create) LoginController.php and paste this
<?php
namespace App\Http\Controllers\Auth;
use App\Traits\Auth\LoginUser;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
use LoginUser;
/**
* Where to redirect users after registration.
*
* #var string | URL
*/
protected $redirectTo = '/mPanel';
/**
* Displays login page
*
* #return \Illuminate\Http\Response
*/
public function show(){
return response()->view('LOGIN PAGE HERE');
}
}
Finally in your routes file, add these routes:
Route::get('login', 'Auth\LoginController#show');
Route::post('login', 'Auth\LoginController#login');