<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
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;
/**
* For redirect after registeration
* #return mixed
*/
public function redirectPath()
{
// return property_exists($this, 'redirectTo') ? $this->redirectTo : '/user/profile/';
//return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
return Redirect::intended('/');
}
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return \App\Http\Controllers\Auth\AuthController
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Handle a login request to the application.
*
* #param LoginRequest $request
* #return Response
*/
public function postLogin(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
if(Auth::user()->is_admin)
return redirect('/admin');
else {
return Redirect::intended('/');
}
}
return redirect('auth/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
}
I am redirecting a user to an intended url after signup but i get the following error.
Header may not contain more than a single header, new line detected
This is the code in the AuthController.
public function redirectPath()
{
return Redirect::intended('/');
}
And the following is the code in the Authenticate class.
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/register');
}
}
return $next($request);
}
I am using laravel 5
Related
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
In my laravel 8 iam define gate but there some problem my gate is accept only one model name is that Admin when i try to check another model name there are error show
here is my authserviceprovider
<?php
namespace App\Providers;
use App\Models\Admin\Role;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('isAdmin', function(Role $role) {
if ($role->role === 'Admin') {
return true;
} else {
return false;
}
});
}
}
here is controller
public function index(Role $role)
{
if (!Gate::allows('isAdmin', $role))
{
abort(403);
}
$users = Admin::with('roles')->get();
return view('Admin.user.index', compact('users'));
}
error message
TypeError
App\Providers\AuthServiceProvider::App\Providers{closure}(): Argument #1 ($role) must be of type App\Models\Admin\Role, App\Models\Admin given, called in D:\xampp\htdocs\education\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 477
http://127.0.0.1:8000/admin/users
Gate are mostly used to authored login user. if you need to authorise in any model specific then use policy
so in gate we get login user instance as call back automatically
so in your case code will be like this
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('isAdmin', function($user) {
return $user->role->name === 'Admin';
});
}
then in controller
public function index(Role $role)
{
abort_if(!Gate::allows('isAdmin'));
$users = Admin::with('roles')->get();
return view('Admin.user.index', compact('users'));
}
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);
}
I'm new to Laravel and I'm trying to set up an email verification for job_seeker but after I register a new job_seeker I redirect to profile page which must be protected with job_seeker_verified middleware
in normal case I must be redirecting to job_seeker/verify which uses the route named job_seeker_verification.notice with the controller verification_controller and the function that shows the view with verify message but instead I get
forbidden page 403
namespace App\Http\Controllers\job_seeker;
use App\Job_seeker;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class job_seeker_profile_controller extends Controller
{
public function __construct()
{
$this->middleware(['job_seeker_auth', 'job_seeker_verified']);
}
public function show_profile(Job_seeker $job_seeker)
{
return view('profile.job_seeker_profile');
}
}
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Facades\Auth;
use Closure;
class Ensure_Job_Seeker_Is_Verified
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
$guard == 'job_seeker';
if (
!Auth::guard($guard)->user() || (Auth::guard($guard)->user() instanceof MustVerifyEmail &&
!Auth::guard($guard)->user()->hasVerifiedEmail())
) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
: Redirect::route('job_seeker_verification.notice');
}
return $next($request);
}
}
namespace App\Http\Controllers\job_seeker;
use Illuminate\Http\Request;
use App\Job_seeker;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
class Verification_Controller extends Controller
{
use VerifiesEmails;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected $redirectTo = 'job_seeker.profile';
public function __construct()
{
$this->middleware('job_seeker_auth');
$this->middleware('signed');
$this->middleware('throttle:6,1')->only('resend');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Request $request)
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('profile.job_seeker_verify');
}
public function verify(Request $request)
{
if ($request->route('id') != $request->user()->getKey()) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('job_seeker_verified', true);
}
}
Route::get('job_seeker_email.resend', [
'as'=>'job_seeker_email.verification.resend', 'uses'=>'job_seeker\Job_Seeker_Verication_email#resend'
]);
Route::get('job_seeker/verify', [
'as'=>'job_seeker_verification.notice', 'uses'=>'job_seeker\Verification_Controller#show'
]);
Route::get('job_seeker/verify/{id}', [
'as'=>'job_seeker_verification.verify','uses'=>'job_seeker\Verification_Controller#verify'
]);
Remove
$this->middleware('job_seeker_auth');
From the verification_controller constructor because it's returning 403 before it reaches the show or verify method
An unverified user can't verify themselves if they need to be verified to do so
How to redirect after login with condition in laravel 5.4,
As Like:
if (Auth::user()->id==1) {
return redirect('admin');
}
else {
return redirect('/');
}
How to implement the condition.
Add following code in LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
return redirect()->route('dashboard');
}
return redirect('/home');
}
}
#Al-Amin to redirect after login successfully based on role id you can override authenticated(Request $request, $user) function in your Auth Controller or Login Controller if you have in below manner :
/**
* [authenticated is used to redirect user after login based on role]
* #param Request $request [request object]
* #param [type] $user [user object to check user role]
* #return [type] [return type]
*/
protected function authenticated(Request $request, $user)
{
if($user->role->id == 1) {
return redirect()->intended('/admin'); // it will be according to your routes.
} else {
return redirect()->intended('/'); // it also be according to your need and routes
}
}
This is the method which you should change in RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/dashboard'); // Change this line
}
return $next($request);
}