Category Archives: RSS Feed

New Codingmarks Calendar Week 7 2018


layout: post
title: New codingmarks added in the 7th week of 2018
description: “New codingmarks added in the 7th week of 2018. Keywords: cloud, encryption, firewall, phising, security, tools and user-experience”
author: ama
permalink: /ama/new-codingmarks-week-7-2018
published: true
categories: [codingmarks]
tags: [codingmarks]

New codingmarks added in the 7th week of 2018. Hot topics include:

Continue reading New Codingmarks Calendar Week 7 2018

Understanding and Working with Files in Laravel

By Samuel Oloruntoba

File uploads is one the most commonly used features on the web. From uploading avatars to family pictures to sending documents via email, we can’t do without files on the web.

In today’s article will cover all the ways to handle files in Laravel. If you are new to Laravel, browse the courses or navigate to the tutorials section. After reading the article, If we left something out please let us know in the comments and we’ll update the post accordingly.

Handling of files is another thing Laravel has simplified in its ecosystem. Before we get started, we’ll need a few things. First, a Laravel project. There are a few ways to create a new Laravel project, but let’s stick to composer for now.

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

Where files is the name of our project. After installing the app, we’ll need a few packages installed, so, let’s get them out of the way. You should note that these packages are only necessary if you intend to save images to Amazon’s s3 or manipulate images like cropping, filters etc.

composer require league/flysystem-aws-s3-v3:~1.0 intervention/image:~2.4

After installing the dependencies, the final one is Mailtrap. Mailtrap is a fake SMTP server for development teams to test, view and share emails sent from the development and staging environments without spamming real customers. So head over to Mailtrap and create a new inbox for testing.

Then, in welcome.blade.php update the head tag to:

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File uploads</title>
<style>
  * {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
        "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji",
        "Segoe UI Emoji", "Segoe UI Symbol";
  }
</style>

Modify the body contents to:

<form action="/process" enctype="multipart/form-data" method="POST">
    <p>
        <label for="photo">
            <input type="file" name="photo" id="photo">
        </label>
    </p>
    <button>Upload</button>
    {{ csrf_field() }}
</form>

For the file upload form, the enctype="multipart/form-data" and method="POST" are extremely important as the browser will know how to properly format the request. {{ csrf_field() }} is Laravel specific and will generate a hidden input field with a token that Laravel can use to verify the form submission is legit.

If the CSRF token does not exist on the page, Laravel will show “The page has expired due to inactivity” page.

Now that we have our dependencies out of the way, let’s get started.

Understanding How Laravel Handles Files

Development as we know it in 2018 is growing fast, and in most cases there are many solutions to one problem. Take file hosting for example, now we have so many options to store files, the sheer number of solutions ranging from self hosted to FTP to cloud storage to GFS and many others.

Since Laravel is framework that encourages flexibility, it has a native way to handle the many file structures. Be it local, Amazon’s s3, Google’s Cloud, Laravel has you covered.

Laravel’s solution to this problem is to call them disks. Makes sense, any file storage system you can think of can be labeled as a disk in Laravel. To this regard, Laravel comes with native support for some providers (disks). We have: local, public, s3, rackspace, FTP etc. All this is possible because of Flysystem.

If you open config/filesystems.php you’ll see the available disks and their respected configuration.

File Uploads in Laravel

From the introduction section above, we have a form with a file input ready to be processed. We can see that the form is pointed to /process. In routes/web.php, we define a new POST /process route.

use IlluminateHttpRequest;

Route::post('process', function (Request $request) {
    $path = $request->file('photo')->store('photos');

    dd($path);
});

What the above code does is grab the photo field from the request and save it to the photos folder. dd() is a Laravel function that kills the running script and dumps the argument to the page. For me, the file was saved to “photos/3hcX8yrOs2NYhpadt4Eacq4TFtpVYUCw6VTRJhfn.png”. To find this file on the file system, navigate to storage/app and you’ll find the uploaded file.

If you don’t like the default naming pattern provided by Laravel, you can provide yours using the storeAs method.

Route::post('process', function (Request $request) {
    // cache the file
    $file = $request->file('photo');

    // generate a new filename. getClientOriginalExtension() for the file extension
    $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension();

    // save to storage/app/photos as the new $filename
    $path = $file->storeAs('photos', $filename);

    dd($path);
});

After running the above code, I got “photos/profile-photo-1517311378.png”.

Difference Between Local and Public Disks

In config/filesystems.php you can see the disks local and public defined. By default, Laravel uses the local disk configuration. The major difference between local and public disk is that local is private and cannot be accessed from the browser while public can be accessed from the browser.

Since the public disk is in storage/app/public and Laravel’s server root is in public you need to link storage/app/public to Laravel’s public folder. We can do that with our trusty artisan by running php artisan storage:link.

Uploading Multiple Files

Since Laravel doesn’t provide a function to upload multiple files, we need to do that ourselves. It’s not much different from what we’ve been doing so far, we just need a loop.

First, let’s update our file upload input to accept multiple files.

<input type="file" name="photos[]" id="photo" multiple>

When we try to process this $request->file(‘photos’), it’s now an array of UploadedFile instances so we need to loop through the array and save each file.

Route::post('process', function (Request $request) {
    $photos = $request->file('photos');
    $paths  = [];

    foreach ($photos as $photo) {
        $extension = $photo->getClientOriginalExtension();
        $filename  = 'profile-photo-' . time() . '.' . $extension;
        $paths[]   = $photo->storeAs('photos', $filename);
    }

    dd($paths);
});

After running this, I got the following array, since I uploaded a GIF and a PNG:

array:2 [▼
  0 => "photos/profile-photo-1517315875.gif"
  1 => "photos/profile-photo-1517315875.png"
]

Validating File Uploads

Validation for file uploads is extremely important. Apart from preventing users from uploading the wrong file types, it’s also for security. Let me give an example regarding security. There’s a PHP configuration option cgi.fix_pathinfo=1. What this does is when it encounters a file like https://site.com/images/evil.jpg/nonexistent.php, PHP will assume nonexistent.php is a PHP file and it will try to run it. When it discovers that nonexistent.php doesn’t exists, PHP will be like “I need to fix this ASAP” and try to execute evil.jpg (a PHP file disguised as a JPEG). Because evil.jpg wasn’t validated when it was uploaded, a hacker now has a script they can freely run live on your server… Not… good.

To validate files in Laravel, there are so many ways, but let’s stick to controller validation.

Route::post('process', function (Request $request) {
    // validate the uploaded file
    $validation = $request->validate([
        'photo' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048'
        // for multiple file uploads
        // 'photo.*' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048'
    ]);
    $file      = $validation['photo']; // get the validated file
    $extension = $file->getClientOriginalExtension();
    $filename  = 'profile-photo-' . time() . '.' . $extension;
    $path      = $file->storeAs('photos', $filename);

    dd($path);
});

For the above snippet, we told Laravel to make sure the field with a name of photo is required, a successfully uploaded file, it’s an image, it has one of the defined mime types, and it’s a max of 2048 kilobytes ~~ 2 megabytes.

Now, when a malicious user uploads a disguised file, the file will fail validation and if for some weird reason you leave cgi.fix_pathinfo on, this is not a means by which you can get PWNED!!!

If you head over to Laravel’s validation page you’ll see a whole bunch of validation rules.

Moving Files to the Cloud

Okay, your site is now an adult, it has many visitors and you decide it’s time to move to the cloud. Or maybe from the beginning, you decided your files will live on separate server. The good news is Laravel comes with support for many cloud providers, but, for this tutorial, let’s stick with Amazon.

Earlier we installed league/flysystem-aws-s3-v3 through composer. Laravel will automatically look for it if you choose to use Amazon S3 or throw an exception.

To upload files to the cloud, just use:

$request->file('photo')->store('photos', 's3');

For multiple file uploads:

foreach ($photos as $photo) {
    $extension = $photo->getClientOriginalExtension();
    $filename  = 'profile-photo-' . time() . '.' . $extension;
    $paths[]   = $photo->storeAs('photos', $filename, 's3');
}

Users may have already uploaded files before you decide to switch to a cloud provider, you can check the upcoming sections for what to do when files already exist.

Note: you’ll have to configure your Amazon s3 credentials in config/filesystems.php**.**

Sending Files as Email Attachments

Before we do this, let’s quickly configure our mail environment. In .env file you will see this section

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

We need a username and password which we can get at Mailtrap.io. Mailtrap is really good for testing emails during development as you don’t have to crowd your email with spam. You can also share inboxes with team members or create separate inboxes.

First, create an account and login:

  1. Create a new inbox
  2. Click to open inbox
  3. Copy username and password under SMTP section

After copying credentials, we can modify .env to:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=8a1d546090493b
MAIL_PASSWORD=328dd2af5aefc3
MAIL_ENCRYPTION=null

Don’t bother using mine, I deleted it.

Create your mailable

php artisan make:mail FileDownloaded

Then, edit its build method and change it to:

public function build()
{
    return $this->from('files@mailtrap.io')
        ->view('emails.files_downloaded')
        ->attach(storage_path('app/file.txt'), [
            'as' => 'secret.txt'
        ]);
}

As you can see from the method above, we pass the absolute file path to the attach() method and pass an optional array where we can change the name of the attachment or even add custom headers. Next we need to create our email view.

Create a new view file in resources/views/emails/files_downloaded.blade.php and place the content below.

<h1>Only you can stop forest fires</h1>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Labore at reiciendis consequatur, ea culpa molestiae ad minima est quibusdam ducimus laboriosam dolorem, quasi sequi! Atque dolore ullam nisi accusantium. Tenetur!</p>

Now, in routes/web.php we can create a new route and trigger a mail when we visit it.

use AppMailFileDownloaded;
Route::get('mail', function () {
    $email = 'bruce.wayne@batcave.io';

    Mail::to($email)->send(new FileDownloaded);

    dd('done');
});

If you head over to Mailtrap, you should see this.

Storage Facade for When Files Already Exist

In an application, it’s not every time we process files through uploads. Sometimes, we decide to defer cloud file uploads till a certain user action is complete. Other times we have some files on disk before switching to a cloud provider. For times like this, Laravel provides a convenient Storage facade. For those who don’t know, facades in Laravel are class aliases. So instead of doing something like SymfonyFileWhateverLongNamespaceUploadedFile, we can do Storage instead.

Choosing a disk to upload file. If no disk is specified, Laravel looks in config/filesystems.php and use the default disk.

Storage::disk('local')->exists('file.txt');

use default cloud provider

// Storage::disk('cloud')->exists('file.txt'); will not work so do:
Storage::cloud()->exists('file.txt');

Create a new file with contents

Storage::put('file.txt', 'Contents');

Prepend to file

Storage::prepend('file.txt', 'Prepended Text');

Append to file

Storage::append('file.txt', 'Prepended Text');

Get file contents

Storage::get('file.txt')

Check if file exists

Storage::exists('file.txt')

Force file download

Storage::download('file.txt', $name, $headers); // $name and $headers are optional

Generate publicly accessible URL

Storage::url('file.txt');

Generate a temporary public URL (i.e files that won’t exists after a set time). This will only work for cloud providers as Laravel doesn’t yet know how to handle generation of temporary URLs for local disk.

Storage::temporaryUrl('file.txt', now()->addMinutes(10));

Get file size

Storage::size('file.txt');

Last modified date

Storage::lastModified('file.txt')

Copy files

Storage::copy('file.txt', 'shared/file.txt');

Move files

Storage::move('file.txt', 'secret/file.txt');

Delete files

Storage::delete('file.txt');
// to delete multiple files
Storage::delete(['file1.txt', 'file2.txt']);

Manipulating files

Resizing images, adding filters etc. This is where Laravel needs external help. Adding this feature natively to Laravel will only bloat the application since not installs need it. We need a package called intervention/image. We already installed this package, but for reference.

composer require intervention/image

Since Laravel can automatically detect packages, we don’t need to register anything. If you are using a version of Laravel lesser than 5.5 read this.

To resize an image

$image = Image::make(storage_path('app/public/profile.jpg'))->resize(300, 200);

Even Laravel’s packages are fluent.

You can head over to their website and see all the fancy effects and filters you can add to your image.

Don’t forget directories

Laravel also provides handy helpers to work with directories. They are all based on PHP iterators so they’ll provide the utmost performance.

To get all files:

Storage::files

To get all files in a directory including files in sub-folders

Storage::allFiles($directory_name);

To get all directories within a directory

Storage::directories($directory_name);

To get all directories within a directory including files in sub-directories

Storage::allDirectories($directory_name);

Make a directory

Storage::makeDirectory($directory_name);

Delete a directory

Storage::deleteDirectory($directory_name);

Conclusion

If we left anything out, please let us know down in the comments. Also, checkout Mailtrap, they are really good and they will help you sail through the development phase with regards to debugging emails.

Source:: scotch.io

Build a Lightsaber with CSS and a Checkbox (Solution to Code Challenge #3)

By Chris Sevilleja

Last week, we started Code Challenge #3. The goal was to build these CSS Lightsabers:

Let’s take a look at the solution and build these with pure CSS. After we’re all done, we’ll add in some JavaScript to add the lightsaber sounds for when we click the lightsaber.

Video!

For those that like videos, we’re starting to put our more video content. Check out our YouTube channel

The HTML

We’ll start with the HTML for just one of the lightsabers. This will be fairly simple and will use some [BEM Classes]().

<div class="lightsaber">

  <label>Yoda</label>
  <input type="checkbox" checked>

</div>

That will be the base for our lightsaber. We also want to make sure that we can check/uncheck the checkbox when we click the label. To do this, HTML let’s us add a for attribute to the label and an id to the checkbox:

<div class="lightsaber">

  <label for="yoda">Yoda</label>
  <input id="yoda" type="checkbox" checked>

</div>

Now when we click on the label, this will check and uncheck the checkbox.

The Technique

The technique we’ll use here is a simple one. This is the technique used when you see all the styled out radio and checkboxes across the web. We’re going to style the label as our lightsaber and we’ll hide the checkbox.

Hide the checkbox. Use the label to toggle the checkbox.

Since we are able to use the label to toggle our checkbox, we don’t actually need the checkbox itself. Checkboxes are harder to style out anyway since they come with their own set of base styles per browser.

Adding a Container for the Saber

We’ll style the label as the hilt of our lightsaber and we’ll add another div to house the actual plasma/colored part.

<div class="lightsaber">

  <label for="yoda">Yoda</label>
  <input id="yoda" type="checkbox" checked>
  <div class="plasma"></div>

</div>

We’ll also add a class to this lightsaber so that we know its the Yoda version:

<div class="lightsaber lightsaber--yoda">

  <label for="yoda">Yoda</label>
  <input id="yoda" type="checkbox" checked>
  <div class="plasma"></div>

</div>

IMAGE HERE

The BEM style of classes let us know with the double dashes that this is a modifier to the main .lightsaber class. Our lightsaber looks nothing like a lightsaber just yet. The next bit of magic will happen in the CSS.

The CSS

Now that our HTML is ready, let’s move on to the CSS part. We’ll set some base styles for the hilt/label first:

/* make sure that all things are positioned relative to the parent lightsaber */
.lightsaber   {
  position: relative;
}

.lightsaber label {
  position: absolute;
  width: 15px;
  height: 50px;
  background: #DDD;
}

This next part is optional but adds that extra bit of depth to our lightsaber hilt. We’ll use a CSS gradient for our hilt:

.lightsaber label {
  position: absolute;
  width: 15px;
  height: 50px;
  background: #DDD;
  /* gradient goes here */

}

Hiding the Checkbox

We don’t need to the checkbox to be visually available. We’ll hide it using the opacity:

.lightsaber input[type="checkbox"] {
  opacity: 0;
}

Styling the Plasma

We have our .plasma div that we need to style next. This is the piece that we will show and hide when the checkbox is toggled. This will be the green glowing part for our Yoda saber. Since we already have our HTML checkbox set to the checked state, we’ll style it as if it was on already.

.lightsaber .plasma   {
  transition: height 0.3s;
  position: absolute;
  width: 10px;
  height: 0;
  filter: blur(1px); /* neat css trick to get that glow */
}

Notice that we have added a transition to the height. This is what will get transitioned from 0 height to full height. That’s how we get the lightsaber opening and closing effect.

The Yoda Styling

We want this saber to be for Yoda and we have a class specifically for that purpose. We’ll use that to style the green saber.

.lightsaber--yoda .plasma {
    background: rgb(135, 220, 90);
    background: linear-gradient(
    to right, 
    rgb(135, 220, 90) 0%, 
    rgb(254, 254, 254) 30%, 
    rgb(254, 254, 254) 50%, 
    rgb(254, 254, 254) 70%, 
    rgb(135, 220, 90) 100%
  );
}

.lightsaber--vader .plasma {
    background: rgb(229, 17, 21);
    background: linear-gradient(
    to right, 
    rgba(229, 17, 21, 1) 0%, 
    rgba(254, 254, 254, 1) 30%, 
    rgba(254, 254, 254, 1) 47%, 
    rgba(254, 254, 254, 1) 71%, 
    rgba(229, 17, 21, 1) 100%
  );
}

.lightsaber--windu .plasma {
    background: rgb(202, 116, 221);
    background: linear-gradient(
    to right, 
    rgba(202,116,221,1) 0%,
    rgba(254,254,254,1) 30%,
    rgba(254,254,254,1) 47%,
    rgba(254,254,254,1) 71%,
    rgba(202,116,221,1) 100%
  );
}

I’ve also added the styles for both vader and windu in there.

Toggling the Checkbox On or Off

Based on the state of the checkbox, we’ll set the height of the plasma. This is how we can set height from 0px to 50px of the .plasma:

.lightsaber input[type="checkbox"]:checked ~ .plasma {
  height: 55px;
}

We will check if the checkbox is checked using the [checked psuedo class]() and then set the sibling .plasma to full height!

Bonus: Adding Sound on Click

As a bonus, we can bring in some JavaScript to play a sound whenever this saber is opened/closed. The gist of what we will do is:

  • create an element
  • set the src of that to our lightsaber sound file: FILE HERE
  • play the audio file
// grab the checkbox
const lightsaber = document.querySelector('.lightsaber input[type="checkbox"]');
lightsaber.addEventListener('change', playWhoosh);

function playWhoosh(e) {
  // first check to see if this checkbox is on or off
  const isOn = e.target.checked;
  if (isOn) {
    const whooshSound = document.createElement('audio');
    whooshSound.src = 'https://scotch.io/audio/lightsaber.wav';
    whooshSound.play();
  }
}

Now we have this cool whoosh sound!

Conclusion

That ends the Code Challenge for this week. Hope you found that helpful and got some CSS techniques out of it. Until next week!

Source:: scotch.io

Code Challenge #3: CSS Lightsaber Checkbox

By Chris Sevilleja

Welcome to our Code Challenge #3. Way back when about five years ago when we started Scotch.io, one of our very first articles was to create lightsabers using plain CSS.

Let’s bring that back and see how we can build out the same thing in this week’s code challenge.

The Challenge

The challenge is to rebuild this lightsaber checkbox. Go ahead and use CodePen as your code playground and be sure to share the CodePen and what you learned in the comments.

Requirements

Make sure that you have the following elements:

  • All CSS: Animation of the checkbox and also checking and unchecking are all done in CSS
  • HTML Checkbox: Use a and

Bonus Items: Extras

One bonus that could be fun if you want that extra challenge is to implement the lightsaber sound when you click the checkbox.

Here’s an audio file you can use. You can bring JavaScript in for this part of the challenge.

https://scotch.io/files/lightsaber.wav

Resources

If you get stuck on creating the CSS gradients, here are a few to get you started:

.yoda {
    background: rgb(135, 220, 90);
    background: linear-gradient(
    to right, 
    rgb(135, 220, 90) 0%, 
    rgb(254, 254, 254) 30%, 
    rgb(254, 254, 254) 50%, 
    rgb(254, 254, 254) 70%, 
    rgb(135, 220, 90) 100%
  );
}

.vader {
    background: rgb(229, 17, 21);
    background: linear-gradient(
    to right, 
    rgba(229, 17, 21, 1) 0%, 
    rgba(254, 254, 254, 1) 30%, 
    rgba(254, 254, 254, 1) 47%, 
    rgba(254, 254, 254, 1) 71%, 
    rgba(229, 17, 21, 1) 100%
  );
}

.windu {
    background: rgb(202, 116, 221);
    background: linear-gradient(
    to right, 
    rgba(202,116,221,1) 0%,
    rgba(254,254,254,1) 30%,
    rgba(254,254,254,1) 47%,
    rgba(254,254,254,1) 71%,
    rgba(202,116,221,1) 100%
  );
}

Community

  • Join us on the Slack group in the #codechallenge channel.
  • Post your solutions in the comments.
  • Post your solution on Twitter with #scotchchallenge

Solution

Solution video and code will be posted on Monday. Happy coding!

Source:: scotch.io

Weekly Node.js Update - #7 - 02.16, 2018

By Tamas Kadlecsik

Weekly Node.js Update - #7 - 02.16, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates, projects & tutorials from this week:

Node v6.13.0 (LTS) is released

  • console:
    • added console.count() and console.clear() (James M Snell)
  • crypto:
    • expose ECDH class (Bryan English)
  • added cypto.randomFill() and crypto.randomFillSync() (Evan Lucas)
    • warn on invalid authentication tag length (Tobias Nießen)
  • deps:
    • upgrade libuv to 1.16.1 (cjihrig)
  • dgram:
    • added socket.setMulticastInterface() (Will Young)

Read the post for more info here.

Top 1000 most depended-upon packages

This gist is updated daily via cron job and lists stats for npm packages:

  • Top 1,000 most depended-upon packages
  • Top 1,000 packages with largest number of dependencies
  • Top 1,000 packages with highest PageRank score

5 Practical Ways To Share Code: From NPM To Lerna And Bit

Sharing common code between projects and repositories is a key factor for better modularity and faster development, but it’s also complicated.

Here you can read a practical overview of 5 methods for sharing code between these repos and projects for 2018.

Weekly Node.js Update - #7 - 02.16, 2018

Reducing GraphQL response size by… a lot

I have started to use GraphQL in 2017 and since then without exception used it for every project. However, I have soon hit a limitation–the response size can become huge. This happens when you normalize your resources (as you should).

In this post, you can read a solution for reducing GraphQL response size using basic principles of compression?

How to install node.js and npm on Debian 9

In this blog, We are going to see how we can install the node.js and npm on the Debian Operating system.

The Ideas Behind React Easy State

Front-end developers often refer to transparent reactivity  as magic, but there is nothing magical about it. How come? Read this post for details.
Weekly Node.js Update - #7 - 02.16, 2018

Building a Node.js App with MongoDB Atlas and AWS Elastic Container Service, Part 1

Learn how to build a Node.js application with MongoDB Atlas and deploy it easily using Amazon EC2 Container Service (ECS).

Event sourcing vs. CRUD

Which should you choose: Event Sourcing or CRUD?

In this post, you can read about everything that needs to be considered before deciding.

Learn Node.js & Microservices

Would you like to know more about the Node.js Fundamentals, Microservices, Kubernetes, Angular, or React? We have good news for you!

Previously Node.js Updates:

In the previous Weekly Node.js Update, we collected great articles, like

  • Building a realtime polls app with Node.js and Pusher;
  • Use OpenWhisk for FaaS with Node.js and Couchbase NoSQL;
  • Why Developers Love Node.js & what’s their main issue with it? Survey Results.;
  • A Node.js Perspective on MongoDB 3.6: Array Filters;

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com