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

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

Related

Missing required parameter for [Route: verification.verify]

On a project I have I am using Fortify as my BE. I need a multilingual app, therefore I added the
'prefix' => {locale}' to config/fortify.php.
Login, registering, and 2FA, are working ok, but the problem arrives with the email verification process.
If I try to click on the link received by email, it goes to the /email/verify and returns a forbidden page error.
Then if I request to get another verification email it returns the error displayed on the title of the question.
Probably it has something to be with the locale parameter because when I run route::list, the verification.verify route is displayed with the endpoint of {locale}/email/verify/{id}/{hash}, so I assume that the link on the request another mail is causing the error since it is referenced as /email/verify/{id}/{hash}.
So does anyone know how to change it?
Or has anyone faced a similar problem regarding Fortify and these localization routes?
What I had to do was to customize some of the default Fortify functions, extending some classes in order to add the locale parameter to them.
When a new user is registered (event) it sends the verification email (listener), so I had to configure the files involved in this flow.
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Registered;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class SendEmailVerificationNotification implements ShouldQueue
{
use Queueable;
public function handle(Registered $event)
{
if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
$event->user->sendCustomVerificationEmailNotification();
}
}
}
And create the function sendCustomVerificationEmailNotification on the user's model and the notification CustomVerificationNotification that will be sent.
public function sendCustomVerificationEmailNotification()
{
$this->notify(new CustomVerificationNotification);
}
<?php
namespace App\Notifications;
use Carbon\Carbon;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;
class CustomVerificationNotification extends VerifyEmail
{
protected function verificationUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable);
}
return URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'locale' => app()->getLocale(),
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
}
}
Then in case, the user wants an additional verification email notification, this is handled through a function on the EmailVerificationNotificationController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
class CustomEmailVerificationController extends EmailVerificationNotificationController
{
/**
* Send a new email verification notification.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect()->intended(Fortify::redirects('email-verification'));
}
$request->user()->sendEmail();
return $request->wantsJson()
? new JsonResponse('', 202)
: back()->with('status', 'verification-link-sent');
}
}

Laravel override Login controller, login(). How do i retrieve logged in user data if i overwrite the login controller. I tried to get auth() data

I used laravel like 4 years ago. Had to work on a project on laravel and tried using my own authentication methods but mybad forgot there was already inbuilt better security authentication. I understand if my question seem to be basic.
As you can see the commented line "$userID = Auth::user()->userID;" the auth() is null therefore, userID cannot get its id from null. I am unable to get user session data in any other controllers as well.
Any kind of help or suggestions is appreciated.
P.S. i have used the default login and registration inbuilt function only required function like login is override code. I am using laravel v 4.2.3. I tried passing the userid as url parameter but then discarded it as inbuilt session data makes it more secure and easier
the login function of my controller looks like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function login(Request $request){
$user = new User(); //my model User
$result=$user->login($request); //result has the id of the user
if ($result) {
//$userID = Auth::user()->userID;
return redirect()->route('homepage');
}else{
return redirect()->route('login');
}
}
}
model for user login()
//Auth user then let them login
public function login($request){
$email = $request->input('email');
$password = $request->input('password');
$result=DB::table('users')
->where('email', $email)
->where('password', $password)
->get();
return $result;
}
My Routes.. its default route of "Auth::routes();"
Route::get('/homepage/{userID?}', function($userID = null){
return view('index', ['userID' => $userID]);
})->name('homepage');
Route::get('/evaluate/{userID?}', function ($userID = null) {
return view('evaluate', ['userID' => $userID]);
})->name('evaluate');
I installed a fresh new laravel and tried my code again and somehow it worked. Must have made some errors when trying to override the codes. Thank you

Automatically logout after refreshing the page in laravel 6

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

Laravel Notification not passing data and getting error "must be an instance of App\\Notifications\\User"

I am trying to use Laravel Notification to send email but getting this error
{
"message": "Type error: Argument 1 passed to App\\Notifications\\UserResetPasswordNotify::__construct() must be an instance of App\\Notifications\\User, instance of Illuminate\\Database\\Eloquent\\Collection given, called in /home/fy3bgmgte060/public_html/svs.com/app/Http/Controllers/Api/LoginController.php on line 143",
"status_code": 500
}
My Controller function
public function resendOTPTest(Request $request)
{
$user = User::where(['mobile' => $request->mobile])->first();
Notification::send($user, new UserResetPasswordNotify($user));
return response()->json(['message' => 'success','data' => 'OTP Sent', 'success' => true], 200);
}
my Notification file
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class UserResetPasswordNotify extends Notification
{
use Queueable;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
$user = $this->user;
return (new MailMessage)
->from('info#test.com')
// ->name('Entrance India')
->subject('New OTP from SVS ')
->markdown('mail.userResetPassword', compact('user'));
}
public function toArray($notifiable)
{
return [
//
];
}
}
this id my User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Order;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'fname','lname', 'email','gender', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
}
while trying to use Laravel Notification to send email but getting above error
But same thing is working for User creation function but it is not working for reset Password function
Where am I wrong?
Include User Class in your Notification Class
You are Injecting User Dependency as Typehint to the Magic Method __Cunstructor into your Notification Class.
You have to make sure Class is available there.
Simply use this in your Notification Class.
use App\User
You need to add
use App\User
in Notification file.
Try using $user->notify(new UserResetPasswordNotify($user))

laravel 5.4 login attempts don't work

I am trying to limit my login attempts but still not working
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
and this is ThrottlesLogin.php
protected function hasTooManyLoginAttempts(Request $request)
{
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request), 3, 2
);
}
and i know in laravel 5.4 the AuthenticatesUsers call by default thethrottlesLogin but still dont limit login attempts.
and thanks
You need to use ThrottlesLogins trait in LoginController

Resources