Job Encryption in Laravel

Job Encryption in Laravel

https://ift.tt/3jlYQ0f


Consider this job:

class VerifyUser implements ShouldQueue
{
    private $user;
    private $socialSecurityNumber;

    public function __construct($user, $socialSecurityNumber)
    {
        $this->user = $user;
        $this->socialSecurityNumber = $socialSecurityNumber;
    }
}

When you dispatch this job, Laravel is going to serialize it so that it can be persisted in the queue store. Let’s take a look at how the final form will look like in the store:

VerifyUser::dispatch($user, '45678AB90');
{
   "uuid":"765434b3-8251-469f-8d9b-199c89407346",
   // ...
   "data":{
      "commandName":"App\\Jobs\\VerifyUser",
      "command":"O:16:\"App\\Jobs\\VerifyUser\":12:{s:22:\"\u0000App\\Jobs\\VerifyUser\u0000user\";N;s:38:\"\u0000App\\Jobs\\VerifyUser\u0000
socialSecurityNumber\";s:9:\"45678AB90\";s:3:\"job\";N;s:10:\"connection\";N;s:5:
\"queue\";N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:19:\"chainCatchCallbacks\";N;s:5:\"delay\";N;s:11:\"afterCommit\";N;s:10:\"middleware\";a:0:{}s:7:\"chained\";a:0:{}}"
   }
}

Looking at the payload, you can see that the value of socialSecurityNumber is visible to the human eye. Any person—or program—that gains access to the queue store will be able to extract this value.

For most jobs this isn’t a problem. But if the job stores critical information in the payload, it’s better we encrypt it so that only our queue workers can read it while processing the job. To do that, we’ll need to implement the ShouldBeEncrypted interface:

use Illuminate\Contracts\Queue\ShouldBeEncrypted;

class VerifyUser implements ShouldQueue, ShouldBeEncrypted
{
    private $user;
    private $socialSecurityNumber;

    public function __construct($user, $socialSecurityNumber)
    {
        $this->user = $user;
        $this->socialSecurityNumber = $socialSecurityNumber;
    }
}

This interface was introduced in Laravel v8.19.0 (Released on December 15, 2020)

Now the payload will look like this:

{
   "uuid":"765434b3-8251-469f-8d9b-199c89407346",
   // ...
   "data":{
      "commandName":"App\\Jobs\\VerifyUser",
      "command":"eyJpdiI6IjIyNWFQOXVNWn...OTJlYjBhYTFmZmQ4MjU1MDZiMDVhMjk0OTYwMTY3ZTgyYjEifQ=="
   }
}

Any person or program with access to the queue store will not be able to decrypt the job payload.

You can use the ShouldBeEncrypted interface with queued jobs, mailables, notifications, and event listeners.

programming

via Laravel News Links https://ift.tt/2dvygAJ

February 12, 2021 at 09:45AM

The Ultimate Performance Checklist For Laravel Apps

The Ultimate Performance Checklist For Laravel Apps

https://ift.tt/3rI46Oo


Laravel is fast out-of-the-box, but you can make it faster if you optimize your configurations and application code. This guide lists a wide range of performance tips from quick wins to advanced techniques that would help you make your Laravel app the lean, mean machine your customers want.

The folks over at Enlightn helped us compile this guide. If you’re looking for an automated performance or security tool for Laravel, do check them out!

Why Performance?

We can all agree that we prefer an app that loads faster to one that’s slow.

According to a Google study, 53% of mobile users leave a site that takes longer than 3 seconds to load. The average mobile site takes about 15 seconds to load. That’s how much performance matters!

Every second your app takes longer to load, you’re probably losing customer conversions. Thankfully, for Laravel apps, it’s not a very difficult problem to solve.

1. Use In-Built Performance Quick Wins

Laravel offers a few in-built performance quick wins that can apply to any app.

The most significant performance quick win is route caching. Did you know that every time you boot your Laravel app, your app determines the middleware, resolves aliases, resolves route groups, and identifies the controller action and parameter inputs for every single route entry?

You can bypass the route processing by caching all the required routing information using the route:cache Artisan command:

“`bash
php artisan route:cache


This command can give you up to a 5x performance boost! It can make a significant impact on your app performance.

Besides route caching, Laravel also offers the following:

- [Configuration caching](https://laravel.com/docs/8.x/configuration#configuration-caching) to bypass parsing your `.env` and `config` files on every app boot.
- [View caching](https://laravel.com/docs/8.x/views#optimizing-views) to pre-compile your Blade template views.
- [Event caching](https://laravel.com/docs/8.x/events#event-discovery-in-production) to cache a manifest of all of your app's events and listeners.

Tip: You should make sure to add the above caching commands to your deployment script so that every time you deploy, your routes, config, views, and events are re-cached. Otherwise, any changes you make to your route or config files will not update in your application.

## 2. Optimize Composer

A common mistake sometimes made by Laravel developers is to install all dependencies in production. Some development packages such as Ignition record your queries, logs, and dumps in memory to give you a friendly error message with context for ease of debugging. While this is useful in development, it can slow down your application in production.

In your deployment script, make sure to use the `--no-dev` flag while installing packages using Composer:

"`bash
composer install --prefer-dist --no-dev -o

Additionally, make sure to use the `-o’ flag in production as above. This enables Composer to optimize the autoloader by generating a “classmap”.

You may choose to use the --classmap-authoritative flag instead of the `-o’ flag for further optimization if your app does not generate classes at runtime. Make sure to check out the Composer documentation on autoloader optimization strategies.

3. Choose The Right Drivers

Choosing the right cache, queue, and session drivers can make quite a difference to application performance.

For caching in production, we recommend the in-memory cache drivers such as Redis, Memcached, or DynamoDB. You may consider local filesystem caching for a single-server setup, although it would be slower than the in-memory options.

For queueing, we recommend the Redis, SQS, or Beanstalkd drivers. The database driver is not suitable for production environments and is known to have deadlock issues.

For sessions, we recommend the Database, Redis, Memcached, or DynamoDB drivers. The cookie driver has the file size and security limitations and is not recommended for production.

4. Queue Your Time-Consuming Tasks

There may be specific tasks that take a long time to perform during a typical web request. Laravel has a best-in-class queueing system that allows us to move time-consuming tasks to queued jobs so that your application can respond to requests with blazing speed.

Common examples of such tasks are parsing and storing a CSV file, interacting with third-party APIs, sending notifications to users, expensive database queries, and updating your search index.

5. Set Compression Headers On Text Format Files

Compression headers can have a significant impact on application performance. Ensure that you enable compression headers on your web server or CDN for text format files, like CSS, JS, XML, or JSON.

Most image formats are already compressed and are not text format files (with the exception of SVG, which is an XML document). So, image formats do not need to be compressed.

You may set up gzip or brotli (preferably both as brotli may not be supported for older browsers) at your web server or CDN level to achieve a huge performance boost.

Typically, compression would be able to reduce your file size by around 80%!

6. Set Cache Headers On Static Assets

Caching can provide a performance boost for your application, especially for static assets such as images, CSS, and JS files. It is recommended to enable cache-control headers at the webserver level or at your CDN level (if applicable). If you wish to set these headers at your Laravel app instead of the webserver, you may use Laravel’s cache control middleware.

Cache headers ensure that browsers don’t request static assets on subsequent visits to your website. This can enhance your user experience as your website loads faster on subsequent visits.

Make sure you use cache-busting so that when you change your CSS or JS code, browsers avoid relying on stale cached content. Laravel Mix provides cache busting out of the box.

7. Consider Using A CDN To Serve Assets

Content Delivery Networks (CDNs) are a geographically distributed group of servers that serve content closer to application visitors by using a nearby server. This enables visitors to experience faster loading times.

Besides faster loading times, CDNs also have other benefits such as decreased web server load, DDoS protection, and analytics on assets served.

Some popular CDNs include Cloudflare, AWS Cloudfront, and Azure CDN. Most CDNs are free for a certain usage threshold. Do consider using CDNs for boosting asset serving performance.

Laravel offers CDN support out of the box for Mix and the asset helper function.

8. Minify Your JS and CSS Code

Minification strips extra code from your application that is not essential for execution (like comments, whitespace, renaming variables with shorter names, and other optimizations). It’s always a good idea to minify JS and CSS files in production.

Laravel Mix provides minification out of the box when you run your production script.

9. Use Cache Wisely

Laravel has caching support built-in. Caching is best used for read-heavy workloads. These workloads typically involve either time-consuming data retrieval or data processing tasks.

Some common use cases of caching could include:

  • Caching static pages: Caching static pages is a no-brainer. Laravel’s website uses page caching for every single documentation page.
  • Fragment or partial caching: Sometimes, instead of caching full pages, it may be useful to cache page fragments. For instance, you may want to cache the page header that contains the name of the user and a profile pic. Instead of fetching the data from the database every time, you can cache the header fragment in one go.
  • Query caching: If your application queries the database on a high frequency for items that seldom change, it may be useful to cache the queries. For instance, if you run an e-commerce store, you might want to cache the items displayed on the store homepage rather than fetching them from the database on every store visit.

Remember that caching is not useful for the “long tail” (items rarely requested). Instead, it should be used carefully for any data retrieval that happens on a high frequency (as compared to data updates).

You must also make sure to invalidate or refresh your cache every time your cached content changes. For instance, if you are caching the profile header, refresh the cache once a user updates their profile pic.

10. Identify Your App’s Performance Bottlenecks

If some of your pages have high loading times or high memory usage, it may be essential to identify performance bottlenecks. Many tools exist within the Laravel ecosystem to help you do that, including Laravel Telescope, Laravel Debugbar, and Clockwork.

Some common performance bottlenecks include:

  • N+1 Queries: If your code executes one query for each record, it will result in more network round trips and a larger number of queries. This can be solved in Laravel using eager loading.
  • Duplicate Queries: If your code executes the same query more than once for the same request, it may slow down your application. Typically these issues can be solved by extracting data computation or retrieval to a separate class if multiple services or classes need the same set of data.
  • High Memory Usage: To reduce memory usage in your application, consider using lazy collections and query chunking for reducing model hydrations. For storing files, check out automatic streaming to reduce memory usage.
  • Slow Queries: If you have queries that are taking too long to execute, you should consider query caching and/or using explain statements to optimize query execution plans.

If you are unable to identify performance bottlenecks in your application using the debugging tools mentioned above, you may consider using profiling tools such as XDebug or Blackfire.

Conclusion

Performance is a wide topic, but Laravel has several components built-in such as Mix, queues, and caching that make performance look easy! We hope that you learned something new about boosting your app’s performance.

programming

via Laravel News https://ift.tt/14pzU0d

February 12, 2021 at 10:55AM

Python Morsels: What is __init__?

Python Morsels: What is __init__?

https://ift.tt/3d1UABQ



Transcript:

Let’s talk about the __init__ method in Python.

A pointless Point class

Here’s a class called Point:

class Point:
    """2-dimensional point."""

We can construct a new instance of this class by calling it:

>>> p = Point()
>>> p
<point.Point object at 0x7fd239fecfd0>

We have a Point object at this point, but this Point object really has no point because it has no functionality (it doesn’t store any useful data or have any methods).

We could manually add attributes to Point objects to store some data on them:

>>> p.x = 1
>>> p.y = 2
>>> p.x
1

But doing so would be a little silly.

It would be better if we could somehow call this class with arguments to store attributes automatically.

The initializer method

Currently, if we try to call this class with arguments, we’ll see an error:

>>> p = Point(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Point() takes no arguments
>>>

In order to accept arguments, we need to define a __init__ method in our class.

    def __init__(self, x, y):
        self.x = x
        self.y = y

The first argument in our __init__ method will always be self (just like pretty much every other method).
After that we need to declare any arguments we want our class to accept.

The main thing you’ll pretty much always see in a __init__ method, is assigning to attributes.

This is our new Point class

class Point:
    """2-dimensional point."""
    def __init__(self, x, y):
        self.x = x
        self.y = y

If we call it like before without any arguments, we’ll see an error because this class now requires two arguments, x and y:

>>> p = Point()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'

We need to give our Point class two arguments in order to get a new instance of this class:

>>> p = Point(1, 2)

This Point object now has an x attribute and a y attribute:

>>> p.x
1
>>> p.y
2

That means our __init__ method was called!

Python calls __init__ whenever a class is called

Whenever you call a class, Python will construct a new instance of that class, and then call that class’ __init__ method, passing in the newly constructed instance as the first argument (self).

Unlike many programming languages, __init__ isn’t called the "constructor method".

Python’s __init__ method is called the initializer method.
The initializer method initializes our new class instance.
So by the point, that the initializer method is called the class instance has already been constructed.

Summary

When you make a new class in Python the first method you’ll likely make is the __init__ method.
The __init__ method allows you to accept arguments to your class.

More importantly, the __init__ method allows you to assign initial values to various attributes on your class instances.

Python

via Planet Python https://ift.tt/1dar6IN

February 12, 2021 at 11:51AM

I wonder why?

I wonder why?

https://ift.tt/3jHO70k

AP-NORC poll: A third of US adults skeptical of COVID shots

The poll from The Associated Press-NORC Center for Public Affairs Research found that while 67% of Americans plan to get vaccinated or have already done so, 15% are certain they won’t and 17% say probably not. Many expressed doubts about the vaccine’s safety and effectiveness.

The poll suggests that substantial skepticism persists more than a month and a half into a U.S. vaccination drive that has encountered few if any serious side effects. Resistance was found to run higher among younger people, people without college degrees, Black Americans and Republicans.

Of those who said they definitely will not get the vaccine, 65% cited worries about side effects, despite the shots’ safety record over the past months. About the same percentage said they don’t trust COVID-19 vaccines. And 38% said they don’t believe they need a vaccine, with a similar share saying that they don’t know if a COVID-19 vaccine will work and that they don’t trust the government.

Let’s recap the situation.

We’ve been told that the vaccine doesn’t stop you from catching or transmitting the virus.

We’ve been told that after you get the vaccine you still have to (double) mask and socially distance.

We’ve been told that despite mass vaccination, the lockdowns will continue and we’re still unable to return to normal.

We know the vaccine has been rushed to market faster than any other in history and that we cannot sue the pharmaceutical companies if we have bad reactions.

What’s the selling point of getting vaccinated.

I’m curious as to why more people are not skeptical.

I’m not an anti-vaxxer.  I’ve had all my shots.  So have my kids.  I get my flu shot every year.

But those have decades of clinical history.

We don’t know if a year from now one in ten people who got the vaccine will end up with cancer or uncontrollable burning rectal discharge.

That is where the reticence comes from.

Not to mention that the handling of the COVID has been so bad I can’t fault anyone who doesn’t trust the government.

“The governor who killed most of the old people in his city then defied a court order stopping him from hiding that fact, a Congressman who got trapped by a Chinese honeypot, and a President with signs of dementia and a millionaire crackhead son trading on daddy’s name say you have to get a vaccine, that doesn’t allow you to take off your mask and live a normal life.  And if the side effects cripple you, you get nothing.”

Wow, where do I sign up for that?

 

 

guns

via https://gunfreezone.net

February 11, 2021 at 01:37PM

Make Your Own Electronic Target with freETarget Open Source Targets

Make Your Own Electronic Target with freETarget Open Source Targets

https://ift.tt/3tRvrzw

 freETarget is an open-source program that allows the average joe to build his very own electronic rifle or pistol target right at home without needing to go to an advanced shooting facility that contains such devices. Almost all modern competitions are making use of Electronic Targets so why not give yourself the same advantages and systems you’d use during a competition? If anything, these Electronic Targets make it easier and faster for shooters to get some solid practice in without constantly walking to check on targets.

freETarget - The Free Open Source Electronic Target

freETarget – The Free Open Source Electronic Target

What is freETarget?

Virtually all competitions are now held on electronic targets. They have the advantage of providing instantaneous feedback without the necessity of peering through a scope or scoring with a plug gauge. Unfortunately, they are expensive and outside of the means of most shooters.

So what to do?

Given the success of various open source projects such as Linux or Open Office, it seems to make sense that somebody try to make an open source electronic target.

freETarget – Free E Target

FreETarget is an opensource project where the parts to make the target, electronics, and visualization software is available online and can be assembled by anybody.

 

freETarget - The Free Open Source Electronic Target

Who can use freETarget?

freETarget is open source, so anybody who has the technical expertise to install software on a PC should be able to make their own freETarget.

  • Advanced amateurs
  • 4H Clubs
  • Scout troops

Commercially available targets are awesome, but for most of us, who has the money. freeETarget is an international collaboration of people providing the skills needed to make an affordable Electronic Target

Ways you can use freETarget

  • You can access the GIT HUB (github.com/ten-point-nine/freETarget) for the detailed technical content. You will find the circuit and mechanical drawings, low level driver software, and the source to the PC application. Download and join the team.
  • You can purchase the assembled and tested circuit boards and build your own housing to start shooting electronically.
  • Join the team. Expanding skills are needed to move the project to the forefront of competitive shooting.
  • Join the conversation on TargetTalk.org

The system is made up of 3 major elements which include the target sensor and acquisition electronics, the target housing, and the PC visualization software. There is a complete list of where to get these items and how to assemble your own freETarget for use at your local club. This is a great example of everyday shooters using their ingenuity to meet the standards of the more professional shooting world without having to spend the money on official electronic target systems.

From what I have read on their blog, the group is making boards for people to purchase to use in their own builds; however, there is currently a waiting list for these limited production boards. All of the software, circuit assemblies, and mechanical design are being handled worldwide by a team of dedicated shooters who want everyone to have access to these advanced systems. Would you build your own freETarget for yourself or even for your local shooting club?

The post Make Your Own Electronic Target with freETarget Open Source Targets appeared first on AllOutdoor.com.

guns

via All Outdoor https://ift.tt/2yaNKUu

February 11, 2021 at 12:02PM

Products Designed for Shabbat Let You Perform Certain Tasks Without Technically Performing Them

Products Designed for Shabbat Let You Perform Certain Tasks Without Technically Performing Them

https://ift.tt/3tSUkv5

For strict adherents of Judaism, Saturdays can be tough days. On Shabbat, whish lasts from sundown each Friday to sundown on Saturday, Jewish law (Halacha) prohibits melakha, which loosely translates to "work;" in practice it means one cannot push an elevator button, turn an appliance on or off, or open a bottle of soda, as some examples.

The laws are pretty specific; for instance, you can open a refrigerator, but if the light inside the ‘fridge visibly illuminates, you’ve broken Halacha. As a workaround, some Jews will disconnect the bulb prior to Shabbat; others will cover the bulb in black tape. There are also interpersonal workarounds: You can ask a non-Jewish person to turn an air conditioner on for you, for instance.

Because some of these workarounds are inconvenient, a company called Kosher Innovations sells an entire line of products that are rabbi-approved and allow you to perform certain tasks without technically violating Halacha. Some examples:

The KosherLamp Max

"A simple twist reveals or hides the light on this innovative reading lamp – and it can be used on Shabbos according to halacha!"

The Kosher Fridz-eez

"Do you like having a light in your refrigerator all week but need a way to keep the light off during Shabbos or Yom Tov?

"That is what the Kosher Fridg-eez is for. It’s designed to hold down the fridge light switch in order to keep the light turned off. When Shabbos or Yom Tov is over, simply pull the plastic tab to remove it, letting the fridge light shine again."

The Shabbos Bottle Opener

"Did you forget to open your soda bottles before Shabbos? Not to worry–the Shabbos Bottle Opener can be used to open plastic soda bottles on Shabbos! It allows you to remove the plastic cap including the plastic ring, without tearing it.

"Normally, the action of unscrewing the bottle cap causes the perforated ring to tear. This is fine for during the week but on Shabbos/Yom Tov, falls under the category of the melacha of Makeh B’Patish (Act of Completion). By separating the ring from the cap, it finishes the cap, allowing it to be removed from the bottle.

"The Shabbos Bottle Opener grips the bottle cap and removes both the cap and the perforated plastic ring at the same time, without tearing the ring. Thus it avoids the melacha of Makeh B’Patish. In fact, one can still replace the cap with the perforated ring still attached, back onto the bottle. One would just need to use the Shabbos Bottle Opener a second time to remove it again."

I find this category of product design completely fascinating. You can check out more of these here.

fun

via Core77 https://ift.tt/1KCdCI5

February 10, 2021 at 09:54AM

The Falcon and the Winter Soldier Trailer Wins the Super Bowl

The Falcon and the Winter Soldier Trailer Wins the Super Bowl

https://ift.tt/3oYcrvG


Just bros bro-ing about.
Screenshot: Disney

Trailer FrenzyA special place to find the newest trailers for movies and TV shows you’re craving.

I don’t know from sports, but I know my supes, and as far as I’m concerned, the Super Bowl was between the New York City Falcons and the Brooklyn Bucky-neers. They both won and so did we.

In a new spot aired during the Super Bowl, we got a new look at the upcoming Disney+ show starring Anthony Mackie and Sebastian Stan, and co-starring Daniel Brühl, Wyatt Russell, and Emily VanCamp (hopefully this show will do Sharon Carter at least mildly less dirty than the movies—Peggy’s niece deserves better).

The Falcon and the Winter Soldier drops, at last, on Disney+ March 19.


For more, make sure you’re following us on our Instagram @io9dotcom.

G/O Media may get a commission

geeky,Tech

via Gizmodo https://gizmodo.com

February 7, 2021 at 07:24PM

AlmaLinux Releases Beta of Their CentOS/RHEL 8 Fork

AlmaLinux Releases Beta of Their CentOS/RHEL 8 Fork

https://ift.tt/3ruC20S

AlmaLinux describes itself as "an open-source, community-driven project that intends to fill the gap left by the demise of the CentOS stable release." And now AlmaLinux "has announced their beta release of their CentOS/RHEL 8 fork," writes Slashdot reader juniorkindergarten. AlmaLinux will be getting $1 million a year in development funding from CloudLinux (the company behind CloudLinux OS, a CentOS clone with over 200,000 active server instances). Their CEO stresses that AlmaLinux "is built with CloudLinux expertise but will be owned and governed by the community. We intend to deliver this forever-free Linux distribution this quarter." And they’ve committed to supporting it through 2029. Their press release touts AlmaLinux as "a 1:1 binary compatible fork of RHEL 8, with an effortless migration path from CentOS to AlmaLinux. Future RHEL releases will also be forked into a new AlmaLinux release." From the AlmaLinux blog:
We’ve collected community feedback and built our new beta release around what you would expect from an enterprise-level Linux distribution…inspired by the community and built by the engineers and talent behind CloudLinux. Visit https://almalinux.org to download the Beta images. With the Beta release deployed, we’d like to ask the community to be involved and provide feedback. We aim to build a Linux distribution entirely from community contributions and feedback. During AlmaLinux Beta, we ask for assistance in testing, documentation, support and future direction for the operating system. Together, we can build a Linux distribution that fills the gap left by the now unsupported CentOS distribution. On Wednesday they’ll be hosting a live QA webinar with the AlmaLinux team. And there’s also a small AlmaLinux forum on Reddit.


Read more of this story at Slashdot.

geeky

via Slashdot https://slashdot.org/

February 6, 2021 at 03:41PM