Connect with us

The 3 least-secure programming languages

kizinho

Published

on

Follow
NEWS: The 3 least-secure programming languages [New  Developer] » Naijacrawl
Photo: Naijacrawl
site

WhiteSource has released a report outlining which popular programming languages contain the most security vulnerabilities.

 

It looked through its database of known open source security flaws and vulnerabilities over the past decade for the report.

 

The “vulnerability” results were as follows:

 

C – 47%

 

PHP – 17%

 

Java – 11%

 

JavaScript – 10%

 

Python – 5%

 

C++ – 5%

 

Ruby – 4%

 

WhiteSource said it has found that the percentage of critical vulnerabilities is declining for five of the seven languages considered – only JavaScript and PHP do not follow this trend.

 

WhiteSource added that these findings do not necessarily reflect how vulnerable each language is.

 

For example, as C has been around for longer than the other languages and has the highest volume of written code, it is understandable that more C vulnerabilities have been discovered.

 

“My own  conclusion from the research is that it is not about the language itself that makes it any more or less secure, but how you use it,” said WhiteSource.

site


kizinho

I am a software developer, like meeting people and love blogging, that's why I developed naijacrawl because that's what I love doing.

Continue Reading
Click To Comment

BE First To Comment


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    How to solve This page isn’t working HTTP ERROR 500 in Laravel

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: How to solve This page isn’t working HTTP ERROR 500 in Laravel [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl

    In case you ran into this problem This page isn’t working www.example.com is currently unable to handle this request HTTP ERROR here is the cause and how to fix it. First, it must not be an error from your code, it is an error from querying large data from your database. So request ran out of memory, to fix it follow this step.

    In your Laravel root project folder locate this file

    vendor/laravel/framework/src/Illuminate/
    Database/Connection.php.
    

    Insert this line of code after line 324 

    ini_set('memory_limit', '-1'); 
    

    or follow the code snippet or image below:


     public function select($query, $bindings = [], $useReadPdo = true)    {        return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {            if ($this->pretending()) {                return [];            }            // For select statements, we'll simply execute the query and return an array            // of the database result set. Each element in the array will be a single            // row from the database table, and will either be an array or objects.            ini_set('memory_limit', '-1');         
    
       $statement = $this->prepared($this->getPdoForSelect($useReadPdo)                              ->prepare($query));            $this->bindValues($statement, $this->prepareBindings($bindings));            $statement->execute();            return $statement->fetchAll();        });    }
    


    Continue Reading

    How to convert image from png, jpg to webp image in Laravel

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: How to convert image from png, jpg to webp image in Laravel [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl

    Hi, folks will show how you can convert any image to webp image.

    Why Webp

    WebP is making headway in the image format space this year. The image format — which is developed by Google — uses both lossy and lossless compression by utilizing technology that Google purchased from On2 Technologies.


    WebP has been around a while now, actually, and it first made headlines in a 2010 Google press conference. But, like any new technology, it had some initial rough patches. Today, WebP is on version 1.0.0, so we thought it would be a great time to talk about what makes WebP so powerful, and why it’s a fantastic option for web designers and developers.

    a

    Before I proceed to describe what WebP actually is, let us focus on why it matters—it’s not only about making images smaller, but it’s also about why and how the images need to be made smaller.


    You may have heard about design mistakes killing your SEO and conversion rates. While there are some aspects that CSS or JavaScript are responsible for, like blocking rendering, the images nowadays are a huge part of any website’s weight. Therefore, users on slower connections will have trouble interacting with your website (unless it’s an AMP).

    Just recently, It’s an interesting area of expertise, where you take care of lots of small things to deliver one big thing—a superfast, superlight website that reads on any device and looks amazing at the same time.


    Chances are, you’ve seen WebP images before. If you open Naijacrawl in Google Chrome, all of those thumbnails are going to be WebP thumbnails. If you were to open the Facebook app on your android phone, all of the images that you see would be WebP. It’s definitely being utilized by various companies around the world to increase performance.


    So let's see how you can do the same using laravel to convert your images to webp image.


    Note this works in all laravel versions


    I assumed you have a project already or you can create one by using this command


    composer create-project 
    laravel/laravel webimage
     --prefer-dist


    You must have installed a composer before you can run the command.


    We need a controller so let's create one

    php artisan make:controller 
    ImageWebpController
    


    Inside the controller, we will write a code that will process our image and convert it to webp inside a folder


    What it Requires

    file extension

    file name

    folder

    
    namespace
     App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Str;
    class ImageWebpController 
    extends Controller {
    public function webpImage
    (Request $request) 
    {
    if ($request->hasFile('file')) {
    $file = $request->file('file');
    $extension = $file->getClientOriginalExtension(); 
    $rand = '-' . strtolower(Str::random(10));  
    $name = $rand . '.' . $extension;   
    return $this->processImage($file, $name);  
     }  
      }    
    private function processImage
    ($file, $name) 
    {  
    $file->move(public_path('/test/image'), 
    $name);  
          //convert to webp         
    $webp = public_path() . '/test/image/' .
     $name;      
      $im = imagecreatefromstring
    (file_get_contents($webp)); 
     $new_webp =
     preg_replace('"\.(jpg|jpeg|png|webp)$"',
     '.webp', $webp);  
    imagewebp($im, $new_webp, 50);  
     return'message'
     => 'image successfully 
    converted to webp.
     check your 
    folder to see it'
    ];   
     }
    }
    ?>

    from what i did, i check if the request is a file before proceeding , have to get extension of the file and use it make a slug name for the image, because i don't want it to carry original name.

    $extension = $file->
    getClientOriginalExtension();
    

    I have to use str function to form a characters for the name of the image

     $rand = '-' . 
    strtolower(Str::random(10));
    
    //final name
    $name = $rand . '.' . $extension;
    

    I needed another private function because i want to separate my code for easy to read using processImage function.

    
     private function processImage
    ($file, $name) {
    $file->move(public_path('/test/image'),
     $name); 
           //convert to webp         
    $webp = public_path() . '/test/image/' .
     $name;
     $im = imagecreatefromstring
    (file_get_contents($webp));  
    $new_webp =
     preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',
     $webp);
    imagewebp($im, $new_webp, 50);        
    return'message' 
    => 'image successfully 
    converted to webp. 
    check your folder 
    to see it' ];  
      }
    ?>

    After i called it to the main function which

    is webpImage function .

    Inside processImage function ,

    the file is moved to my public folder called test/image before converting it to webp image

    //get image that
     we want to convert 
    $webp = public_path() .
     '/test/image/' . $name;
    //create the image        
    $im = imagecreatefromstring
    (file_get_contents($webp));
    //accept image extensions of jpg,png,webp 
    $im = imagecreatefromstring
    (file_get_contents($webp));
     $new_webp = 
    preg_replace('"\.(jpg|jpeg|png|webp)$"', 
    '.webp', $webp);
    //make the webp image and set the quality to 50 
    //the more quality the more it becomes broght and increase mb
    // you can set to 100 which means no quality will be reduced 
     imagewebp($im, $new_webp,50);
    ?>

    From my code i didn't add validation rule which you can do it if you needed it , just to make it allow only files and extension type


    Find this article helpful kindly share it.

    Continue Reading

    How to use the same Guard name in WEB and API Using Laravel Spatie Permission

    kizinho

    Published

    on

    NEWS: How to use the same Guard name in WEB and API Using Laravel Spatie Permission [New  Developer] » Naijacrawl
    Photo: Naijacrawl

    Hi, Folks will show how to use the same guard name on your Laravel application using Laravel Spatie Permission without creating multiple guards for your web and API when building your real projects.


    Spatie Permission comes with guard name it is used to authenticate user role and permission in your laravel app. But what if you have Role and Permission with Guard Name Web, it means only web can use this permission or role, when you want to use it for API to Authorize user Permission or Role, this would not work and you will always get user don't have permission to access this page.


    In this article, you can now use a single Guard name for both Web and API.


    Guard name depends on your application usage, guard name can be admin,user, but i prefer to use guard name as web or API, so that i don't have to create each role and permission for different guard name, and it saves time to use single guard name in all your applications. So let's start


    Go to this file vendor/spatie/laravel-permission/src/Models/Role and add protected $guard_name = 'web' .

    You can change the $guard_name to whatever you want to use as your guard name.


    See Full Code

    namespace Spatie\Permission\Models;
    
    
    use Spatie\Permission\Guard;
    use Illuminate\Database\Eloquent\Model;
    use Spatie\Permission\Traits\HasPermissions;
    use Spatie\Permission\Exceptions\RoleDoesNotExist;
    use Spatie\Permission\Exceptions\GuardDoesNotMatch;
    use Spatie\Permission\Exceptions\RoleAlreadyExists;
    use Spatie\Permission\Contracts\Role as RoleContract;
    use Spatie\Permission\Traits\RefreshesPermissionCache;
    use Illuminate\Database\Eloquent\Relations\MorphToMany;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    
    
    class Role extends Model implements RoleContract {
    
    
        use HasPermissions;
        use RefreshesPermissionCache;
    
    
        protected $guarded = ['id'];
        protected $guard_name = 'web';
    
    
        public function __construct(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
    
    
            parent::__construct($attributes);
    
    
            $this->setTable(config('permission.table_names.roles'));
        }
    
    
        public static function create(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
    
    
            if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) {
                throw RoleAlreadyExists::create($attributes['name'], $attributes['guard_name']);
            }
    
    
            if (isNotLumen() && app()::VERSION < '5.4') {
                return parent::create($attributes);
            }
    
    
            return static::query()->create($attributes);
        }
    
    
        /**
         * A role may be given various permissions.
         */
        public function permissions(): BelongsToMany {
            return $this->belongsToMany(
                            config('permission.models.permission'), config('permission.table_names.role_has_permissions'), 'role_id', 'permission_id'
            );
        }
    
    
        /**
         * A role belongs to some users of the model associated with its guard.
         */
        public function users(): MorphToMany {
            return $this->morphedByMany(
                            getModelForGuard($this->attributes['guard_name']), 'model', config('permission.table_names.model_has_roles'), 'role_id', config('permission.column_names.model_morph_key')
            );
        }
    
    
        /**
         * Find a role by its name and guard name.
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
         *
         * @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
         */
        public static function findByName(string $name, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('name', $name)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                throw RoleDoesNotExist::named($name);
            }
    
    
            return $role;
        }
    
    
        public static function findById(int $id, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('id', $id)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                throw RoleDoesNotExist::withId($id);
            }
    
    
            return $role;
        }
    
    
        /**
         * Find or create role by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Role
         */
        public static function findOrCreate(string $name, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('name', $name)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
            }
    
    
            return $role;
        }
    
    
        /**
         * Determine if the user may perform the given permission.
         *
         * @param string|Permission $permission
         *
         * @return bool
         *
         * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
         */
        public function hasPermissionTo($permission): bool {
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
            }
    
    
            if (!$this->getGuardNames()->contains($permission->guard_name)) {
                throw GuardDoesNotMatch::create($permission->guard_name, $this->getGuardNames());
            }
    
    
            return $this->permissions->contains('id', $permission->id);
        }
    
    
    }
    


    Go to this file again vendor/spatie/laravel-permission/src/Models/Permission and add protected $guard_name = 'web' .

    Full Code


    namespace Spatie\Permission\Models;
    
    
    use Spatie\Permission\Guard;
    use Illuminate\Support\Collection;
    use Spatie\Permission\Traits\HasRoles;
    use Illuminate\Database\Eloquent\Model;
    use Spatie\Permission\PermissionRegistrar;
    use Spatie\Permission\Traits\RefreshesPermissionCache;
    use Illuminate\Database\Eloquent\Relations\MorphToMany;
    use Spatie\Permission\Exceptions\PermissionDoesNotExist;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    use Spatie\Permission\Exceptions\PermissionAlreadyExists;
    use Spatie\Permission\Contracts\Permission as PermissionContract;
    
    
    class Permission extends Model implements PermissionContract {
    
    
        use HasRoles;
        use RefreshesPermissionCache;
    
    
        protected $guarded = ['id'];
        protected $guard_name = 'web';
    
    
        public function __construct(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
    
    
            parent::__construct($attributes);
    
    
            $this->setTable(config('permission.table_names.permissions'));
        }
    
    
        public static function create(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
    
    
            $permission = static::getPermissions(['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']])->first();
    
    
            if ($permission) {
                throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
            }
    
    
            if (isNotLumen() && app()::VERSION < '5.4') {
                return parent::create($attributes);
            }
    
    
            return static::query()->create($attributes);
        }
    
    
        /**
         * A permission can be applied to roles.
         */
        public function roles(): BelongsToMany {
            return $this->belongsToMany(
                            config('permission.models.role'), config('permission.table_names.role_has_permissions'), 'permission_id', 'role_id'
            );
        }
    
    
        /**
         * A permission belongs to some users of the model associated with its guard.
         */
        public function users(): MorphToMany {
            return $this->morphedByMany(
                            getModelForGuard($this->attributes['guard_name']), 'model', config('permission.table_names.model_has_permissions'), 'permission_id', config('permission.column_names.model_morph_key')
            );
        }
    
    
        /**
         * Find a permission by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findByName(string $name, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
            if (!$permission) {
                throw PermissionDoesNotExist::create($name, $guardName);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Find a permission by its id (and optionally guardName).
         *
         * @param int $id
         * @param string|null $guardName
         *
         * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findById(int $id, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['id' => $id, 'guard_name' => $guardName])->first();
    
    
            if (!$permission) {
                throw PermissionDoesNotExist::withId($id, $guardName);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Find or create permission by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findOrCreate(string $name, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
    
    
            if (!$permission) {
                return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Get the current cached permissions.
         */
        protected static function getPermissions(array $params = []): Collection {
            return app(PermissionRegistrar::class)
                            ->setPermissionClass(static::class)
                            ->getPermissions($params);
        }
    
    
    }
    


    Next go to your Model where you use HasRoles and Paste this code , eg I used HasRoles in my User Model , will use the code on my user

    Copy this code


     public function hasPermissionTo($permission, $guardName = 'web'): bool {
    
    
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
        }
    
    
        protected function getDefaultGuardName(): string {
            return 'web';
        }
    


    Now all web and API can use the same guard name to check user role and permission

    See complete Code on my user model


    namespace App\Models\User;
    
    
    use Laravel\Passport\HasApiTokens;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Spatie\Permission\Traits\HasRoles;
    
    
    class User extends Authenticatable implements MustVerifyEmail {
    
    
        use HasApiTokens,
            SoftDeletes,
            HasRoles,
           ;
    
    
        public function hasPermissionTo($permission, $guardName = 'web'): bool {
    
    
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
        }
    
    
        protected function getDefaultGuardName(): string {
            return 'web';
        }
    
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'id', 'slug', 'username', 'email', 'email_verified_at', 'created_at', 'password',
        ];
    
    
        /**
         * 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',
        ];
    
    
    
    }
    


    If this article help you kindly share , thanks for reading

    Continue Reading

    Latest