dimanche 3 mai 2020

Vue / Laravel: How to validate files uploaded from the frontend?

I have an image uploader on my Vue app that takes multiple files. I want to ensure they are images and of a certain size and if not, obviously don't upload the files and have the frontend display the error. Right now, the route it hits in the controller loos like this:

   public function uploadAssets(UploadAssetsFormRequest $request)
    {
        if ($request->hasFile('file')) {
            $files = $request->file('file');
            $stack = [];
            foreach ($files as $file) {
                $fileName = Storage::put('/check/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
                array_push($stack, $fileName);
            }
            return response()->json($stack);
        }
    }

My Form Request is below and has the validation but I don't know how to apply that in the controller.

UploadAssetsFormRequest

<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UploadAssetsFormRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'files.*' => 'required|image|max:1000',
        ];
    }

    public function messages()
    {
        return [
            'files.*.max'   => 'The image is too large',
            'files.*.image' => 'Only image files are allowed.',
        ];
    }
}


via Chebli Mohamed

samedi 2 mai 2020

Laravel Passport JWT authentication failing

Out of the blue I started getting this error in production when trying to create a JWT through passport, running on Ubuntu/apache2. As far as I'm aware nothing was changed on the server, no installs, no deployments, it just stopped working.

production.ERROR: There was an error while creating the signature: error:04066044:rsa routines:rsa_ossl_private_encrypt:internal error {"exception":"[object] (InvalidArgumentException(code: 0): There was an error while creating the signature: error:04066044:rsa routines:rsa_ossl_private_encrypt:internal error at /api/vendor/lcobucci/jwt/src/Signer/OpenSSL.php:27)
[stacktrace]
#0 /api/vendor/lcobucci/jwt/src/Signer/BaseSigner.php(36): Lcobucci\\JWT\\Signer\\OpenSSL->createHash('eyJ0eXAiOiJKV1Q...', Object(Lcobucci\\JWT\\Signer\\Key))
#1 /api/vendor/lcobucci/jwt/src/Builder.php(470): Lcobucci\\JWT\\Signer\\BaseSigner->sign('eyJ0eXAiOiJKV1Q...', Object(Lcobucci\\JWT\\Signer\\Key))
#2 /api/vendor/lcobucci/jwt/src/Builder.php(450): Lcobucci\\JWT\\Builder->createSignature(Array, Object(Lcobucci\\JWT\\Signer\\Rsa\\Sha256), Object(Lcobucci\\JWT\\Signer\\Key))
#3 /api/vendor/league/oauth2-server/src/Entities/Traits/AccessTokenTrait.php(41): Lcobucci\\JWT\\Builder->getToken()
#4 /api/vendor/league/oauth2-server/src/ResponseTypes/BearerTokenResponse.php(28): Laravel\\Passport\\Bridge\\AccessToken->convertToJWT(Object(League\\OAuth2\\Server\\CryptKey))
#5 /api/vendor/league/oauth2-server/src/AuthorizationServer.php(202): League\\OAuth2\\Server\\ResponseTypes\\BearerTokenResponse->generateHttpResponse(Object(Zend\\Diactoros\\Response))
#6 /api/vendor/laravel/passport/src/Http/Controllers/AccessTokenController.php(63): League\\OAuth2\\Server\\AuthorizationServer->respondToAccessTokenRequest(Object(Zend\\Diactoros\\ServerRequest), Object(Zend\\Diactoros\\Response))
#7 /api/vendor/laravel/passport/src/Http/Controllers/HandlesOAuthErrors.php(28): Laravel\\Passport\\Http\\Controllers\\AccessTokenController->Laravel\\Passport\\Http\\Controllers\\{closure}()
#8 /api/vendor/laravel/passport/src/Http/Controllers/AccessTokenController.php(65): Laravel\\Passport\\Http\\Controllers\\AccessTokenController->withErrorHandling(Object(Closure))
#9 /api/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(48): Laravel\\Passport\\Http\\Controllers\\AccessTokenController->issueToken(Object(Zend\\Diactoros\\ServerRequest))
#10 /api/vendor/laravel/framework/src/Illuminate/Routing/Route.php(219): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(Laravel\\Passport\\Http\\Controllers\\AccessTokenController), 'issueToken')
#11 /api/vendor/laravel/framework/src/Illuminate/Routing/Route.php(176): Illuminate\\Routing\\Route->runController()
#12 /api/vendor/laravel/framework/src/Illuminate/Routing/Router.php(680): Illuminate\\Routing\\Route->run()
#13 /api/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#14 /api/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php(58): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(163): Illuminate\\Routing\\Middleware\\ThrottleRequests->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#16 /api/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /api/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /api/vendor/laravel/framework/src/Illuminate/Routing/Router.php(682): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#19 /api/vendor/laravel/framework/src/Illuminate/Routing/Router.php(657): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#20 /api/vendor/laravel/framework/src/Illuminate/Routing/Router.php(623): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#21 /api/vendor/laravel/framework/src/Illuminate/Routing/Router.php(612): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#22 /api/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(176): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#23 /api/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))


via Chebli Mohamed

Ajax call on change not working in laravel 5.8

web.php file

Route::group(['middleware'=>['auth','lfwuser']], function(){
    Route::get('/lfwuser_addEngagementData', 'LfwUser\LfwDashboardController@getEngagementData');

    Route::post('/lfwuser_SubDataEngagementData', 'LfwUser\LfwDashboardController@fetchSubData');
});

LfwDashboardController File.

public function getEngagementData(){
        if (Auth::check()) {
            $data = DB::table('table')
                            ->select('col')
                            ->distinct('col')
                            ->get();
            return view('lfwuser.lfwuser_addEngagementData')->with('data', $data);
        }
        else {
            return \view('auth.login');
        }

    }

    public function fetchSubData(Request $request){
        if (Auth::check()) {
            echo "Hello World";
        }
        else {
            return \view('auth.login');
        }

    }

Blade file

@extends('layouts.lfwuser') @section('title') LeapForWord | Content Management @endsection @section('content')
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <center>
                    <h4 class="card-title">Add Data</h4>
                </center>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                    </div>
                    <div class="col-md-6">
                        <form action="/lfwuser_addEngagementData" method="POST" enctype="multipart/form-data ">
                             


                            <div class="form-group">
                                <label for="dataType">Data Type</label>
                                <select class="form-control" name="dataType" id="dataType" required>
                                    <option value=" ">--- Select ---</option>
                                    @foreach($data as $datatype)
                                    <option value=""></option>
                            @endforeach
                            </select>
                            </div>

                            <div class="form-group">
                                <label for="subdataType">Sub Data Type</label>
                                <select class="form-control" name="subdataType" id="subdataType" required>
                                    <option value="">--- Select ---</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <input type="hidden" class="form-control" name="subDataId" id="subDataId" required>
                            </div>

                            <div class="form-group">
                                <label for="filellink">Link:</label>
                                <input type="text" class="form-control" name="filellink" id="filellink" required>
                            </div>

                            <div class="form-group">
                                <div class="row">
                                    <button type="submit" class="btn btn-outline-success text-center">Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="col-md-3"></div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection @section('scripts')
<script>
    $(document).ready(function() {
        $("#dataType").change(function() {
            let datatype = $("#dataType").val();
            let _token = $('input[name="_token"]').val();

            console.log("Data Type: " + datatype);

            if (dataType != '') {
                $.ajax({
                    url: "/lfwuser_SubDataEngagementData",
                    method: "POST",
                    dataType: "json",
                    data: {
                        datatype: datatype,
                        _token: _token
                    },
                    success: function(response) {
                        console.log("hi" + response);
                    }
                });
            } else {

            }

        });
    });
</script>
@endsection

Nothing gets in response and no error on the console. How should I resolve this issue? The form is shown when the user logged in into the system The blade file store inside the view/user folder. I guess the mistake in the URL part. URL is not calling properly, sometimes it shows error 419 for file, It is taking much time please let me know where I am doing wrong?



via Chebli Mohamed

Route redirection is not working in Laravel

After successfully login in my Laravel application, it takes me to dashbaord. After logout from the application it takes me to the login page again. But if I click back icon from the browser It will take me to dashboard again though I have log out.

routes

Route::get('/admin-login', 'userController@index');
Route::post('/admin-login', 'userController@admin_login');
Route::get('/admin-logout', 'userController@admin_logout');
Route::get('/dashboard', 'dashboardController@index');

dashboardController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class dashboardController extends Controller
{
    public function __construct()
    {
        if (!Auth::check()) {
            return redirect('/admin-login'); //This Redirection Doesn't Work
        }
    }

    public function index()
    {
        return view('admin.dashboard.dashboard');
    }
}

Where is the problem I can't find out. Please Anybody help ? Thanks in advance.



via Chebli Mohamed

Ajax not calling in Laravel 5.8

Web.php file

Route::group(['middleware'=>['auth','admin']], function(){
    Route::get('/admin_addEngagementData', 'Admin\DashboardController@getEngagementForm');
    Route::post('/admin_insertEngagementData', 'Admin\DashboardController@insertEngagementData');
});

admin_addEngagement.blade.php

@extends('layouts.admin') @section('title') LeapForWord | Content Management @endsection @section('content')
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header card-header-primary">
                <center>
                    <h4 class="card-title">Add DataTypes</h4>
                </center>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <form method="post" id="dynamic_form">
                        
                        <span id="result"></span>
                        <table class="table table-bordered table-striped" id="user_table">
                            <thead>
                                <tr>
                                    <th class="text-center">Data</th>
                                    <th class="text-center">Type Of Data</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="2" align="right">&nbsp;</td>
                                    <td>
                                        <input type="submit" name="save" id="save" class="btn btn-primary" value="Save" />
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection @section('scripts')
<script>
    $(document).ready(function() {

        var count = 1;

        dynamic_field(count);

        function dynamic_field(number) {
            html = '<tr>';
            html += '<td><input type="text" name="datatype[]" class="form-control" /></td>';
            html += '<td><input type="text" name="subdatatype[]" class="form-control" /></td>';
            if (number > 1) {
                html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
                $('tbody').append(html);
            } else {
                html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
                $('tbody').html(html);
            }
        }

        $(document).on('click', '#add', function() {
            count++;
            dynamic_field(count);
        });

        $(document).on('click', '.remove', function() {
            count--;
            $(this).closest("tr").remove();
        });

        $('#dynamic_form').on('submit', function(event) {
            event.preventDefault();
            $.ajax({
                url: '',
                method: 'post',
                data: $(this).serialize(),
                dataType: 'json',
                beforeSend: function() {
                    $('#save').attr('disabled', 'disabled');
                },
                success: function(data) {
                    if (data.error) {
                        var error_html = '';
                        for (var count = 0; count < data.error.length; count++) {
                            error_html += '<p>' + data.error[count] + '</p>';
                        }
                        $('#result').html('<div class="alert alert-danger">' + error_html + '</div>');
                    } else {
                        dynamic_field(1);
                        $('#result').html('<div class="alert alert-success">' + data.success + '</div>');
                    }
                    $('#save').attr('disabled', false);
                }
            })
        });

    });
</script>
@endsection

DashboardController.php

class DashboardController extends Controller
{
   public function getEngagementForm(){
        if(Auth::check()){
            return \view('admin.admin_addEngagementData');
        }
        else{
            return \view('auth.login');
        }
    }

    public function insertEngagementData(Request $request){
        if(Auth::check()){
            // \dd($request);
            $id = Auth::user()->id;

            if($request->ajax()){
                $rules = array(
                    'datatype.*'  => 'required',
                    'subdatatype.*'  => 'required'
                );

                $error = Validator::make($request->all(), $rules);
                if($error->fails()){
                    return response()->json([
                        'error'  => $error->errors()->all()
                    ]);
                }

                $datatype = $request->datatype;
                $subdatatype = $request->subdatatype;


                for($count = 0; $count < count($datatype); $count++){
                    $data = array(
                        'user_id' => $id,
                        'datatype' => $datatype[$count],
                        'subdatatype'  => $subdatatype[$count]
                    );
                    $insert_data[] = $data;
                }

                Lfw_engagement_datatype::insert($insert_data);
                return response()->json([
                    'success'  => 'Data Added successfully.'
                ]);
            }
        }
        else{
            return \view('auth.login');
        }

    }
}

I had kept my blade.php file inside view/admin/admin_addEngagement.blade.php file. but I am not getting any output and in console, i am getting error:- jquery.min.js:3049 POST-http://127.0.0.1:8000/admin_insertEngagementData 500 (Internal Server Error)

how can I resolve this issue?



via Chebli Mohamed

How I login with Hashed Password in laravel

I am trying to login and sending email and password from Database. when i pass email and password to login function i gives the 401 unauthorized error. Strange thing is when i send password as a string it works. See the code below

public function verification(Request $request)
     {
        $user = User::find($request->user_id);

        if(Carbon::now() > $user->codeCreatedAt  && $user->verification_code !== $request->code) {
            return response()->json(['success' => false]);
        }
        $user->verify = 1;
        $user->save();
        $request->request->add([
            'email' => $user->email,
            'password' => $user->password

        ]);
        return $this->login($request);
    }

public function login(Request $request)
    {

        $credentials = $request->only('email', 'password');

        if ($token = $this->guard()->attempt($credentials)) {

            return $this->respondWithToken($token);
        }
        return response()->json(['errors' => 'Unauthorized'], 401);
    }


via Chebli Mohamed

vendredi 1 mai 2020

laravel 5.2 pass variable in all controllers

can someone help please, i want to make my varaibles global in all controllers without every time create instance.. settings = new Setting(); settings has only one row.

class Controller extends BaseController

protected $settings;

    public function __construct() 
    {
        $this->settings = Setting::all();
        View::share('settings', $this->settings);
    }
}

and in another controller i use :

$this->settings->email;

but it does not work, please i search and see this method is not good, can someone please give me a good approach for this, laravel 5.2.

thanks so much..!!



via Chebli Mohamed