mercredi 2 juin 2021

What is the best practice to prevent hacking by uploading php files to public folder on Laravel?

My Laravel public folder was uploaded by many php files, and also with some Wordpress files. It happened same to another Opencart website. I think hacker using same method to do that. Could anyone can help to answer some of the following questions or giving the best practices?

  1. How hacker could upload php files to website? They upload with page that allow to upload file? Or they attack by guessing FTP username and password?
  2. How to prevent this attacking? We have to do file type upload validation? And also config server security like file and folder permission, etc?
  3. How attacker find our website? We didn't share to anywhere, just upload to a new server. Then a few months later it was attacked.


via Chebli Mohamed

laravel get list of users only email verified

When I try to get the list of users from User:all(), it shows me the users who also are not email verifed.

So to avoid the above situation, I am writing the following code.

$users = User::with('selfie')->whereNotNull('email_verified_at')->orderBy('created_at', 'desc')->get();

let me know if there is any other shorter way.



via Chebli Mohamed

Call to undefined method App\User::admin() error in Session in Laravel

I'm trying to put some session in my project and its working fine when Im logged out. But when Im logged in as an Admin Im getting Call to undefined method App\User::admin() errror.

this is my routes

Route::resource('/create','PagesController@showCreate')->middleware(IsAdmin::class);
Route::get('/users','UserController@index')->middleware(IsAdmin::class);
Route::get('/verify','UserController@userVerify')->middleware(IsAdmin::class);

this is my User model

<?php

namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *  protected $table = 'users';
    *public $primaryKey ='id';
     * @var array
     */
  
    protected $fillable = [
        'name', 'email', 'password','userType',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'admin' => 'boolean',
    ];

    public function posts(){
        return $this->hasMany('App\Post');
    }

    public function isAdmin()
    {
        return $this->admin;
    }
   
}

and this is my IsAdmin class

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        {
            if ( Auth::check() && Auth::user()->admin() )
            {
                return $next($request);
            }
    
            return redirect('home');
        }
    }
}

and everytime I try to redirect to other routes I get the same error except for the dashboard



via Chebli Mohamed

Laravel not accepting POST Method

I been trying to add a route to my button, whereby I have declared the method to POST, but when I click on the button, an error prompt saying it is using GET method.

enter image description here

Here is my view

<form method="post" action="">
..
..
<table class="table m-l-sm">
                            <tbody>
                                @foreach($order->packages as $item)
                                
                                <tr>
                                    <td>
                                        <p class="m-b-xxs font-bold"></p>
                                        @foreach($item->products as $product)
                                        <p class="m-b-xxs"> X </p>
                                        @endforeach

                                        <div class="form-group row m-t-sm">
                                            <div class="col-md-4">
                                                <div class="input-group d-inline">
                                                    <span class="input-group-addon font-bold">RM </span>
                                                    <span class="input-group-addon">X</span>
                                                    <input id="" type="number" class="form-control" name="package[][qty]" value="" min="0" placeholder="Qty" @cannot('edit-order-package', $order) disabled @endcannot>                                                    
                                                </div>
                                            </div>@error('package.'.$item->id)
                                            <div class="col-md-12 alert alert-danger"></div>
                                            @enderror
                                                <div class="col-md-8 d-flex justify-content-end">
                                                    <a class="btn btn-sm btn-danger btn-danger" href="" >Delete</a>  <--- where i am calling my route
                                                </div>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
</form>

Here is my Route

  Route::post('/{order}/edit/delete', 'App\OrderController@handleDeleteItemOrder')->name('admin.order.item.edit.delete');

Controller

public function handleDeleteItemOrder(Order $order){
            log:info($order);
        }


via Chebli Mohamed

mardi 1 juin 2021

Get date with relation using two columns in Laravel

I have a table named as users:

id |  name |  email  

and attachment table

id |  file_name   |  user_id  |  type 
1    filename1.jpg      56         7
2    filename2.jpg      56         7
3    filename3.jpg      57         7
4    filename4.jpg      56         6

i'm fetching data from users table like:

 $data = Users::find($id);

but i want to get attachment table data also with users table. But i want to match user_id and type also, where user_id matches and type = 7 only those rows should return.



via Chebli Mohamed

set the default value to Input type Date - Laravel

I am working on a project with laravel, i need set default value to input type date.

I use the variable: value=" "

result: problem

the problem is that the date is not displayed

in the database is the date

database

<input type="date"  class="form-control flatpickr flatpickr-input active mb-4" id="entrega" name="entrega"
       value=" " 
       min="2018-01-01" max="2025-12-31">

help pls



via Chebli Mohamed

Laravel 5 Property [userType] does not exist on this collection instance

I keep getting property [userType] does not exist error when Im trying to make log in condition here is my Controller code below. I also tried to make Auth controller but I just keep getting the same error from this.

<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function redirectTo()
{
    $user = User:all();
    if($user->userType == 'admin')
    {
        return 'dashboard';
    }
    else
    {
        return 'verify first';
    }
}
}

and here is my model code

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *  protected $table = 'users';
    *public $primaryKey ='id';
     * @var array
     */
  
    protected $fillable = [
        'name', 'email', 'password','userType',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function posts(){
        return $this->hasMany('App\Post');
    }

   
}

anyway on how can I fix this? Please show me the correct way to create a redirect in login because I just want to create a login with admin, user, and guest mode.



via Chebli Mohamed