I'm testing an API call that I have working in Postman and other interfaces built over the API, but I'm trying to actually get my return values within my laravel site.
Should be simple enough, I made a very bare service file that uses guzzle to get to the API url, and I have a function in there for logging in using a test email, password and client ID (all of which work in the api interface such as Postman)
I'm calling the class and function inside my authController and then returning the function call in the view, then dumping that inside the view.
However, currently I'm getting null on my page dump.
Is there something I'm missing here, possibly in my service file. I don't think there should be anything passed here, but maybe I'm overlooking something more obvious.
Authorize.php
<?php
namespace App\Services\restAPI;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Session;
use Exception;
class AuthService
{
protected $baseurl;
protected $guzzleClient;
public function __construct() {
$this->baseurl = config('http://ip.address');
$this->baseurl = rtrim($this->baseurl, '/') . '/'; // ensure trailing slash
$this->guzzleClient = new \GuzzleHttp\Client(
['verify' => config('app.ca_pem_file'),
'headers' => [
'Event-ID' => ACCESS_EVENT_ID
],
'base_uri' => $this->baseurl
]
);
}
public function loginGetToken(){
$password = "password";
$email = "test#thisAPI.com";
$client_id = "0";
$payload = (object)[
'password'=>(string)$password,
'email'=>(string)$email
];
$retval = $this->post('login/?client_id='.$client_id,$payload);
return $retval;
}
private function post($endpoint,$payload){
$result = $this->guzzleClient->request('POST', $endpoint, ['json'=>$payload]);
$body = $result->getBody();
return json_decode($body);
}
}
AuthController.php
use Redirect;
use Illuminate\Http\Request;
use App\Services\restAPI\AuthService;
class AuthController extends Controller
{
public function login(Request $request)
{
$authService = new AuthService();
$login = $authService->loginGetToken();
return redirect(route('auth.login'))
->with('login', $login)
}
login.blade.php
<?php
dd($login);
?>
Since you are redirecting, the data is not directly available in the view as a variable. It should be in the session though, so you can try this in your view:
dd(session('login'));
https://laravel.com/docs/5.7/redirects#redirecting-with-flashed-session-data
Related
If there is a process to set Session in Controller executed by test using PHPUnit, error "Session store not set on request" will be issued and it will fail.
PHP 7.1
Larval 5.8
PHPunit 7.5
public function auth(Request $request)
{
$email = $request->input('id');
$password = $request->input('password');
// I intend to succeed..
//$Client = App::make('Client');
//$res = $Client->authenticate($email, $password);
$res = true;
if ($res) {
$token = "sampletoken";
$request->session()->put('Authorization', $token);
return redirect()
->intended('/list');
}
return redirect('/login');
}
<?php
namespace Tests\Feature;
use Illuminate\Http\Request;
use App\Http\Controllers\LoginController;
use Tests\TestCase;
use Mockery;
class LoginControllerTest extends TestCase
{
public function testAuth()
{
$request = new Request();
$request->merge([
"id" => "test_id",
"password" => "test_pass"
]);
$controller = new LoginController();
$response = $controller->auth($request);
$this->assertEquals(preg_match('/\/list/', $response->getTargetUrl()), 1);
}
}
1) Tests\Feature\LoginControllerTest::testAuth
RuntimeException: Session store not set on request
Please tell me the solution.
In your test setUp method, you can set the session on the request, and tell it to use the array driver so that it isn't persisted:
$this->app['request']->setSession($this->app['session']->driver('array'));
I've been reading the documentation up and down now, still not sure what I'm doing wrong. In my opinion the documentation is very difficult to understand for a beginner.
Anyway, I'm trying to make something akin to the Auth::user() method, where it returns additional data about a logged in user that I will be needing for this application.
I have this helper class here:
namespace App\Helpers;
use Auth;
use Illuminate\Http\Request;
use App\Models\Grouping\User;
use App\Models\Grouping\Client;
use App\Models\Grouping\Rank;
class ClientUser {
public function __construct($request) {
$this->request = $request;
}
public function client() {
return Client::find($this->request->session()->get('client_id'));
}
public function auth() {
if (Auth::check()) {
// Get the client
$client = $this->client();
// Get the client's user
$user = $client->users()->find(Auth::user()['id']);
// Get the rank of the logged in user
$rank = Rank::find($user->pivot->rank_id);
return [
'user' => $user,
'rank' => $rank,
'client' => $client
];
}
return null;
}
}
This is responsible for doing what I described, returning additional data that I can't get through Auth::user(). Now I'm trying to register this class in the AuthServiceProvider
public function register()
{
// Register client auth
$request = $this->app->request;
$this->app->singleton(ClientUser::class, function ($app) {
return new ClientUser($request);
});
}
Now what I don't understand is how I'm supposed to make this globally accessible throughout my app like Auth::user() is.
The problem with just making "importing" it is that it needs the request object, which is why I'm passing it through the service container.
Now here's where I'm stuck. I'm not able to access app in my controller or anywhere, and I can't define a Facade because a Facade expects you to return a string of the bound service that it should "alias?"
Change your service provider like this :
$this->app->bind('client.user', function ($app) {
return new ClientUser($app->request);
});
Create another class extended from Illuminate\Support\Facades\Facade.
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class ClientUserFacade extends Facade {
public static function getFacadeAccessor(){
return "client.user";
}
}
Add 'ClientUser => ClientUserFacade::class in alias key of app.php
Repeated Calls – Lets say you need your Application to talk to an API and you're using guzzle or a wrapper or whatever. I find myself having to call the connection in every controller function e.g:
class ExampleController extends Controller
{
public function one()
{
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
$data = $json->object;
// do stuff
}
public function two()
{
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
$data = $json->object;
// do stuff
}
}
How do I better handle this? Do I use a service Provider? if so, how would I best implement these calls? Should I create another controller and call all my API connections in each function and then include that controller and call upon each function as required? Should I place it in a __construct?
lets try the Dependency inversion principle
Ok this might sound a bit hard at first and my code might have some typos or minor mistakes but try this
You need to create the interface
namespace app\puttherightnamespace; // this deppends on you
interface ExempleRepositoryInterface
{
public function getquery(); // if you passinga variable -> public function getquery('variable1');
}
Now you have to create the repo
class ExempleRepository implements ExempleRepositoryInterface {
public function getquery() {
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
return $json->object;
}
Now last step is to bind the interface to the repo in a service provider register method
public function register()
{
$this->app->bind('namespacehere\ExempleRepositoryInterface', 'namespacehere\ExempleRepository');
}
Now everytime you need the result in a controller all you have to do is to ineject
class ExempleController extends Controller {
private $exemple;
public function __construct(ExempleRepositoryInterface $home) {
$this->exemple = $exemple;
}
public function test() {
$data = $this->exemple->getquery(); / you can pass a variable here if you want like this $this->exemple->getquery('variable');
// do stuff
}
this is not the simplest way but this is the best way i guess
I have made the following custom guard:
<?php
namespace App\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
class LicenseGuard implements Guard
{
use GuardHelpers;
protected $request;
public function __construct(LicenseUserProvider $provider, Request $request)
{
$this->provider = $provider;
$this->request = $request;
}
public function user ()
{
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (!is_null($this->user))
return $this->user;
$user = null;
$licenseKey = $this->request->json('license_key');
if (!empty($licenseKey)) {
$user = $this->provider->retrieveByLicense($licenseKey);
}
return $this->user = $user;
}
public function validate (Array $credentials = [])
{
/* Validate code */
}
}
?>
In my middleware i have defined the following:
<?php
if($this->auth->guard($guard)->quest())
return response('You have entered an unknown license key', 401);
The error that i am getting is:
Fatal error: Call to undefined method App\Auth\LicenseGuard::quest()
I am using the default GuardHelper trait which has the "quest" method, i just can't find out why this is happening.
I am using PHP7 and Lumen 5.2
Not sure what you are doing there my friend, but I assume quest "isn't the droids you are looking for".
I need access to the RouteCollection that Laravel possesses when it gets ran normally and all ServiceProviders are booted. I need the RouteCollection because a legacy app needs to know if Laravel has the particular route, so if it doesn't, legacy code can take care of the route.
I figure if I can somehow get a hold of Illuminate\Routing\Router in an artisan command, I could simply call the getRoutes() function and output a JSON file containing an array of all the routes. Then when the legacy code needs to determine if Laravel supports the Route, it could read that file.
In order to do that though, I need access to the Router class. Not sure how to accomplish that... I looked at Illuminate\Foundation\Console\RoutesCommand source code and I can't figure out how it works. What's really odd is it looks like the Router class is being injected, but when I do Artisan::resolve('MyCommand'), I get an empty RouteCollection.
EDIT
I never did figure out how to accomplish this question, but for those in a similar situation, I found this works for the most part, although I'm not sure how bad the overhead is starting Laravel each request just to check the routes. Right now it doesn't seem like that much.
// Start laravel, so we can see if it should handle the request
require_once(__DIR__.'/laravel/bootstrap/autoload.php');
$app = require_once(__DIR__.'/laravel/bootstrap/start.php');
$app->boot();
// Create the fake request for laravel router
$request = Request::createFromGlobals();
$request->server->set('PHP_SELF', '/laravel/public/index.php/'.$_REQUEST['modname']);
$request->server->set('SCRIPT_NAME', '/laravel/public/index.php');
$request->server->set('SCRIPT_FILENAME', __DIR__.'/laravel/public/index.php');
$request->server->set('REQUEST_URI', '/laravel/public/'.$_REQUEST['modname']);
$routes = Route::getRoutes();
foreach($routes as $route) {
if ($route->matches($request)) {
$app->run($request);
exit;
}
}
Here is a simplified implementation
JsonRoutes.php
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
class JsonRoutes extends Command {
protected $name = 'routes:json';
protected $description = 'Spits route information in JSON format.';
protected $router;
protected $routes;
public function __construct(Router $router) {
parent::__construct();
$this->router = $router;
$this->routes = $router->getRoutes();
}
public function fire() {
$result = [];
foreach ($this->routes as $route) {
$result[] = [
'methods' => implode(',', $route->methods()),
'host' => $route->domain(),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => $route->getActionName(),
];
}
$file = $this->option('file');
if ($file) {
File::put($file, json_encode($result));
return;
}
$this->info(json_encode($result));
}
protected function getArguments() { return []; }
protected function getOptions() {
return [
['file', 'f', InputOption::VALUE_OPTIONAL, 'File name.'],
];
}
}
You register it in artisan.php:
Artisan::resolve('JsonRoutes');
Sample usage:
Spit it out to stdout
$ artisan routes:json
[{"methods":"GET,HEAD","host":null,"uri":"\/","name":null,"action":"Closure"}]
Write it to a file
$ artisan routes:json -f /tmp/routes.json