Laravel Socialite google login transfers to login page again - laravel

I am try to integrate Google login with my application. Its working fine but it send your user back to login screen after google authentication. But when I click on the google login again it behaves like the user is already logged in. I dont want want the user to fall back to login when we comeback from google. Following are my files for controller and routes.
LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
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 = '/admin';
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
/*
* Remove the socialite session variable if exists
*/
\Session::forget(config('access.socialite_session_name'));
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => __('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
*
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$errors = [];
if (config('auth.users.confirm_email') && !$user->confirmed) {
$errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
}
if (!$user->active) {
$errors = [$this->username() => __('auth.active')];
}
if ($errors) {
auth()->logout(); //logout
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
return redirect()->intended($this->redirectPath());
}
}
SocialLoginController
namespace App\Http\Controllers\Auth;
use App\Models\Auth\User\User;
use App\Services\RoleService;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Socialite;
class SocialLoginController extends LoginController
{
use AuthenticatesUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/admin';
public function redirect($provider)
{
return Socialite::driver($provider)->stateless()->redirect();
}
public function googleCallback($provider)
{
$userSocial = Socialite::driver($provider)->stateless()->user();
$user = User::where(['email' => $userSocial->getEmail()])->first();
if($user){
Auth::login($user,true);
return redirect('admin/partners');
} else {
$user = User::create([
'name' => $userSocial->getEmail(),
'email' => $userSocial->getEmail(),
]);
$user->roles()->attach([RoleService::ROLE_AUTHENTICATED]);
return redirect('/admin');
}
}
}
routes/auth.php
Route::group(['namespace' => 'Auth', 'middleware' => ['force.ssl']], function () {
// Authentication Routes...
Route::get('login', 'LoginController#showLoginForm')->name('login');
Route::post('login', 'LoginController#login');
Route::get('logout', 'LoginController#logout')->name('logout');
// Social Authentication Routes...
Route::post('login', 'SocialController#login');
Route::get('login/{provider}', 'SocialLoginController#redirect');
Route::get('login/{provider}/callback', 'SocialLoginController#googleCallback');
});
Middleware/RedirectIfAuthenicated.php
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('/admin');
}
return $next($request);
}
}

return Socialite::driver($provider)->with(["prompt" => "select_account"])->redirect();
this is worked for me

Related

Wrong on login and restet pasword on LARAVEL 9

enter image description here
Login is failed, the credencials email and password, is correct, but laravel dont acces to dashboard
The password reset is worng to, the email is correct and i try chance of credentials on myphpadmin but dont entry.
this is my code
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
If you're mass assignment while attempting authentication make sure the form requested keys must same as Model's $fillable keys.
then try this:
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$credentials = $request->validated();
if (Auth::attempt($credentials)) {
return redirect()->intended(RouteServiceProvider::HOME);
}
return back()->with('message', 'The given credentials are not matched');
}
if you're working with multi guards, try this:
public function store(LoginRequest $request)
{
$credentials = $request->validated();
if (Auth::guard('web')->attempt($credentials)) {
return redirect()->intended(RouteServiceProvider::HOME);
}
return back()->with('message', 'The given credentials are not matched');
}
I have tested this example code from your and my implementation
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\User;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Session::flush();
Auth::logout();
return redirect('/');
}
/**
* Registration page.
*
*/
public function registration()
{
return view('auth.registration');
}
/**
* Store new user request handler
*
*/
public function storeUser(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("dashboard")->withSuccess('have signed-in');
}
/**
* Store new user
*
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Dashboard for user
*
*/
public function dash()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('are not allowed to access');
}
}
Please check from your project and check flash messages if password was wrong check password hashing correctly

Laravel 8 Multi Auth with Jetstream livewire

im trying to setup a multi auth system in laravel 8 with jetstream livewire in my ecomm project (one login page for admins(/admin/login) and another for users(/login))
i have followed a tutorial and everything is ok expect when i login to user from /login page i can access /admin/dashboard with that user and with admin its fine and cant access user /dashboard
routes\web.php:
Route::get('/', function () {
return view('welcome');
});
Route::group(['prefix'=>'admin','middleware'=>['admin:admin']],function(){
Route::get('/login', [AdminController::class, 'loginForm']);
Route::post('/login', [AdminController::class, 'store'])->name('admin.login');
Route::get('/logout', [AdminController::class, 'Logout'])->name('admin.logout');
});
Route::middleware(['auth:sanctum,admin', 'verified'])->get('/admin/dashboard', function () {
return view('admin.index');
})->name('dashboard.admin');
Route::middleware(['auth:sanctum,web', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Models\Admin.php:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* 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',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
Controllers\AdminController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Routing\Pipeline;
use App\Actions\Fortify\AttemptToAuthenticate;
use Laravel\Fortify\Actions\EnsureLoginIsNotThrottled;
use Laravel\Fortify\Actions\PrepareAuthenticatedSession;
use App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable;
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginViewResponse;
use Laravel\Fortify\Contracts\LogoutResponse;
use Laravel\Fortify\Features;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Requests\LoginRequest;
use Auth;
class AdminController extends Controller
{
/**
* The guard implementation.
*
* #var \Illuminate\Contracts\Auth\StatefulGuard
*/
protected $guard;
/**
* Create a new controller instance.
*
* #param \Illuminate\Contracts\Auth\StatefulGuard
* #return void
*/
public function __construct(StatefulGuard $guard, Request $request)
{
$this->guard = $guard;
}
public function loginForm(){
return view('admin.login',['guard'=>'admin']);
}
public function Logout(){
Auth::logout();
return Redirect()->url('admin/login')->with('success', 'Logged Out');
}
/**
* Show the login view.
*
* #param \Illuminate\Http\Request $request
* #return \Laravel\Fortify\Contracts\LoginViewResponse
*/
public function create(Request $request): LoginViewResponse
{
return app(LoginViewResponse::class);
}
/**
* Attempt to authenticate a new session.
*
* #param \Laravel\Fortify\Http\Requests\LoginRequest $request
* #return mixed
*/
public function store(LoginRequest $request)
{
return $this->loginPipeline($request)->then(function ($request) {
return app(LoginResponse::class);
});
}
/**
* Get the authentication pipeline instance.
*
* #param \Laravel\Fortify\Http\Requests\LoginRequest $request
* #return \Illuminate\Pipeline\Pipeline
*/
protected function loginPipeline(LoginRequest $request)
{
if (Fortify::$authenticateThroughCallback) {
return (new Pipeline(app()))->send($request)->through(array_filter(
call_user_func(Fortify::$authenticateThroughCallback, $request)
));
}
if (is_array(config('fortify.pipelines.login'))) {
return (new Pipeline(app()))->send($request)->through(array_filter(
config('fortify.pipelines.login')
));
}
return (new Pipeline(app()))->send($request)->through(array_filter([
config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
AttemptToAuthenticate::class,
PrepareAuthenticatedSession::class,
]));
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Laravel\Fortify\Contracts\LogoutResponse
*/
public function destroy(Request $request): LogoutResponse
{
$this->guard->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return app(LogoutResponse::class);
}
}
Responses\LoginResponse.php:
<?php
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect()->intended('admin/dashboard');
}
}
i also created a copy of StatefulGuard in App\Guards\AdminStatefulGuard.php following that tutorial but never used it.
Problem fixed by adding this code to my admin controllers.
public function __construct()
{
$this->middleware(['auth:admin,admin', 'verified']);
}
and also replacing this in web route:
Route::middleware(['auth:sanctum,admin', 'verified'])->get('/admin/dashboard', function () {
return view('admin.index');
})->name('dashboard.admin');
with this:
Route::middleware(['auth:admin,admin', 'verified'])->get('/admin/dashboard', function () {
return view('admin.index');
})->name('dashboard.admin');
Try this on Admin middleware
public function handle(Request $request, Closure $next, $guard)
{
if (Auth::guard($guard)->check()) {
return redirect('/admin/dashboard');
}
if(Auth::guard('web')->check()) {
return redirect('/dashboard');
}
return $next($request);
}
and on RedirectIfAuthenticated middleware:
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
if(Auth::guard('admin')->check()) {
return redirect('admin/dashboard');
}
return $next($request);
}

How to redirect user after login to the same route came from in laravel 7?

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');
}
}

View [auth.login] not found

I am working on login part of application where i am creating two seperate login for admin and user.
My Controller structure is like :
Controller - Admin (For Admin)
LoginController.php
-- Auth
login.blade.php
.... Auth (For Normal user)
LoginController.php
...
Views:
Admin
login.blade.php
auth
login.blade.php
till now i'm working on the admin part.
LoginController.php
<?php
namespace App\Http\Controllers\Admin;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect admins after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
/**
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showLoginForm()
{
return view('admin.auth.login');
}
public function login()
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('admin')->attempt([
'email' => $request->email,
'password' => $request->password
], $request->get('remember'))) {
return redirect()->intended(route('admin.dashboard'));
}
return back()->withInput($request->only('email', 'remember'));
}
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
/*public function logout(Request $request)
{
Auth::guard('admin')->logout();
$request->session()->invalidate();
return redirect()->route('admin.login');
} */
}
RedirectIfAuthenticated.php
<?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)
{
switch($guard){
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect('/admin');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/');
}
break;
}
return $next($request);
}
}
Authenticate.php
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
web.php
Route::group(['prefix' => 'admin'], function () {
Route::get('login', 'Admin\LoginController#showLoginForm')->name('admin.login');
Route::post('login', 'Admin\LoginController#login')->name('admin.login.post');
Route::get('logout', 'Admin\LoginController#logout')->name('admin.logout');
//Route::get('dashboard', 'Admin\LoginController#dashboard')->name('admin.dashboard');
Route::group(['middleware' => ['auth:admin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard.index');
})->name('admin.dashboard');
});
whenever i access dashboard throgh url i get View[auth.login] not found.
You can modify the file Authenticate.php to receive the guard name in redirectTo method.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* #var array
*/
protected $guards = [];
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string[] ...$guards
* #return mixed
*
* #throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
if (reset($this->guards) === 'admin') {
return route('admin.login');
}
return route('login');
}
}
}
Note that it may be necessary to execute php artisan cache:clear after the change.
source

Laravel 5 authentication weird behaviour

Before explaining the problem. Let me explain, things i have tried out.I ran the command
php artisan make:auth
it created files like HomeController, a directory auth which had register & login pages. in my application i have a directory Pages. i opened up AuthenticatesUsers trait and changed
return view('auth.login'); to my view return view('Pages.login');
After that: i changed view of showRegistrationForm methods view return view('auth.register'); to return view('Pages.register'); from RegistersUsers.php
Here is UserController
lass UserController extends Controller {
//constructor
public function __construct() {
}
//Admin: return view
public function showCommunity() {
$Community = Community::latest()->get();
$Ideas = Idea::latest()->get();
return view('privatePages.communities', compact(array('Community', 'Ideas')));
}
Routes that were generated by php artisan make:auth
Route::auth();
//Auth Controller
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Now coming back to the problem. yesterday morning. When i opened up localhost/auth/register. Registration process was working fine and data was storing in DB. But there was an issue with login view. Neither it was throwing an error on wrong credentials nor logged the user in on correct credentials. Later in the evening. Login view was working and throwing an error even upon entering correct credentials it said Credentials does not match record. But registration process was not working and data was not storing in DB. It really confusing.
Here is AutheticatesUsers File
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
//use App\Http\Requests\UserRequest;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();
}
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$view = property_exists($this, 'loginView')
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {
return view($view);
}
return view('Pages.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
return $this->login($request);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
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.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->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 && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* 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::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* #return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* #return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
One more thing for registration process. I am not using laravel's Request rather my own created 'UserRequest`. If any other information is needed. i would provide that. Any help would be appreciated.

Resources