jeudi 9 février 2017

Cors Is Needed, but how do I do it with Middle ware in Laravel 5.3?

So I have the following middle ware (similar to this question):

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

}

Seems simple, its registered:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        // ...
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\Cors::class,
        // ...
    ];
}

The route uses it:

Route::group([
    'prefix'     => 'api/v1/',
    'middleware' => 'cors'
], function() {
    // ...
});

So by now we have everything working, great. Excellent. Now lets throw a wrench into our blog api, in the constructor lets do:

public function __construct(BlogsEntity $blogsEntity, BlogService $blogService, BlogValue $blogValue) {
    $this->blogsEntity  = $blogsEntity;
    $this->blogsService = $blogService;
    $this->blogValue    = $blogValue;

    $this->middleware('api.auth', ['only' => ['blogs', 'edit', 'delete']]);
    $this->middleware('api.blog.validation', ['only' => ['create', 'edit']]);
}

Ok so the first middle ware, since we will be calling the blogs method is the api.auth. What does that look like:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.']);
        }


        return $next($request);
    }
}

So you might be thinking, well ya - you are getting the error:

Fetch API cannot load http://ift.tt/2kTDsUc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ift.tt/2k8SpNR' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Because you are not setting CORS on the api auth request. So I did:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.'])
                ->headers( 'X-Total-Count', 0 );
        }


        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Same issue.

I have middle ware that affects specific routes and I have cors that affects all api routes. So how do I fix this?

I thought I was doing this right, the request coming in for any route, has all the associated headers on them If I remove the middle ware from the constructor, this works perfectly, no issue. If I remove the "only on blogs" part, its works perfectly. No issue.

The Cors middle ware is on every route for the api section. Yet some routes have specific middle ware that are triggered on specific actions that when enabled cause this cors issues, but when disabled do not.

help.



via Chebli Mohamed

Laravel 5: How to verify if values separated by comma from a database table field are contained in an array?

So, basically I have a field in a table from my database which contains some values separated by comma (something like: "value1, value2, value3"). I need to check somehow if one or more of these values are contained in an array of values and retrieve the model(s). I'd like a solution using Eloquent Model Query to achieve this, if not possible with Model Query, then a Query Builder solution will be okay as well, or maybe something alternative.



via Chebli Mohamed

Laravel save multiple record at once

have a problem to save multiple records at once. This is my form

    {!! Form::open(array('url'=>'pipeline/save?return='.$return, 'class'=>'form-horizontal','files' => true , 'parsley-validate'=>'','novalidate'=>' ')) !!}
    @foreach($destinazioni as $destinazione)
    <div class="col-md-2 col-md-offset-2 text-left">
        <input type="text" name="destination[]" readonly class="form-control" value=""/>

    </div>

    <div class="col-md-6 text-left">
        <select name="target[]" class="form-control">
        <option value="Nessuna">Seleziona...</option>
        @foreach($campi->keys() as $target)
        <option value="">  </option>
        @endforeach
        </select>
    </div>
    @endforeach
        @if(!empty($profilo->set_attributi))
            @foreach($profilo->attributi as $attributo)
            <div class="col-md-2 col-md-offset-2 text-left">
                <input type="text" name="destination[]" readonly class="form-control" value=""/>
            </div>
            <div class="col-md-6 text-left">
        <select name="target[]" class="form-control">
        <option value="Nessuna">Seleziona...</option>
        @foreach($campi->keys() as $target)
        <option value="">  </option>
        @endforeach
        </select>
    </div>
    @endforeach
@endif
<div style="clear:both"></div>  


                  <div class="form-group" style="margin-top:5%">
                    <label class="col-sm-4 text-right">&nbsp;</label>
                    <div class="col-sm-8">  
                    <button type="submit" name="apply" class="btn btn-info btn-sm" ><i class="icon-checkmark-circle2"></i> </button>
                    <button type="submit" name="submit" class="btn btn-primary btn-sm" ><i class="icon-bubble-check"></i> </button>
                    <button type="button" onclick="location.href='' " class="btn btn-warning btn-sm "><i class="icon-cancel-circle2 "></i>   </button>
                    </div>    

                  </div>

         {!! Form::close() !!}

This is controller where i try to handle inserting of data:

$rules = $this->validateForm();
    $validator = Validator::make($request->all(), $rules);  
    if ($validator->passes()) {
        $request = array('destination' => $request->input('destination'), 'target' => $request->input('target'));
        foreach ($request as $req) {
            $destination = new Pipeline;        
            $destination->destination = $req->destination;
            $destination->target = $req->target;
            $destination->save();
        }

        return Redirect::to('pipeline')->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');

But actually i get Try to get proprety of non object error. I have also tried with Pipeline::insert($data) method but it return wrong names of column error



via Chebli Mohamed

mercredi 8 février 2017

Laravel 5.1 logs out when firing multiple ajax requests

My Laravel 5.1 installation keeps logging out randomly when I fire multiple ajax requests. This is solved by using Redis as session driver, but since this installation is running on Xampp (Windows) I can't use that. I already tried to switch to database session driver but that did not sove the issue.

I'm running PHP5.6.

Any help is appreciated.



via Chebli Mohamed

laravel, how can I ignore a special route?

how can I ignore special routes with nginx server. for example I have a.com address and I want Ignore a.com/abc



via Chebli Mohamed

mardi 7 février 2017

API Laravel through Java application

I have a LARAVEL API coded in PHP with MYSQL Database but i want to create a Desktop App for few users, but for this i have to call my API with token csrf how can i do that

I tried like that

(It is a test class)

    package com.trying.text;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

public class Main {
    private final static String USER_AGENT = "Mozilla/5.0";
    private static String csrf;
    @Override
    public void start(Stage primaryStage) {

    }

    public static void main(String[] args) throws Exception {

        System.out.println("Testing 1 - Send Http GET request");
        sendGet();
        System.out.println("Testing 2 - Send Http POST request");
        sendPost();

    }

    public static void connectionHttp(){

    }

    // HTTP GET request
        private static void sendGet() throws Exception {

            String url = "http://ift.tt/2ko0YHN";

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");

            //add request header
            con.setRequestProperty("User-Agent", USER_AGENT);

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // strip out your required data with a regex
            Pattern pattern = Pattern.compile(".*<input type=\"hidden\" name=\"_token\" value=\"(.*?)\">.*");
            Matcher matcher = pattern.matcher(response.toString());

            if (matcher.find()) {
                System.out.println(matcher.group(1));
                csrf = matcher.group(1);
                sendPost();
            }
            //print result
            System.out.println(response.toString());

        }

        // HTTP POST request
        private static void sendPost() throws Exception {

            String url = "http://ift.tt/2kDR9nu";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "name=test&password=test&_token=" + csrf;

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());

        }
}

I succeed to make a get call when i don't have to give to him a csrf (The first call is route that didn't under web middleware (Laravel for security and more..) But when i need to call an adress that need a csrf i try to get the csrf of one page that i know that had a csrf hidden input but i don't sicced to send a post request.

I have a 500 HTTP response.



via Chebli Mohamed

lundi 6 février 2017

automated logout function using laravel 5.1

am a fresher developer , actually my task is to set a automatic expiry account in php laravel 5.1, i tried it with middleware but it downs the sever speed, ok give me some ideas, actuallly wat iam searching is, if i registering into a site, at that time am inserting a current time in db, after creating user log, am triying to logging , so once i regstred as a new user, that account login access will be deactivated within 24 hours , by comparing the time which you inserted time while regstr.????????



via Chebli Mohamed