Last require in index.php only work for routes - slim

I am creating API in SLIM in which i have included two routes files customers.php and books.php. books.php route file is working properly but when i run customers.php routes it says 404 error.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../src/config/db.php';
$config = [
'settings' => [
'displayErrorDetails' => true,
//'determineRouteBeforeAppMiddleware' => true,
'debug' => true
],
];
$app = new \Slim\App($config);
//$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
// Customer routes
require '../src/routes/customers.php'; //this route file does not work
require '../src/routes/books.php'; //this route file work
$app->run();

Related

Laravel redirect to a named route with param returns status 200

I have the following named route with params, to which I want to redirect from a post request:
Route::get('/view-project-team/{project_request_id}', 'SinglePageController#viewProjectTeam')->name('view.project.team');
The controller where I handle the post request:
public function createProjectTeam(Request $request){
try {
$projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);
TeamMember::whereIn('email', $request->projectTeamEmails)
->update([
'project_request_id' => $projectRequest->id
]);
$projectTeam = TeamMember::get();
/*return response()->json( [
'success'=> true,
'projectRequestId' => $projectRequest->id
]);*/
return redirect()->route('view.project.team', ['project_request_id' => $projectRequest->id ]);
} catch(\Exception $e){
return ['success' => false, 'message' => 'project team creation failed'];
}
}
And the response that I get:
In the network tab, I see 90 under Name, which obviously stands for the id and only when I hover over I see the full URL http://team-management-tool.test/view-project-team/90
It is so weird as it seems correct the way i use the redirect, no clue what can be the issue then?

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

Stop sending the access token with the response body in Yii2

I am developing a rest API using Yii2, the front end is developed by ionic.
the case is that when I have an action which it uses bearer authentication..
it works fine but the access token is returned with the response body which leads to an HttpErrorResponse in the client side:
SyntaxError: Unexpected token y in JSON at position 0 at Json.parse
the response is returned like this so the client is not able to parse the json
y2sSCEXqkUoVY2BjkQZqx8g3W42273Cz{"success":false,"message":"you liked it before"}
this is the behaviour code which uses the bearear authentication
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => CorsCustom::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'only' => ['like', 'unlike', 'likes', 'create'],
'authMethods' => [
HttpBearerAuth::className(),
],
];
return $behaviors;
}
I want to stop sending the access token in the body or send it as a json
I think you should remove the echo $token statement from your USER model
public static function findIdentityByAccessToken($token, $type = null)
{
/* echo $token; */
return static::findOne(['auth_key' => $token]);
}
Stop echo the token before the response and you'll get your job DONE!
public static function findIdentityByAccessToken($token, $type = null)
{
/* echo $token; */
return static::findOne(['auth_key' => $token]);
}

Silex default_target_path not working after successful login

I've got a problem ith redirect after successful login.
App.php file (part of it):
<?php
use Silex\Application;
/** ... */
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
$app = new Application();
/** ... */
$app['security.encoder.digest'] = $app->share(function ($app) {
return new PlaintextPasswordEncoder();
});
$app['security.firewalls'] = array(
'secured' => array(
'pattern' => '^/admin/',
'form' => array(
'login_path' => '/login',
'check_path' => '/admin/login_check',
'default_target_path' => '/admin/news',
'always_use_default_target_path' => true,
),
'logout' => array(
'logout_path' => '/admin/logout',
),
'users' => array(
'admin' => array('ROLE_ADMIN', 'test'),
),
),
);
My controllers.php file:
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app->get('/login', function(Request $request) use ($app) {
return $app['twig']->render('login.html.twig', array(
'error' => $app['security.last_error']($request),
'last_username' => $app['session']->get('_security.last_username'),
));
});
$app->get('/admin/news', function(Request $request) use ($app) {
if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
echo 'admin';
}
});
I am logged in (after passing correct login data in form), I have access to /admin/news route, but I have to go to that address manually. I'd like to be redirected there automatically after successful login. Now I'm kept in /login page. When I change default_target_path to 'http://google.com', it works properly.
I use homestead (vagrant) with nginx. Silex 1.3.0.
I'll appreciate any help.
The solution (or rather workaround) which worked was:
change 'default_target_path' to '/admin';
add new route:
$app->get('/admin', function() use ($app) {
return $app['twig']->render('admin/loggedIn.html.twig');
});
in admin/loggedIn.html.twig template I've added js redirect to admin/news
I don't have any idea why wasn't it working. If anyone knows - please leave a comment.

Validate and process form in different routes, Symfony2

I'm doing a search page for my users. Form is displayed in the path /home and the collected data is sent to the path /search. There these are used to do a search which I show at /search. The problem is that if the form is processed at /search and there is any validation error the form is reloaded in /search and not at /home. Is there any way to get this?
//routing.yml
home:
path: /
defaults: { _controller: UsuarioBundle:Default:home}
search:
path: /search
defaults: { _controller: UsuarioBundle:Default:search}
.
//UsuarioBundle/Controller/DefaultController.php
public function homeAction()
{
$request = $this->getRequest();
$usuario = new Usuario();
$formulario = $this->createForm(new UsuarioBusquedaType(), $usuario, array(
'action' => $this->generateUrl('search'),
'method' => 'POST',
));
return $this->render('UsuarioBundle:Default:portada.html.twig', array('formulario' => $formulario->createView() ));
}
public function searchAction()
{
$request = $this->getRequest();
$usuario = new Usuario();
$formulario = $this->createForm(new UsuarioBusquedaType(), $usuario, array(
'action' => $this->generateUrl('search'),
'method' => 'POST',
));
$formulario->handleRequest($request);
if ($formulario->isValid()) {
// Validate and search in DB
return $this->render('UsuarioBundle:Default:resultado.html.twig', array('usuarios' => $usuarios));
}
return $this->render('UsuarioBundle:Default:portada.html.twig', array('formulario' => $formulario->createView() ));
I have also tried to do so: display the form and process it in the same path /home and then send the data through a redirection but I don’t know how to pass data to the new route. Any idea?
Thanks in advance.
You could try something like this:
if ($formulario->isValid()) {
// Validate and search in DB
return $this->render('UsuarioBundle:Default:resultado.html.twig', array('usuarios' => $usuarios));
}
return $this->homeAction();