Automatically logout after refreshing the page in laravel 6 - laravel

I am Automatically logout after refreshing the page in laravel 6. Everything is working fine but I am successfully logged in but when I refresh the page automatically logged out. I am using a socialite package to login to my app. I also increase the session lifetime to 180 in config/session.php file but still didn't work...
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use App\Models\Constant_model;
use App\SocialProvider;
use App\User;
use Socialite;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
// public function __construct()
// {
// $this->middleware('guest')->except('logout');
// }
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$social_user = Socialite::driver($provider)->user();
$authuser = $this->findOrCreateUser($social_user,$provider);
Auth::login($authuser,true);
return redirect('/');
}
public function findOrCreateUser($social_user,$provider){
$authuser = SocialProvider::where('provider_id', $social_user->id)->first();
if(!$authuser){
$user = User::firstOrCreate(
['email'=> $social_user->getEmail()],
['ip_address'=> '127.0.0.1'],
['user_name'=> $social_user->getName()],
['name'=> $social_user->getName()],
['picture'=> $social_user->getAvatar()],
['password'=> 'sfdsfsdffsfsfs'],
);
$user->socialProviders()->create(
['provider_id'=>$social_user->getId(), 'provider'=>$provider]
);
return $user;
}else{
$user_id = $authuser->user_id;
$userdata = Constant_model::getDataOneColumn('users',"id",$user_id);
$user = User::firstOrCreate(
['email'=> $userdata[0]->email],
['ip_address'=> '127.0.0.1'],
['user_name'=> $userdata[0]->username],
['name'=> $userdata[0]->name],
['picture'=> $userdata[0]->picture],
['password'=> 'sfdsfsdffsfsfs'],
);
return $user;
}
}}

Related

How to set the global variable on Laravel Controller?

Everyone.
Every function on a controller, I am using the same variables.
public function store(Request $request)
{
$user = auth()->user();
$user_name = $user->name;
$user_id = $user->id;
$init_pdf = url('/') . '/images/' . 'upload/' . $user_name . '/' . $name;
...
}
public function signedPdf(request $request)
{
$user = auth()->user();
$user_name = $user->name;
$user_id = $user->id;
$name = $user_name . $user_id . '.' . $file->extension();
...
}
I want to set the global variable for the common variables.
How can I set it?
thanks
Normally you can directly set things in the constructor but there is an issue with Controllers in regards to middleware. The Controller is resolved before the request has passed through the middleware stack. Which means you usually won't have things like sessions or auth available yet. You would want to use a closure based middleware in the constructor of the Controller to be able to set this value:
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = $request->user();
// also can set other variables here as well
// let the request continue through the stack
return $next($request);
});
}
Then you should have access to $this->user in your methods.
Another answer: Assign user values for whole controller in laravel
Duplicate of that basically.
This solution is worked for me
In
app/Http/Controllers/Controller.php
Import Illuminate\Support\Facades\Auth
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth; <--- like this
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected $userId;
protected $userName;
public function __construct()
{
$this->userId = Auth::user()->id;
$this->userName = Auth::user()->name; <--- "Admin"
}
}
Now $this->userId and $this->userName is available wherever extends Controller
For example:
app/Http/Controllers/API/v1/ConfigController.php
class ConfigController extends Controller
{
public function index() {
return $this->userName; <--- "Admin"
}

If logged with jwt-auth looks in controller Auth::user() is empty

In my Laravel 5.8/vuejs 2.6 app I use
"tymon/jwt-auth": "^1.0.0",
and my app/Http/Controllers/AuthController.php has method:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard('api')->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
and I keep token on client side. It works but I want to add more checks on the server's side, when I save data and to make in control's method :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Settings;
use App\Http\Traits\funcsTrait;
use App\Forum;
use App\ForumCategory;
use App\ForumThread;
use App\ForumPost;
use Illuminate\Routing\Controller as BaseController;
use App\User;
use App\library\CheckValueType;
use App\Http\Requests\ForumThreadRequest;
use JavaScript;
class ForumController extends BaseController
{
use funcsTrait;
public function __construct()
{
$this->middleware('auth');
}
public function add_new_thread(ForumThreadRequest $request)
{
$loggedUser = Auth::user();
if ( empty($loggedUser->id) ) {
return response()->json(['error_code'=> 1, 'message'=> "You must be logged!", 'forumThreadRow'=>null],HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}
try {
But even if I have logged into the system it looks like that in add_new_thread method $loggedUser is empty.
Have I to make some additive actions in login method of AuthController.php or in which way ?
As I use api guard decision is to use :
$user = Auth::guard('api')->user();
This is a late answer, but maybe could help someone.
I had the same issue and it was fixed by adding $table property to the user model User.php
/**
* Specify table name otherwise Auth::user() will return null
*
* #var string
*/
protected $table = 'users';
see here

Unable to show data in Laravel

I am adding a feature in chatter package and now am unable to show data on my view
this is the code of controller ChatterreplyController.php
<?php
namespace DevDojo\Chatter\Controllers;
use Illuminate\Http\Request;
use DevDojo\Chatter\Models\Chatterreply;
use Auth;
use Carbon\Carbon;
use DevDojo\Chatter\Events\ChatterAfterNewDiscussion;
use DevDojo\Chatter\Events\ChatterBeforeNewDiscussion;
use DevDojo\Chatter\Models\Models;
use Illuminate\Routing\Controller as Controller;
use Event;
use Validator;
class ChatterreplyController extends Controller
{
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return back()->with('chatter_alert','Add Comment Successfully');
}
public function show(Chatterreply $chatterreply ,$id)
{
$chatterreplies = Chatterreply::where('chatter_post_id',$id)->get();
return view('chatter::discussion', compact('chatterreplies'));
echo "<pre>"; print_r('$chatterreplies'); die;
}
}
this is the view page discussion.blade.php
#foreach($chatterreplies as $chatterreply)
{{$chatterreply->reply}}
#endforeach
try this:
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return redirect('/discussion')->with('chatter_alert','Add Comment Successfully');
}

Auth::User() gives null in laravel 5.2

I am new to laravel. I am using multi authentication in my application. User and Admin are 2 type of user in my application. Iam developing change password for admin after logged in to application through admin's profile page. now I want to get logged in admin user detail so that i have use below code in my controller
if (Auth::guard('admin')->check()) {
$user = Auth::id();
echo '<pre>';
dd($user);
exit;
}
I have also add following code in controller
use App\Http\Controllers\Adminauth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Admin;
use Session;
use DB;
use App\Http\Controllers\Controller;
use Auth;
In route.php i have write following code
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::auth();
Route::get('admin/profile/change_password', 'Admin\AdminController#change_password');
});
But i am not able to get admin user detail. can anyone help me to solve this problem.
Try this
public function __construct() {
$this->middleware('auth:admin');
$this->middleware(function ($request, $next) {
$user = $this->user = Auth::user();
dd($user);
});
}
In routes
Route::get('/', function () {
//return view('welcome');
return view('auth.login');
});
Auth::user() is working only under auth middleware. You may call auth middleware on controller or call it on routes, but not on both.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class YourController extends Controller
{
public function __construct()
{
$this->middleware('auth')
}
public function yourFunction(Request $request)
{
$user = \Auth::user();
dd($user);
}
}
<?php
Route::get('your-uri', function () {
$user = \Auth::user();
dd($user);
})->middleware('auth');

Laravel middleware redirection

when i use laravel middleware its routes is not work properly
<?php
namespace App\Http\Controllers;
use Auth;
use App\Article;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
//use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function __construct(){
$this->middleware('auth',['only'=>'create']);
}
//
public function index(){
//return \Auth::user();
$articles = Article::latest('published_at')->published()->get();
return view('articles.index',compact('articles'));
}
public function show($id){
$article = Article::findorFail($id);
//dd($article->published_at->addDays(8)->diffForHumans());
return view('articles.show',compact('article'));
}
public function create(){
if(Auth::guest()){
return redirect('articles');
}
return view('articles.create');
}
public function store(ArticleRequest $request){
/*
$input = Request::all();
$input['published_at'] = Carbon::now();
*/
$article = new Article($request->all());
Auth::user()->articles()->save($article);
//Article::create($request->all());
return redirect('articles');
}
public function edit($id){
$article = Article::findorFail($id);
return view('articles.edit', compact('article'));
}
public function update($id, ArticleRequest $request){
$article = Article::findorFail($id);
$article->update($request->all());
return redirect('articles');
}
}
when i go to http://localhost/lernlaravel/public/articles/create it works fine
but when i go to http://localhost/learnlaravel/public/articles it redirect to http://localhost/articles.
index() method is used for listing articles how i can fix it?
The redirect () accepts a URL path so if you want ensure your redirect will work on both testing and production environments, I would pass either action () or route () to all of your applications redirect calls. In your this case I would go with
return redirect(action ('ArticlesController#show', $articles->id));
This way Laravel will automatically generate the proper URL path to the controller you want to handle the request.
If you choose to go with route() you are required to have named the route in your routes file, but I find that with resourceful controllers it's less complicated to go with action.

Resources