how to put only session auth in laravel - laravel

Web.php
Route::group(['middleware'=>'auth:admin'], function(){
Route::resource('dashboard', 'DashboardController');
Route::group(['prefix'=>'users','namespace'=>'User','as'=>'u.'], function(){
Route::resource('list', 'ListController');
Route::resource('segments', 'SegmentController');
});
Route::group(['prefix'=>'sales','namespace'=>'Sales','as'=>'s.'], function(){
Route::resource('credits', 'CreditController');
Route::resource('packages', 'PackageController');
});
});
RedirectIfAuthenticated
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard)
{
if(Session::has('admin_session')){
return redirect('admin/dashboard');
}
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
return $next($request);
}
}
AuthController
public function login(Request $request)
{
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/firebaseKey.json');
$firebase= (new Factory)->withServiceAccount($serviceAccount)->create();
$this->database = $firebase->getDatabase();
$auth = $firebase->getAuth();
// if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
// return redirect('admin/dashboard');
// }
try {
if($user = $auth->verifyPassword($request->email,$request->password)){
Session::put('admin_session',$user);
return redirect('admin/dashboard');
}
} catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) {
echo 'wrong password'; die();
} catch (\Kreait\Firebase\Auth\SignIn\FailedToSignIn $e) {
echo 'invalid email'; die();
}
}
How to put only session authentication on above-mentioned routes?
As I want to put firebase authentication so laravel's wouldn't work here,
So I just want to implement simple isset(session('admin_session')) functionality which will be common for all routes...
Anyone, please suggest me how to implement it... it keeps redirecting!

Change the middleware group to a new middleware name:
Web.php
Route::group(['middleware'=>'role'], function(){ //or the name you want to use
Route::resource('dashboard', 'DashboardController');
Route::group(['prefix'=>'users','namespace'=>'User','as'=>'u.'], function(){
Route::resource('list', 'ListController');
Route::resource('segments', 'SegmentController');
});
Route::group(['prefix'=>'sales','namespace'=>'Sales','as'=>'s.'], function(){
Route::resource('credits', 'CreditController');
Route::resource('packages', 'PackageController');
});
});
Create a new middleware by php artisan make:middleware Role :
Role.php (Middleware)
<?php
namespace App\Http\Middleware;
use Session;
use Closure;
class Role
{
public function handle($request, Closure $next)
{
if(Session::has('admin_session')) {
return $next($request);
}
return redirect()->route('login');
}
}
Modify the RedirectIfAuthenticated middleware to this:
RedirectIfAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Session::has('admin_session')) {
return redirect('admin/dashboard');
}
return $next($request);
}
}
Modify AuthController to this:
AuthController.php
public function login(Request $request)
{
if ($auth = $this->firebase->getAuth()) {
try {
$user = $auth->verifyPassword($request->email, $request->password);
Session::put('admin_session',$user);
return redirect('admin/dashboard');
}
catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) {
return back(); // code for wrong password
}
catch (\Kreait\Firebase\Auth\SignIn\FailedToSignIn $e) {
return back(); //code for user doesn't exists
}
}
return back(); // something went wrong
}

Related

Why file /resources/views/errors/404.blade.php is not opened on invalid url?

Working with laravel 8 app started by other developer, I can not show
file /resources/views/errors/404.blade.php(I have this file) when invalid url like
http://127.0.0.1:8000/app_admin/platforms/2/editINVALID URL
I got empty page with 200 Status Code returned
in routes/web.php I see :
<?php
use Illuminate\Support\Facades\Route;
...
/* ========= For Adminside ========= */
Route::group(array('middleware' => 'auth_admin', 'prefix' => 'app_admin'), function() {
...
In file app/Http/Middleware/AuthenticatedAdmin.php I have :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthenticatedAdmin
{
public function handle($request, Closure $next, $guard = null)
{
$uri = $request->path();
$bypass_uri = array('/app_admin', 'app_admin/login',
'app_admin/logout', 'app_admin/forgot_password');
if (!in_array($uri, $bypass_uri)) {
if (Auth::guard($guard)->check()) {
if (Auth::user()->urole == 1) {
// return redirect()->route('dashboard');
}
if (Auth::user()->urole == 0) {
return redirect()->url('/');
}
} else {
return redirect()->route('login');
}
}
return $next($request);
}
}
Also I try add logs into :
app/Exceptions/Handler.php :
<?php
namespace App\Exceptions;
//use Laravel\Fortify\Contracts\LogoutResponse;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
protected $dontReport = [
//
];
protected $dontFlash = [
'password',
'password_confirmation',
];
public function register()
{
$this->reportable(function (Throwable $e) {
\Log::info( varDump($e, ' -1 app/Exceptions/Handler.php register $e::') );
});
}
public function render($request, Throwable $e)
{
$response = parent::render($request, $e);
\Log::info( varDump($response->status(), ' -1 app/Exceptions/Handler.php render $response->status()::') );
if ($response->status() === 419) {
\Log::info( ' Expired' );
auth()->logout();
// return app(LogoutResponse::class);
}
if ($this->isHttpException($e)) {
if ($e->getStatusCode() == 404) {
return response()->view('errors' . '404', [], 404);
}
}
return $response;
}
}
I do not see any logs when I enter invalid url like :
http://127.0.0.1:8000/app_admin/platforms/2/editINVALID URL
How can it be fixed?
Thanks!

Get null when running JWTAuth::user() in Laravel

I've been using JWT for authentication in Laravel. I have a JWTMiddleware to check authorization, which works fine, like the following.
try {
JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
return response()->json(['error' => 'Token is Invalid']);
}
User model
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->uuid = Str::uuid()->toString();
});
static::saving(function ($model) {
$original_uuid = $model->getOriginal('uuid');
if ($original_uuid !== $model->uuid) {
$model->uuid = $original_uuid;
}
});
}
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
Now I have a route that uses this middleware and returns an authenticated user.
Route::middleware(['jwt.verify'])->group(function () {
Route::post('/user', function () {
$user = JWTAuth::user();
return response()->json($user);
});
});
After entering this route, I get null. Why does the middleware work fine, yet I can not retrieve the user?

Call to a member function hasAnyRole() on null

I am new on laravel. I am actually having a problem with my middleware. I already registered it on Kernel.php file.
public function handle($request, Closure $next){
$user = Auth::user();
if($user->hasAnyRole('school'))
{
return $next($request);
}
return redirect('login');
}
here is my User model
public function roles(){
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles(){
return null !== $this->roles()->whereIn('name', $roles)->first();
}
public function hasAnyRole(){
return null !== $this->roles()->where('name', $role)->first();
}
Try flipping the logic and also checking if logged in.
Do a (Auth::check() :
public function handle($request, Closure $next){
if (Auth::check()) {
$user = Auth::user();
if($user->hasAnyRole('school'))
{
return $next($request);
}
} else {
return redirect('login');
}
}

auth()->user() return null in ServiceProvider

i try to get the user id in ServiceProvider but auth()->user() return null after successfully login where is the problem ?
It doesn't just work in test mode
public function boot()
{
dd(auth()->user()); // => return null
try {
Permission::get()->map(function ($permission) {
// dd('$permission');
Gate::define($permission->slug, function ($user) use ($permission) {
return $user->hasPermissionTo($permission);
});
});
} catch (\Exception $e) {
report($e);
}
Try using:
use Auth;
public function boot(){
Auth::user(); //or
Auth::user()->name; //or
Auth::user()->get();
}

Laravel 5.2 session cookie driver

I have a problem with the cookie session driver. I need to create an app that works with only cookies. With my configuration, the session is not persisting in Laravel 5.2 with the cookie driver. If I use the file session driver, it works.
.env file:
SESSION_DRIVER=cookie
I also created a middleware that checks if a custom session value exists (only handle() function):
public function handle($request, Closure $next)
{
//dd(session('auth')) // null
if (!session('auth')) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('/');
}
}
return $next($request);
}
I added the middleware to the $routeMiddleware array in app/Http/Kernel.php:
'cookies' => \App\Http\Middleware\CheckCookies::class,
My routes are:
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'LoginController#index');
Route::post('login', 'LoginController#login');
Route::group(['middleware' => 'cookies'], function () {
Route::get('home','HomeController#index');
Route::get('logout','HomeController#logout');
});
});
Here's my LoginController#login method:
public function login()
{
session([
'auth' => ['name' => 'John Doe']
]);
return redirect('/home');
}
How can I fix this?
Just use Cookie Facades in laravel.
Cookie::queue('key', 'value', $minutes);
To make cookie forever
Cookie::forever('key', 'value');
Modify your code and try this.
LoginController#login
public function login(){
$cookieValue=json_encode(array('name'=>'John Dow'));
Cookie::queue('auth', $cookieValue, 60);
return redirect('/home');
}
CheckCookies Middleware
public function handle($request, Closure $next){
if (!Cookie::get('auth'))
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect('/');
}
return $next($request);
}
}

Resources