Skip to content

Commit

Permalink
Merge branch 'master' into feature/update-to-laravel-6
Browse files Browse the repository at this point in the history
  • Loading branch information
mikebronner committed Sep 5, 2019
2 parents 1e27215 + 5066292 commit 37d35d5
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 266 deletions.
12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# These are supported funding model platforms

github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: mikebronner
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ addons:
php:
- 7.1.3
- 7.2
- 7.3

before_script:
- travis_retry composer self-update
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
### Removed
- compatibility with older versions of Laravel.

## [0.8.3] - 2019-06-30
### Added
- support for Spatie's `laravel-csp` package.

## [0.8.2] - 2019-06-30
### Changed
- method of checking registered middleware groups to use `hasMiddlewareGroup()`.

## [0.6.12] - 5 Aug 2018
### Fixed
- middleware response to be a view instead of string. Thanks @dallincoons, #96 #95.
Expand Down
222 changes: 1 addition & 221 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
![Coffee for Laravel](https://github.com/GeneaLabs/laravel-caffeine/blob/master/caffeine.jpg)

# Caffeine for Laravel
[![Join the chat at https://gitter.im/GeneaLabs/laravel-caffeine](https://badges.gitter.im/GeneaLabs/laravel-caffeine.svg)](https://gitter.im/GeneaLabs/laravel-caffeine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Travis](https://img.shields.io/travis/GeneaLabs/laravel-caffeine.svg)](https://travis-ci.org/GeneaLabs/laravel-caffeine)
Expand All @@ -8,222 +6,4 @@
[![GitHub (pre-)release](https://img.shields.io/github/release/GeneaLabs/laravel-caffeine/all.svg)](https://github.com/GeneaLabs/laravel-caffeine)
[![Packagist](https://img.shields.io/packagist/dt/GeneaLabs/laravel-caffeine.svg)](https://packagist.org/packages/genealabs/laravel-caffeine)

## Goal
Prevent forms from timing out when submitting them after leaving them on-screen
for a considerable amount of time. (Laravel defaults to 120 minutes, but that
is configurable and could be different site-by-site.)

## Implementation
To achieve this, we are sending a caffeine-drip (a request at regular intervals)
to keep the session from timing out.
This is only implemented on pages with a `_token` field, so all other pages will
time-out as normal.

## Reasoning
I chose this approach to keep the integrity of site-security, by avoiding the
following:
- exposing the CSRF Token on an unsecured endpoint.
- eliminating CSRF Token validation on specific routes, or even altogether.
- removing session-timeout on all pages.

## Considerations
### Routes
This package adds the routes under `genealabs/laravel-caffeine`.

### Dependencies
- Your project must be running one of the following Laravel versions:
- 5.1 (LTS)
- 5.3
- 5.4
- 5.5 (LTS)
- 5.6
- PHP 7.1.3 or higher.

## Installation
For Laravel 5.2, follow the directions here: https://github.com/GeneaLabs/laravel-caffeine/tree/166e2ca08af7cc62a59360f33e03d1cb8478df6a

1. Install the package:
```sh
composer require genealabs/laravel-caffeine
```

2. **This is only required for Laravel 5.4 or below:**
Add the service provider entry in `config/app.php`:
```php
// 'providers' => [
GeneaLabs\LaravelCaffeine\Providers\Service::class,
// ],
```

3. If you are running 5.5 or above, remove the providers entry from `config/app.php`.
4. If you have previously registered the middleware, please remove the following
middleware from `app/Http/Kernel.php`:
```php
// protected $middleware = [
GeneaLabs\LaravelCaffeine\Http\Middleware\LaravelCaffeineDripMiddleware::class,
// ];
```

## Upgrade Notes
### 0.6.0
This update changes the config file setting names. Please delete the published
config file `config/genealabs-laravel-caffeine.php` if it exists, and follow the
configuration instructions below.

## Configuration
```php
return [
/*
|--------------------------------------------------------------------------
| Drip Interval
|--------------------------------------------------------------------------
|
| Here you may configure the interval with which Caffeine for Laravel
| keeps the session alive. By default this is 5 minutes (expressed
| in milliseconds). This needs to be shorter than your session
| lifetime value configured set in "config/session.php".
|
| Default: 300000 (int)
|
*/
'drip-interval' => 300000,
/*
|--------------------------------------------------------------------------
| Domain
|--------------------------------------------------------------------------
|
| You may optionally configure a separate domain that you are running
| Caffeine for Laravel on. This may be of interest if you have a
| monitoring service that queries other apps. Setting this to
| null will use the domain of the current application.
|
| Default: null (null|string)
|
*/
'domain' => null,
/*
|--------------------------------------------------------------------------
| Drip Endpoint URL
|--------------------------------------------------------------------------
|
| Sometimes you may wish to white-label your app and not expose the AJAX
| request URLs as belonging to this package. To achieve that you can
| rename the URL used for dripping caffeine into your application.
|
| Default: 'genealabs/laravel-caffeine/drip' (string)
|
*/
'route' => 'genealabs/laravel-caffeine/drip', // Customizable end-point URL
/*
|--------------------------------------------------------------------------
| Checking for Lapsed Drips
|--------------------------------------------------------------------------
|
| If the browser is put to sleep on (for example on mobil devices or
| laptops), it will still cause an error when trying to submit the
| form. To avoid this, we force-reload the form 2 minutes prior
| to session time-out or later. Setting this setting to 0
| will disable this check if you don't want to use it.
|
| Default: 2000 (int)
|
*/
'outdated-drip-check-interval' => 2000,
/*
|--------------------------------------------------------------------------
| Use Route Middleware
|--------------------------------------------------------------------------
|
| Drips are enabled via route middleware instead of global middleware.
|
| Default: false (bool)
|
*/
'use-route-middleware' => false,
];
```
___Only publish the config file if you need to customize it___:
```sh
php artisan caffeine:publish --config
```
## Usage
That was it! It will apply itself automatically where it finds a form with a
`_token` field, or a meta tag named "csrf-token", while pages are open in
browsers.
### Prevent Caffeination
There are two methods to prevent Caffeine for Laravel from dripping to keep the
session alive: disabling it in Blade using the meta tag method, or enabling
route-middleware mode, and then only enabling it on routes or route groups.
#### Meta Tag Method
If you would like to prevent a certain page from caffeinating your application,
then add the following meta tag:
```php
<meta name="caffeinated" content="false">
```
#### Route Middleware Method
To enable this mode, you need to publish the configuration file (see the
configuration section above) and then set `use-route-middleware` to `true`. This
will disable the default global middleware mode (which applies it to any page
that has the CSRF token in it across your entire application). Now you need to
selectively enable Caffeine on a given route or route group using route
middleware:
```php
Route::any('test', 'TestController@test')->middleware('caffeinated');
Route::group(['middleware' => ['caffeinated']], function () {
Route::any('test', 'TestController@test');
})
```
You can still use the route middleware method and apply it globally to all
routes by editing `app/Http/Kernel.php` and adding it to the `web` middleware
group. Although you should only use this option if you have a very specific use-
case that prevents you from utilizing the default global middleware option.
__This will only have effect if the page includes a form. If not, the page will
not caffeinate your application anyway.__
# The Fine Print
## Commitment to Quality
During package development I try as best as possible to embrace good design and
development practices to try to ensure that this package is as good as it can
be. My checklist for package development includes:
- ✅ Achieve as close to 100% code coverage as possible using unit tests.
- ✅ Eliminate any issues identified by SensioLabs Insight and Scrutinizer.
- ✅ Be fully PSR1, PSR2, and PSR4 compliant.
- ✅ Include comprehensive documentation in README.md.
- ✅ Provide an up-to-date CHANGELOG.md which adheres to the format outlined
at <http://keepachangelog.com>.
- ✅ Have no PHPMD or PHPCS warnings throughout all code.
## Contributing
Please observe and respect all aspects of the included Code of Conduct
<https://github.com/GeneaLabs/laravel-caffeine/blob/master/CODE_OF_CONDUCT.md>.
### Reporting Issues
When reporting issues, please fill out the included template as completely as
possible. Incomplete issues may be ignored or closed if there is not enough
information included to be actionable.
### Submitting Pull Requests
Please review the Contribution Guidelines <https://github.com/GeneaLabs/laravel-caffeine/blob/master/CONTRIBUTING.md>.
Only PRs that meet all criterium will be accepted.
## ❤️ Open-Source Software - Give ⭐️
We have included the awesome `symfony/thanks` composer package as a dev
dependency. Let your OS package maintainers know you appreciate them by starring
the packages you use. Simply run `composer thanks` after installing this
package. (And not to worry, since it's a dev-dependency it won't be installed in
your live environment.)
Documentation has moved to https://genealabs.com/docs/laravel-caffeine/.
6 changes: 5 additions & 1 deletion resources/views/script.blade.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
@if (function_exists('csp_nonce'))
<script nonce="{{ csp_nonce() }}">
@else
<script>
@endif
var lastCheck = new Date();
var caffeineSendDrip = function () {
var ajax = window.XMLHttpRequest
Expand All @@ -14,7 +18,7 @@
ajax.open('GET', '{{ $url }}');
ajax.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
ajax.send();
}
};
setInterval(function () {
caffeineSendDrip();
Expand Down
3 changes: 1 addition & 2 deletions src/Dripper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ class Dripper extends Model
{
public function getHtmlAttribute() : string
{
$html = (string) view('genealabs-laravel-caffeine::script')
return (string) view('genealabs-laravel-caffeine::script')
->with([
'ageCheckInterval' => $this->ageCheckInterval,
'ageThreshold' => $this->ageThreshold,
'interval' => $this->interval,
'url' => $this->url,
]);
return $html;
}

public function getAgeCheckIntervalAttribute() : int
Expand Down
9 changes: 5 additions & 4 deletions src/Http/Middleware/LaravelCaffeineDripMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ public function handle(Request $request, Closure $next)
}

$dripper = (new Dripper);
$content = str_replace(
'</body>',
"{$dripper->html}</body>",
$content
$content = preg_replace(
'/(<\/body\>?|<\/html\>?|\Z)/',
$dripper->html . '$1',
$content,
1
);
$original = $response->original;
$response->setContent($content);
Expand Down
21 changes: 2 additions & 19 deletions src/Providers/Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Service extends ServiceProvider
{
public function boot()
{
app('router')->group($this->middlewareGroupExists('web')
app('router')->group(app("router")->hasMiddlewareGroup('web')
? ['middleware' => 'web']
: [], function () {
require __DIR__ . '/../../routes/web.php';
Expand Down Expand Up @@ -53,29 +53,12 @@ public function boot()
}
}

protected function middlewareGroupExists(string $group) : bool
{
$routes = collect(app('router')->getRoutes()->getRoutes());

return $routes->reduce(function ($carry, Route $route) use ($group) {
$carry = ($carry ?? false) ?: false;
$actions = (array) $route->getAction();

if (array_key_exists('middleware', $actions)
&& in_array($group, (array) $actions['middleware'])
) {
return true;
}

return $carry;
}) ?? false;
}

protected function shouldRegisterGlobalMiddleware() : bool
{
return (! request()->ajax()
&& ! $this->shouldRegisterRouteMiddleware()
&& (php_sapi_name() === 'fpm-fcgi'
|| php_sapi_name() === 'cgi-fcgi'
|| php_sapi_name() === 'apache2handler'
|| config("app.env") === 'internaltesting'));
}
Expand Down
24 changes: 12 additions & 12 deletions tests/Browser/DripTest.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
<?php namespace GeneaLabs\LaravelCaffeine\Tests\Browser;

use GeneaLabs\LaravelCaffeine\Tests\BrowserTestCase;
use Laravel\Dusk\Browser;
// use GeneaLabs\LaravelCaffeine\Tests\BrowserTestCase;
// use Laravel\Dusk\Browser;

class DripTest extends BrowserTestCase
{
public function testFormDoesntExpire()
{
$this->browse(function (Browser $browser) {
$response = $browser->visit('tests/form');
// class DripTest extends BrowserTestCase
// {
// public function testFormDoesntExpire()
// {
// $this->browse(function (Browser $browser) {
// $response = $browser->visit('tests/form');

$response->assertSee('Test Form');
});
}
}
// $response->assertSee('Test Form');
// });
// }
// }
10 changes: 5 additions & 5 deletions tests/BrowserTestCase.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php namespace GeneaLabs\LaravelCaffeine\Tests;

use Orchestra\Testbench\Dusk\TestCase as BaseTestCase;
// use Orchestra\Testbench\Dusk\TestCase as BaseTestCase;

abstract class BrowserTestCase extends BaseTestCase
{
use CreatesApplication;
}
// abstract class BrowserTestCase extends BaseTestCase
// {
// use CreatesApplication;
// }
Loading

0 comments on commit 37d35d5

Please sign in to comment.