How to get ID of authorized user in jwt-auth? - laravel

How to get ID of authorized user in jwt-auth?
I tried to get id by standart method, but it does not work

When using jwt-auth you can get the user ID by parsing the JWT token:
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
$userId = $user->id;
# code...
}

Related

How to catch exception in parent control of class with findOrFail?

In Laravel 9 I make Repository class and in one of its methods I have with 2 findOrFail calling
use Illuminate\Database\Eloquent\ModelNotFoundException;
class ArticleToManyVotesRepository
...
public function store(int $id, int $manyItemId, array $data): JsonResponse|MessageBag
{
$article = Article::findOrFail($id);
$vote = Vote::findOrFail($manyItemId);
if ($article->votes()->where('vote_id', $manyItemId)->exists()) {
throw new CustomManyToManyItemException('Article "' . $id . '" with vote ' . $manyItemId . ' already exists');
}
DB::beginTransaction();
try {
$article->votes()->attach($manyItemId, $data);
DB::Commit();
} catch (\Exception $e) {
\Log::info(varDump($e->getMessage(), ' -1 STORE $e->getMessage()::'));
DB::rollback();
return sendErrorResponse($e->getMessage(), 500);
}
return response()->json(['result' => true], 201); // 201
}
In the parent controller I have try block with checks for ModelNotFoundException:
public function articleManyVotesStore(Request $request, int $articleId, int $voteId)
{
try {
$data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
return $repository->store(id: $articleId, manyItemId: $voteId,
data: $data);
} catch (ModelNotFoundException $e) {
return response()->json(['message' => $e->getMessage()], 404);
}
} catch (CustomManyToManyItemException $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
But as in store method there are 2 calling of "findOrFail" in which way can I catch a valid Exception of findOrFail ?
Seems findOrFail has no any parameters ?
Thanks!
one way is to compare exception model namespace like below
try {
$data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
return $repository->store(id: $articleId, manyItemId: $voteId,
data: $data);
} catch (ModelNotFoundException $e) {
if($e->getModel() === Article::class){
//add your logic here
}elseif($e->getModel() === Vote::class){
//add your logic here
}
return response()->json(['message' => $e->getMessage()], 404);
}

How to handle response (exception) in guzzle async request?

I need to get response from async request and retry request if it's not successful. I'm trying to test with printing message in log file if exception is called, but I'm not getting this error message.
What I tried so far ->
I followed this link: https://github.com/reactphp/promise#how-promise-forwarding-works
$promise = Api::async()->get($url)->then(
function ($result) {
$this->handleResult($result);
}
)->otherwise(function (\Exception $x) {
// Propagate the rejection
info('error');
throw $x;
});
$promise->wait();
$promise = Api::async()->get($url)->then(
function ($result) {
$this->handleResult($result);
}
)->then(function ($result) {
info('error');
throw new \Exception($result);
})->otherwise(function (\Exception $result) {
// Handle the rejection, and don't propagate.
// This is like catch without a rethrow
info('error');
return $result->getMessage();
})
->then(function ($result) {
info('error');
});
$promise->wait();
These two I tried from this docs: https://docs.php-http.org/en/latest/components/promise.html
$promise = Api::async()->get($url)->then(
function ($result) {
$this->handleResult($result);
}
);
try {
$promise->wait();
} catch (\Exception $exception) {
info('error');
}
$promise = Api::async()->get($url)->then(
// The success callback
function (ResponseInterface $res) {
},
function (\Exception $e) {
info('error');
}
);
$promise->wait();

How to Display Successful and Failed Data in Laravel Maatwebsites Import

In my Laravel-5.8 using Maatwebsites-3.1, I am trying to update Employee Leaves into MySQL database through MS Excel.
Controller
public function import(Request $request){
$request->validate([
'file' => 'required|max:10000|mimes:xlsx,xls',
]);
$path1 = $request->file('file')->store('temp');
$path=storage_path('app').'/'.$path1;
try{
Excel::import(new LeavesImport, $path);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
Log::error($e);
$errormessage = "";
foreach ($failures as $failure) {
$errormess = "";
foreach($failure->errors() as $error)
{
$errormess = $errormess.$error;
}
$errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
}
Session::flash('error', $errormessage);
return back();
}catch (\Illuminate\Database\QueryException $e)
{
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Log::error($e);
DB::rollback();
Session::flash('error', 'You have a duplicate entry problem!');
}
return back();
}
Session::flash('success', 'Leave Records Imported Successfully');
return redirect()->back;
}
Below is the code for the data to be imported from the MS Excel Sheet
Import
class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
protected $staffid, $leavetype, $commencementdate, $resumptiondate;
private $errors = []; // array to accumulate errors
use Importable;
return new HrLeaveRequest([
'employee_id' => $this->getStaffId(),
'leave_type_id' => $this->getLeaveType(),
'commencement_date' => $this->transformDate($row['commencement_date']),
'resumption_date' => $this->transformDate($row['resumption_date']),
'no_of_days' => $row['leave_days'],
]);
}
public function getStaffId(){
if(!empty($this->staffid)){
return HrEmployee::where('employee_code',$this->staffid)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
public function getLeaveType(){
if(!empty($this->leavetype) || !$this->leavetype){
return HrLeaveType::where('leave_type_name',$this->leavetype)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
// this function returns all validation errors after import:
public function getErrors()
{
return $this->errors;
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function batchSize(): int
{
return 200;
}
public function headingRow(): int
{
return 1;
}
}
I want to display:
The List Successful uploads
The list of failed uploads
How do I achieve this?
Thanks

How to use JWT for laravel API for different user tables?

These are the basic functions of the driver user.
public function authenticate(Request $request){
$credentials=$request->only('email','password');
try {
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
if (!$token =JWTAuth::attempt($credentials)) {
return response()->json(['error'=>'Invalid_Crendals'],401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(['token Login Driver'=>compact('token'),'msg'=>'driver']);
}
public function register(){
$email=request()->email;
$name=request()->name;
$last=request()->last;
$password=request()->password;
$driver=Driver::create([
'name'=>$name,
'email'=>$email,
'last'=>$last,
'password'=>bcrypt($password),
]);
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
$token=JWTAuth::fromUser($driver);
return response()->json(['token Driver'=>$token],200);
}
public function testd(){
try {
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
$token=JWTAuth::getToken();
$driver=JWTAuth::toUser($token);
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json($driver);
}
These are the conventional user functions
public function authenticate(Request $request){
$credentials=$request->only('email','password');
try {
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
if (!$token =JWTAuth::attempt($credentials)) {
return response()->json(['error'=>'Invalid_Crendals'],401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(['toke Login User'=>compact('token'),'msg'=>'User Register']);
}
public function register(){
$email=request()->email;
$name=request()->name;
$password=request()->password;
$user=User::create([
'name'=>$name,
'email'=>$email,
'password'=>bcrypt($password),
]);
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
$token=JWTAuth::fromUser($user);
return response()->json(['token'=>$token],200);
}
public function testd(){
try {
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
$token=JWTAuth::getToken();
$driver=JWTAuth::toUser($token);
} catch (JWTException $e) {
return response()->json(['error' => 'could_not__User_create_token'], 500);
}
return response()->json($driver);
}
And used a middleware for each one This is for the driver user
public function handle($request, Closure $next)
{
try {
Config::set('jwt.user','App\Driver');
Config::set('auth.providers.users.model', \App\Driver::class);
$user=JWTAuth::parseToken()->authenticate();
if (! $user) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return $next($request);
}
And for the conventional user
try {
Config::set('jwt.user','App\User');
Config::set('auth.providers.users.model', \App\User::class);
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return $next($request);
}
File App.php
Route::post('authenticate','Api\UserController#authenticate');
Route::post('register','Api\UserController#register');
Route::post('authenticate/driver','Api\DriverController#authenticate');
Route::post('register/driver','Api\DriverController#register');
Route::post('test/driver','Api\DriverController#testd')->middleware('driver');
Route::post('test/user','Api\UserController#testd')->middleware('user');
Users are authenticated and register well in their corresponding tables The problem I encounter is the following, When I use the generated token when registering a user Driver and I use this same token to access the route test / user where by logic this does not owe me To show no result since it is an incorrect token generated by another user, this same token enters the function and shows me the data of a conventional user. How can I solve this security problem? The truth has been many days and I have not been able to solve it.

massupdate customer data in magento customer grid

i need to massupdate customer streetaddress using magento. for this i wrote bultupdate function in customer grid controller. here is the query but it is not working. how can i change this query to update street address using customerid
public function massUpdateAction()
{
$customerIds = $this->getRequest()->getParam('customer');
$street_type = $this->getRequest()->getParam('street');
if (!is_array($customerIds)) {
$this->_getSession()->addError($this->__('Please select customer(s).'));
} else {
if (!empty($customerIds)) {
try {
foreach ($customerIds as $customerId) {
Mage::getSingleton('customer/address')
->updateAttributes($customerIds, array('billing_street_full' => $street_type), $storeId);
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
}
$this->_redirect('*/*/index');
}
Try this:
try {
foreach ($customerIds as $customerId) {
$addresses = Mage::getModel('customer/customer')->load($customerId)->getAddressesCollection();
foreach ($addresses as $address) {
$address->setData('billing_street_full', $street_type)->save();
}
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}

Resources