Laravel Policy works for view but not viewAny - php

My policy for an API controller seems to be working fine for view, but returns 'This action is unauthorized.' for viewAll, both while sending an admin api token. Using Laravel 7 with Spatie Roles/Permissions. AppBaseController extends Illuminate\Routing\Controller. I've tried it without the middleware, just to be sure. Tried commenting out the 'before' function, to make sure it's not conflicting. Double-checked I'm sending Answer::class with the viewAny call. Confirmed the model 'can' method also returns false on viewAny. Tried it with and without optional User parameter in viewAny. Read and re-read the documentation, and every similar issue on here I could find. Can't seem to work out the issue. Not even sure how to trace what Laravel is doing to get that response.
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//logged in
Route::group(['middleware' => ['auth:api', 'verified']], function () {
Route::get('answers', 'AnswerAPIController#index')->name('answers.index');
Route::post('answers/{id}', 'AnswerAPIController#store')->name('answers.store');
Route::get('answers/{id}', 'AnswerAPIController#show')->name('answers.show');
Route::put('answers/{id}', 'AnswerAPIController#update')->name('answers.update');
Route::delete('answers/{id}', 'AnswerAPIController#destroy')->name('answers.destroy');
});
AnswerPolicy.php
<?php
namespace App\Policies;
use App\Models\Answer;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class AnswerPolicy
{
use HandlesAuthorization;
/**
* Perform pre-authorization checks.
*
* #param \App\Models\User $user
* #param string $ability
* #return void|bool
*/
public function before(User $user, $ability)
{
if ($user->hasRole('admin')) {
return true;
}
}
/**
* Determine whether the user can view any answers.
*
* #param \App\Models\User $user
* #return mixed
*/
public function viewAny(User $user)
{
return true;
//
// if ($user !== null) {
// return true;
// }
}
/**
* Determine whether the user can view the answer.
*
* #param \App\Models\User|null $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function view(?User $user, Answer $answer)
{
return true;
// if ($answer->published) {
// return true;
// }
// visitors cannot view unpublished items
// if ($user === null) {
// return false;
// }
// // admin overrides published status
// if ($user->can('view answers')) {
// return true;
// }
}
/**
* Determine whether the user can create answers.
*
* #param \App\Models\User $user
* #return mixed
*/
public function create(User $user)
{
return true;
// if ($user->can('create answers')) {
// return true;
// }
}
/**
* Determine whether the user can update the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function update(User $user, Answer $answer)
{
return true;
// if ($user->can('edit answers')) {
// return true;
// }
}
/**
* Determine whether the user can delete the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function delete(User $user, Answer $answer)
{
return true;
// if ($user->can('delete answers')) {
// return $user->id == $answer->user_id;
// }
}
/**
* Determine whether the user can restore the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function restore(User $user, Answer $answer)
{
return true;
//
}
/**
* Determine whether the user can permanently delete the answer.
*
* #param \App\Models\User $user
* #param \App\Models\Answer $answer
* #return mixed
*/
public function forceDelete(User $user, Answer $answer)
{
return true;
//
}
}
AnswerAPIController.php
<?php
namespace App\Http\Controllers\API;
use Auth;
use Log;
use Throwable;
use App\Http\Controllers\AppBaseController;
use App\Http\Requests\API\CreateAnswerAPIRequest;
use App\Http\Requests\API\UpdateAnswerAPIRequest;
use App\Repositories\AnswerRepository;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
/**
* Class AnswerController
* #package App\Http\Controllers\API
*/
class AnswerAPIController extends AppBaseController
{
use AuthorizesRequests;
/** #var AnswerRepository */
private $answerRepository;
public function __construct(AnswerRepository $answerRepo)
{
$this->answerRepository = $answerRepo;
}
/**
* #param Request $request
* #return Response
*/
public function index(Request $request)
{
try {
$this->authorize('viewAny', Answer::class);
$answers = $this->answerRepository->all(
$request->has('search') ? $request->get('search') : [],
$request->has('skip') && $request->has('limit') ? $request->get('skip') : null,
$request->has('limit') ? $request->get('limit') : null,
$request->has('columns') ? $request->get('columns') : ['*'],
$request->has('with') ? $request->get('with') : null,
$request->has('sort') ? $request->get('sort') : 'id',
$request->has('direction') ? $request->get('direction') : 'asc'
);
return $this->sendResponse($answers->toArray(), 'Answers retrieved successfully.');
} catch (Throwable $e) {
$trace = $e->getTrace()[array_search(__FILE__, array_column($e->getTrace(), 'file'))];
Log::error($e->getMessage() . " (" . $trace['file'] . ":" . $trace['line'] . ")\r\n" . '[stacktrace]' . "\r\n" . $e->getTraceAsString());
return $this->sendError($e->getMessage(), $request->all());
}
}
/**
* #param int $id
* #return Response
*/
public function show($id, Request $request)
{
try {
/** #var Answer $answer */
$answer = $this->answerRepository->find(
$id,
$request->has('columns') ? $request->get('columns') : ['*'],
$request->has('with') ? $request->get('with') : null
);
$this->authorize('view', $answer);
if (empty($answer)) {
return $this->sendError('Answer (' . $id . ') not found.');
}
return $this->sendResponse($answer->toArray(), 'Answer retrieved successfully.');
} catch (Throwable $e) {
$trace = $e->getTrace()[array_search(__FILE__, array_column($e->getTrace(), 'file'))];
Log::error($e->getMessage() . " (" . $trace['file'] . ":" . $trace['line'] . ")\r\n" . '[stacktrace]' . "\r\n" . $e->getTraceAsString());
return $this->sendError($e->getMessage());
}
}
}
request URL (index)
https://evenpulse.test/api/answers?api_token=****
response
{
"success": false,
"message": "This action is unauthorized.",
"data": {
"api_token": "****"
}
}
request URL (view)
https://evenpulse.test/api/answers/1?api_token=****
response
{
"success": true,
"data": {
"id": 1,
"question_id": 1,
"order": 1,
"text": "asdf",
"is_correct": false
},
"message": "Answer retrieved successfully."
}

In a classic case of 'asking often illuminates the problem', I figured it out 30 seconds later, after two days of struggles.
In the 'viewAny' authorize method I had put in the Answer::class bit, but nowhere in the controller did I define what 'Answer' is. I fixed it by adding
use App\Models\Answer;
to the top of the controller.

Related

Laravel multiple policies always authenticated?

I'm using Laravel 9 with the Laravel Spatie Permissions package. I have users and roles in my system. Users have roles, and depending on their permissions on their role they either can or can't create new users / new roles etc.
I've set up my UserPolicy and RolePolicy, and am passing my User model to each since it's the user that needs to be checked against what permissions they have, then in the controller of my choice, such as my RoleController I run:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('viewAny', User::class);
$roles = Role::with('permissions')->get();
if (!$roles || count($roles) <= 0) {
return response()->json([
'message' => 'No roles found'
], 404);
}
return response()->json([
'roles' => $roles
], 200);
}
Strangely, if I edit my RolePolicy's viewAny permission and return false, I'm still able to see the data? I shouldn't be. what am I missing?
Here's my RolePolicy
<?php
namespace App\Policies\UserManagement;
use Spatie\Permission\Models\Role;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class RolePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function viewAny(User $user)
{
// TODO: if I return false I still have access?
if ($user->can('role_index')) {
return true;
}
}
/**
* Determine whether the user can view the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function view(User $user)
{
if ($user->can('role_show')) {
return true;
}
}
/**
* Determine whether the user can create models.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function create(User $user)
{
if ($user->can('role_store')) {
return true;
}
}
/**
* Determine whether the user can update the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function update(User $user)
{
if ($user->can('role_update')) {
return true;
}
}
/**
* Determine whether the user can delete the model.
*
* #param \App\Models\User $user
* #return \Illuminate\Auth\Access\Response|bool
*/
public function delete(User $user)
{
if ($user->can('role_destroy')) {
return true;
}
}
}
And my AuthServiceProvider:
<?php
namespace App\Providers;
use App\Models\User;
use Spatie\Permission\Models\Role;
use App\Policies\UserManagement\UserPolicy;
use App\Policies\UserManagement\RolePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* #var array<class-string, class-string>
*/
protected $policies = [
User::class => UserPolicy::class,
User::class => RolePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
ResetPassword::createUrlUsing(function ($user, string $token) {
$frontendUrl = trim(rtrim(config('lespro.frontend_url'), '/'));
return $frontendUrl . '/account/reset/?email=' . $user->email . '&token=' . $token;
});
// Implicitly grant "super_admin" role all permissions
// This works in the app by using gate-related functions like auth()->user->can() and #can()
Gate::before(function ($user, $ability) {
return $user->hasRole('super_admin') ? true : null;
});
}
}

How do I extend Laravel Sanctum's functionality?

I am specifically trying to get Sanctum's Guard class to look for the API token in a JSON request body if it can't find it in the Authorization header. I simply need to add an elseif after it checks for the bearer token.
So question is: What is the best way to override this method (or class) with my own, without touching the original Sanctum files?
<?php
namespace Laravel\Sanctum;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;
class Guard
{
/**
* The authentication factory implementation.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* The number of minutes tokens should be allowed to remain valid.
*
* #var int
*/
protected $expiration;
/**
* Create a new guard instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #param int $expiration
* #return void
*/
public function __construct(AuthFactory $auth, $expiration = null)
{
$this->auth = $auth;
$this->expiration = $expiration;
}
/**
* Retrieve the authenticated user for the incoming request.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
public function __invoke(Request $request)
{
if ($user = $this->auth->guard('web')->user()) {
return $this->supportsTokens($user)
? $user->withAccessToken(new TransientToken)
: $user;
}
if ($token = $request->bearerToken()) {
$model = Sanctum::$personalAccessTokenModel;
$accessToken = $model::where('token', hash('sha256', $token))->first();
if (! $accessToken ||
($this->expiration &&
$accessToken->created_at->lte(now()->subMinutes($this->expiration)))) {
return;
}
return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken(
tap($accessToken->forceFill(['last_used_at' => now()]))->save()
) : null;
}
}
/**
* Determine if the tokenable model supports API tokens.
*
* #param mixed $tokenable
* #return bool
*/
protected function supportsTokens($tokenable = null)
{
return in_array(HasApiTokens::class, class_uses_recursive(
$tokenable ? get_class($tokenable) : null
));
}
}
I don't know if you've already figured out but I think you need to add an entry in your AppServiceProvider boot method and override configureGuard functionality placed in SanctumServiceProvider at line 94.
app/Providers/AppServiceProvider.php
Auth::resolved(function ($auth) {
$auth->extend('sanctum', function ($app, $name, array $config) use ($auth) {
return tap($this->createGuard($auth, $config), function ($guard) {
$this->app->refresh('request', $guard, 'setRequest');
});
});
});
You will also need to override createGuard function to specify your custom Guard class with the functionality you require.

Laravel Policy bug

I have used Laravel Policies successfully in the past but am having issues with one currently.
In an ArticleController I have the following method:
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create', Article::class);
$categories = $this->categories;
return view('editable.news.create', compact('categories'));
}
My ArticlePolicy looks like this:
<?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use App\User;
use App\Article;
class ArticlePolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine whether the user can view the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function show(User $user, Article $article)
{
// If the article is published
if ($article->published) {
return true;
}
// A user with permission can view unpublished articles
if ($user->can('view unpublished articles')) {
return true;
}
// Authors can view their own unpublished posts
if ($user->username === $article->author->username) {
return true;
}
}
/**
* Determine whether the user can create posts.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
return true;
}
/**
* Determine whether the user can update the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function update(User $user, Article $article)
{
if ($user->can('edit own articles')) {
return $user->username === $article->author->username;
}
if ($user->can('edit any articles')) {
return true;
}
}
/**
* Determine whether the user can delete the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function delete(User $user, Article $article)
{
// A user can delete their own articles
if ($user->can('delete own articles')) {
return $user->username === $article->author->username;
}
// A user with permission can delete any article
if ($user->can('delete any articles')) {
return true;
}
}
}
You can see in the create method I am just returning true, this is deliberate.
Whenever I hit the create blade I always receive a 403 error.
I also have an accompanying test:
/** #test */
public function a_user_with_permission_can_create_an_article()
{
$this->setupPermissions();
$user = factory(User::class)->create();
$user->assignRole('news contributor');
$article = factory(Article::class)->raw(['excerpt' => null]);
$this->actingAs($user)
->get(route('thanos.articles.create'))
->assertStatus(200);
$this->post(route('thanos.articles.store'), $article);
$this->assertDatabaseHas('articles', [
'user_username' => $user->username,
'title' => $article['title']
]);
}

How to override method in Laravel

I`m trying override "public function sendCode()" to use it in LoginController from below TokenModel.
have done more than tripled confirmed that loading and calling TokenModel from LoginController as an instance is succeed but "public function sendCode()" is not included with TokenModel.
would be very helpful if anyone knows what happens here and tell me what I should code.
=======================TokenModel=========================
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Token extends Model
{
const EXPIRATION_TIME = 15; // minutes
protected $fillable = [
'code',
'user_id',
'used'
];
public function __construct(array $attributes = [])
{
if (! isset($attributes['code'])) {
$attributes['code'] = $this->generateCode();
}
parent::__construct($attributes);
}
/**
* Generate a six digits code
*
* #param int $codeLength
* #return string
*/
public function generateCode($codeLength = 4)
{
$min = pow(10, $codeLength);
$max = $min * 10 - 1;
$code = mt_rand($min, $max);
return $code;
}
/**
* User tokens relation
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Send code to user
*
* #return bool
* #throws \Exception
*/
public function sendCode()
{
if (! $this->user) {
throw new \Exception("No user attached to this token.");
}
if (! $this->code) {
$this->code = $this->generateCode();
}
try {
app('twilio')->messages->create($this->user->getPhoneNumber(),
['from' => env('TWILIO_NUMBER'), 'body' => "Your verification code is {$this->code}"]);
} catch (\Exception $ex) {
return false; //enable to send SMS
}
return true;
}
/**
* True if the token is not used nor expired
*
* #return bool
*/
public function isValid()
{
return ! $this->isUsed() && ! $this->isExpired();
}
/**
* Is the current token used
*
* #return bool
*/
public function isUsed()
{
return $this->used;
}
/**
* Is the current token expired
*
* #return bool
*/
public function isExpired()
{
return $this->created_at->diffInMinutes(Carbon::now()) > static::EXPIRATION_TIME;
}
}
=======================LoginController=========================
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Token;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
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 = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
public function login(Request $request)
{
$this->validateLogin($request);
//retrieveByCredentials
if ($user = app('auth')->getProvider()->retrieveByCredentials($request->only('email', 'password'))) {
$token = Token::create([
'user_id' => $user->id
]);
if ($token->sendCode()) {
session()->set("token_id", $token->id);
session()->set("user_id", $user->id);
session()->set("remember", $request->get('remember'));
return redirect("code");
}
$token->delete();// delete token because it can't be sent
return redirect('/login')->withErrors([
"Unable to send verification code"
]);
}
return redirect()->back()
->withInputs()
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
/**
* Show second factor form
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function showCodeForm()
{
if (! session()->has("token_id")) {
return redirect("login");
}
return view("auth.code");
}
/**
* Store and verify user second factor.
*/
public function storeCodeForm(Request $request)
{
// throttle for too many attempts
if (! session()->has("token_id", "user_id")) {
return redirect("login");
}
$token = Token::find(session()->get("token_id"));
if (! $token ||
! $token->isValid() ||
$request->code !== $token->code ||
(int)session()->get("user_id") !== $token->user->id
) {
return redirect("code")->withErrors(["Invalid token"]);
}
$token->used = true;
$token->save();
$this->guard()->login($token->user, session()->get('remember', false));
session()->forget('token_id', 'user_id', 'remember');
return redirect('home');
}
}

Task runs on my local machine but not production Laravel Lumen

I am having an issue with my production env. On my local machine when I run the command I built:
php artisan updateusers:badcustomernumbers
everything runs as expected, no jobs fail.
When I deployed and tried to run this same task I get:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method App\Services\MiddlewareApi::get_lowest_active_customer_number_by_email() in .../app/Jobs/UpdateBadCustomerNumbersJob.php:48
Here is UpdateBadCustomerNumbersJob.php:
<?php
namespace App\Jobs;
use App\AppUser;
use Illuminate\Support\Facades\Log;
use App\Subscription;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mockery\Exception;
use App\Http\Controllers\UpdateUserController;
use App\Services\MiddlewareApi;
class UpdateBadCustomerNumbersJob extends Job
{
/**
* App users to update customer number for
* #var AppUser
*/
protected $appUsers;
/**
* The number of times the job may be attempted.
*
* #var int
*/
public $tries = 2;
/**
* UpdateBadCustomerNumbersJob constructor.
* #param $appUsers
*/
public function __construct($appUsers)
{
$this->appUsers = $appUsers;
}
/**
* #param UpdateUserController $updateUserController
*/
public function handle(UpdateUserController $updateUserController)
{
$middlewareApi = new MiddlewareApi();
foreach ($this->appUsers as $user) {
$userCustomerNumber = $middlewareApi->get_lowest_active_customer_number_by_email($user->email);
if(!is_null($userCustomerNumber) AND $userCustomerNumber !== false AND !empty($userCustomerNumber->customerNumber)) {
$updateUserController->updateAggregateCustomerNumber($user, $userCustomerNumber, true);
$updateUserController->updateAppDatasCustomerNumber($user, $userCustomerNumber, true);
$updateUserController->updateSubscriptionsCustomerNumber($user, $userCustomerNumber, true);
$updateUserController->updateAppUserCustomerNumber($user, $userCustomerNumber, true);
} else {
//if there is no customer number available just delete this user because they must not have any active subscriptions any longer
$updateUserController->deleteAggregateData($user);
$updateUserController->deleteAppDatas($user);
$updateUserController->deleteSubscriptions($user);
$updateUserController->deleteAppUser($user);
}
}
}
}
and here is MiddlewareAPI.php:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Mockery\Exception;
use GuzzleHttp\Client;
class MiddlewareApi
{
/**
* #var $middlewareToken
*/
private $middlewareToken;
/**
* #var $middlewareUrl
*/
private $middlewareUrl;
public function __construct()
{
$this->setMiddlewareToken(env('MIDDLEWARE_TOKEN'));
$this->setMiddlewareUrl(env('MIDDLEWARE_BASE_URL'));
}
/**
* Sets the Middleware API Token
* #param $token
*/
public function setMiddlewareToken( $token )
{
$this->middlewareToken = $token;
}
/**
* Gets the Middleware API Token
* #return mixed
*/
public function getMiddlewareToken()
{
return $this->middlewareToken;
}
/**
* Sets the Middleware base url
* #param $url
*/
public function setMiddlewareUrl( $url )
{
$this->middlewareUrl = $url;
}
/**
* Gets the Middleware base url
* #return mixed
*/
public function getMiddlewareUrl()
{
return $this->middlewareUrl;
}
/**
* Retrieves the Active subscriptions of a customer
* based on customer number
* #param $customerNumber
* #return bool|mixed
*/
public function get_customer_subscriptions_by_customer_number( $customerNumber )
{
$url = $this->getMiddlewareUrl() . 'sub/active/customernumber/' . $customerNumber;
$header = ['Token' => $this->getMiddlewareToken()];
$errorText = 'Error in get_customer_subscriptions_by_customer_number: ';
return $this->_get($url,$header,$errorText);
}
/**
* Retrieves the Active subscriptions and Products of a customer
* #param $customerNumber
* #return bool|mixed
*/
public function get_customer_subscriptions_and_products_by_customer_number( $customerNumber )
{
$url = $this->getMiddlewareUrl() . 'data/customernumber/' . $customerNumber;
$header = ['Token' => $this->getMiddlewareToken()];
$errorText = 'Error in get_customer_subscriptions_by_customer_number: ';
return $this->_get($url,$header,$errorText);
}
/**
* Retrieve the lowest active customer number by email address
* #param $email
* #return bool|mixed
*/
public function get_lowest_active_customer_number_by_email( $email )
{
$url = $this->getMiddlewareUrl() . 'customer/findlowestactivecustomernumber/emailaddress/' . $email;
$header = ['Token' => $this->getMiddlewareToken()];
$errorText = 'Error in get_lowest_active_customer_number_by_email: ';
return $this->_get($url, $header, $errorText);
}
/**
* Get method to make all get calls from middleware
* #param $endpoint
* #param $headers
* #param $errorText
* #return bool|mixed
*/
public function _get($endpoint, $headers, $errorText)
{
$client = new Client();
try {
$response = $client->request('GET', $endpoint,
['headers' => $headers]
);
$responseData = json_decode($response->getBody()->getContents());
return $responseData;
} catch (Exception $e) {
Log::error($errorText. $e);
return false;
}
}
/**
* Returns data with status code in json format
* #param $statusCode
* #param $data
* #return \Illuminate\Http\JsonResponse
*/
public function apiReturnResponseInJson( $statusCode, $data )
{
$content = ['status' => $statusCode, 'data' => $data];
return response()->json($content, $statusCode);
}
}
I tried running composer update and php artisan cache:clear but I am still getting the same error. I even ssh'd in and get_lowest_active_customer_number_by_email method is present in MiddlewareApi.php.
Any ideas what the problem may be?

Categories