Laravel redirect to a named route with param returns status 200 - redirect

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?

Related

Yii2 bug with CORS when not valid access token

I did with yii2 an acess token authorization if the access token is valid it works fine, but if the access token is invalid it returns the following CORS problem
Access to XMLHttpRequest at 'server' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
if the token is expired, the server works fine storing the old token on another table etc, but the client still gets the same CORS problem
I don't understand why it only happens when I try to return a 401 response, but it works when the acces token is valid, any idea?
This is the code I think its relevant
BehaviorsConfig.php
public static function corsFilterConfig($metodos_aceptados)
{
return [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Allow-Origin' => ['*'], // Añadido
'Access-Control-Request-Method' => $metodos_aceptados,
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => false,
'Access-Control-Max-Age' => 86400,
],
];
}
public static function authenticatorConfig()
{
return [
'class' => QueryParamAuth::className(),
'except' => ['options'],
'tokenParam' => 'access_token',
];
}
every controller
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = BehaviorsConfig::corsFilterConfig(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
$behaviors['authenticator'] = BehaviorsConfig::authenticatorConfig();
return $behaviors;
}
and now to check if the token is still valid and not expired I did this function
public function beforeAction($action){
if(AccessService::isExpired()){
throw new HttpException(401, "Sesión expirada, vuelva a conectarse.");
}
if (!parent::beforeAction($action)) {
return false;
}
return true;
}

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

How to integrate instamojo payment gateway with codeigniter rest server?

I am trying to integrate Instamojo Payment Gateway within Chris Kacerguis’ REST Server.
Problem:
The below code:
public function instamojotest_post()
{
$api = new Instamojo\Instamojo(‘abcd1234’, ‘efgh5678’, 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
header('Location: ' . $response['longurl']);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
is not redirecting to the Instamojo Payment Site and no error is being displayed.
It is working fine and redirecting successfully with vanilla CodeIgniter.
Questions:
1) Is it, at all, possible to redirect from within a REST Server Post Method?
2) If the above is possible, then what is wrong with my code?
3) Is there any other way to achieve what I am trying to do?
I found many tutorials on the internet but none of them are using REST Server.
I stumbled accross this question while Googling. I was also facing the same issue and here is how I solved it.
Note: This is not exactly a solution but a work-around. Also I admit that this may not be the best solution out there, but it worked for me.
I returned the payment url from the Rest Server, and redirected to the url from within the Rest Client.
Rest Client Code:
class Test extends CI_Controller
{
public function instamojo_make_payment()
{
$url = "http://www.example.com/products_api/instamojotest";
$params = []; //You will obviously be needing this in real life implementation :)
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
if ($response['success'])
header('Location: ' . $response['payment_url']);
else
$this->load->view('payment_failed_page');
}
}
Rest Server Code:
class Products_api extends REST_Controller
{
public function instamojotest_post()
{
$api = new Instamojo\Instamojo('abcd1234', 'efgh5678', 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate([
//Make sure to pass these data from the Rest Client
'amount' => 100,
'purpose' => 'New Product Purchase',
'buyer_name' => 'Test User',
'email' => 'testuser#gmail.com',
'phone' => '9876543210',
'redirect_url' => 'http://www.example.com/products_api/validate_payment'
]);
$this->response([
'success' => true,
'payment_url' => $response['longurl']
], 200);
} catch (Exception $e) {
$this->response([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
}
While giving this answer I assumed that the Api is open. If it is not, then make sure to pass your credentials when making the curl call.
Update
Thanks to #AshwiniChaudhary's comment below, which states that:
REST APIs are not meant for redirection. REST API returns JSON, XML
etc and the receiver takes care of whatever is supposed to be done.
the actual reason behind the fact, "why REST Server is not letting us to perform the redirect", becomes pretty clear.

Validation error messages as JSON in Laravel 5.3 REST

My app is creating a new entry via a POST request in an api end point.
Now, if any validation is failed then instead of returning an error json, laravel 5.3 is redirecting the request to home page.
Here is my controller:
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization);
}
If there is no issue with validation then the entity will be successfully added in the database, but if there is issue with validating the request then instead of sending all the error messages as a json response it redirects back to the home page.
How i can set the validate return type to json, so with every request if the validation failed then laravel will send all the error messages as json by default.
You can do your validation as:
$validator = \Validator::make($request->all(), [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422)
}
The validation used in the question looks as per the recommendation by laravel. The reason of redirection is that it throws an exception which you can easily catch using the code below. So it's better to use the recommended way of code instead of re-writing framework's code again :)
public function create( Request $request )
{
$organization = new Organization;
// Validate user input
try {
$this->validate($request, [
'organizationName' => 'required',
'organizationType' => 'required',
'companyStreet' => 'required'
]);
} catch (ValidationException $e) {
return response()->json($e->validator->errors(), 422);
}
// Add data
$organization->organizationName = $request->input('organizationName');
$organization->organizationType = $request->input('organizationType');
$organization->companyStreet = $request->input('companyStreet');
$organization->save();
return response()->json($organization, 201);
}

Redirect URL callback for facebook is not taking Base Url laravel 5

Hello everyone I'm trying to integrate facebook login using laravel5, In my code i have mentioned my redirect URL so it should go on below mentioned URL but when i'm trying to login with facebook my url is coming like this it's not taking my folder name see the difference in both URLs
http://localhost:8000/facebook/callback?code=xxxxx
Correct Url
http://localhost:8000/facebook/public/facebook/callback/
'facebook' => [
'client_id' => 'xxxxxxxxxxxxxxx',
'client_secret' => 'xxxxxxxxxxxxxxxxxxx',
'redirect' => 'http://localhost:8000/facebook/public/facebook/callback/',
],
This is my routes
Route::get('facebook/callback', 'Auth\AuthController#handleProviderCallback');
My controller
public function handleProviderCallback()
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
return redirect('facebook');
}
$authUser = $this->findOrCreateUser($user);
Auth::login($authUser, true);
return redirect()->route('home');
}