Skip to content

Commit a7dcaf0

Browse files
authored
Merge pull request #1 from lbausch/develop
WIP: Version 0.1
2 parents da0fcfc + fd65175 commit a7dcaf0

12 files changed

+547
-40
lines changed

.github/workflows/tests.yml

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
name: tests
2+
3+
on:
4+
push:
5+
pull_request:
6+
schedule:
7+
- cron: '0 0 * * *'
8+
9+
jobs:
10+
tests:
11+
12+
runs-on: ubuntu-latest
13+
# services:
14+
# mysql:
15+
# image: mysql:5.7
16+
# env:
17+
# MYSQL_ALLOW_EMPTY_PASSWORD: yes
18+
# MYSQL_DATABASE: forge
19+
# ports:
20+
# - 33306:3306
21+
# options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
22+
strategy:
23+
fail-fast: true
24+
matrix:
25+
php: [7.2, 7.3, 7.4]
26+
stability: [prefer-lowest, prefer-stable]
27+
28+
name: PHP ${{ matrix.php }} - ${{ matrix.stability }}
29+
30+
steps:
31+
- name: Checkout code
32+
uses: actions/checkout@v2
33+
34+
- name: Cache dependencies
35+
uses: actions/cache@v1
36+
with:
37+
path: ~/.composer/cache/files
38+
key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
39+
40+
- name: Setup PHP
41+
uses: shivammathur/setup-php@v2
42+
with:
43+
php-version: ${{ matrix.php }}
44+
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, gd
45+
coverage: xdebug
46+
47+
- name: Install dependencies
48+
run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction --no-progress
49+
50+
- name: Execute tests
51+
run: vendor/bin/phpunit --verbose --coverage-xml .coverage-xml
52+
env:
53+
DB_PORT: ${{ job.services.mysql.ports[3306] }}
54+
DB_USERNAME: root
55+
56+
- name: Run codacy-coverage-reporter
57+
uses: codacy/codacy-coverage-reporter-action@master
58+
with:
59+
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
60+
coverage-reports: .coverage-xml/index.xml

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
/composer.lock
22
/vendor/
3+
/.phpunit.result.cache

README.md

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,43 @@
11
# Flarum Laravel Session <!-- omit in toc -->
22

3+
![tests](https://github.com/lbausch/flarum-laravel-session/workflows/tests/badge.svg) [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/08e639f60aca4927891fa9e4661003bd)](https://www.codacy.com/manual/lbausch/flarum-laravel-session)
4+
35
**Disclaimer**: This package is still a proof of concept.
46

5-
- [What it does](#what-it-does)
7+
- [What It Does](#what-it-does)
68
- [Requirements](#requirements)
7-
- [Installation and configuration](#installation-and-configuration)
9+
- [Installation and Configuration](#installation-and-configuration)
10+
- [Composer](#composer)
11+
- [Register Middleware](#register-middleware)
12+
- [Setup Database Connection](#setup-database-connection)
13+
- [Publish Package Configuration](#publish-package-configuration)
14+
- [Disable Cookie Encryption](#disable-cookie-encryption)
815
- [Usage](#usage)
9-
- [Accessing session cookie from different domain](#accessing-session-cookie-from-different-domain)
16+
- [Setup Middleware](#setup-middleware)
17+
- [Updating Attributes](#updating-attributes)
18+
- [Accessing Session Cookie From Different Domain](#accessing-session-cookie-from-different-domain)
1019

11-
## What it does
20+
## What It Does
1221
This package allows to use the session of [Flarum](https://flarum.org/) for authentication within a Laravel application.
1322
It accesses Flarum's session cookie and reads the session data from the session storage.
1423
Based on the user information in the Flarum database an user in the Laravel application is created / updated and logged in.
1524

1625
## Requirements
17-
+ PHP 7.4
26+
+ PHP 7.2+
1827
+ Laravel 7
19-
+ Working installation of Flarum in the same filesystem as the Laravel application, so Flarum's session files can be accessed
20-
+ Flarum and Laravel need to share the same domain / subdomain, so Flarum's session cookie can be read
28+
+ Working installation of Flarum in the same filesystem as the Laravel application, so Flarum's session files can be read
29+
+ Flarum and Laravel need to share the same domain / subdomain, so Flarum's session cookie can be accessed
30+
31+
## Installation and Configuration
2132

22-
## Installation and configuration
23-
Install the package by executing `composer require lbausch/flarum-laravel-session:dev-master` and register the middleware in `app/Http/Kernel.php`:
33+
### Composer
34+
Install the package with Composer:
35+
```bash
36+
composer require lbausch/flarum-laravel-session:dev-master
37+
```
38+
39+
### Register Middleware
40+
Register the middleware in `app/Http/Kernel.php`:
2441
```php
2542
/**
2643
* The application's route middleware.
@@ -31,10 +48,12 @@ Install the package by executing `composer require lbausch/flarum-laravel-sessio
3148
*/
3249
protected $routeMiddleware = [
3350
// ...
34-
'flarum' => \Bausch\FlarumLaravelSession\FlarumMiddleware::class,
51+
'flarum' => \Bausch\FlarumLaravelSession\FlarumSessionMiddleware::class,
3552
// ...
3653
];
3754
```
55+
56+
### Setup Database Connection
3857
Define a database connection for the Flarum database in `config/database.php`:
3958
```php
4059
'flarum' => [
@@ -57,9 +76,26 @@ Define a database connection for the Flarum database in `config/database.php`:
5776
]) : [],
5877
],
5978
```
79+
80+
### Publish Package Configuration
6081
Publish the package configuration using `php artisan vendor:publish --provider=Bausch\\FlarumLaravelSession\\ServiceProvider` and update `config/flarum.php` with your settings.
6182

83+
### Disable Cookie Encryption
84+
To avoid Laravel from trying to encrypt the Flarum session cookie, add the following to `app/Http/Middleware/EncryptCookies.php`:
85+
```php
86+
/**
87+
* The names of the cookies that should not be encrypted.
88+
*
89+
* @var array
90+
*/
91+
protected $except = [
92+
'flarum_session',
93+
];
94+
```
95+
6296
## Usage
97+
98+
### Setup Middleware
6399
In `routes/web.php` you may assign the middleware as desired:
64100
```php
65101
Route::middleware(['flarum'])->group(function () {
@@ -69,7 +105,12 @@ Route::middleware(['flarum'])->group(function () {
69105
});
70106
```
71107

72-
## Accessing session cookie from different domain
108+
### Updating Attributes
109+
Attributes which are updated upon a successful authentication can be specified by modifying the array `update_attributes` in `config/flarum.php`.
110+
To track the relationship between your local user and the Flarum user, you may add a column `flarum_id` to your users table.
111+
112+
113+
## Accessing Session Cookie From Different Domain
73114
If Flarum is running on domain.tld and Laravel on sub.domain.tld you need to configure Flarum (`config.php`), so the session cookie can be accessed on the subdomain:
74115
```php
75116
// Note the dot before domain.tld

composer.json

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,48 @@
11
{
22
"name": "lbausch/flarum-laravel-session",
3-
"description": "Use Flarum's session within Laravel",
3+
"description": "Use the session of Flarum within Laravel.",
44
"type": "library",
5-
"require-dev": {
6-
"orchestra/testbench": "^5.3"
7-
},
85
"license": "MIT",
6+
"keywords": [
7+
"auth",
8+
"authentication",
9+
"flarum",
10+
"laravel",
11+
"session",
12+
"share"
13+
],
14+
"support": {
15+
"issues": "https://github.com/lbausch/flarum-laravel-session/issues",
16+
"source": "https://github.com/lbausch/flarum-laravel-session"
17+
},
918
"authors": [
1019
{
1120
"name": "Lorenz Bausch",
1221
"email": "[email protected]"
1322
}
1423
],
1524
"require": {
16-
"php": "^7.4",
25+
"php": "^7.2",
1726
"illuminate/auth": "^7.0",
1827
"illuminate/filesystem": "^7.0",
1928
"illuminate/http": "^7.0",
2029
"illuminate/session": "^7.0",
2130
"illuminate/support": "^7.0"
2231
},
32+
"require-dev": {
33+
"orchestra/testbench": "^5.3",
34+
"phpunit/phpunit": "8.*"
35+
},
2336
"autoload": {
2437
"psr-4": {
2538
"Bausch\\FlarumLaravelSession\\": "src/"
2639
}
2740
},
41+
"autoload-dev": {
42+
"psr-4": {
43+
"Tests\\": "tests/"
44+
}
45+
},
2846
"extra": {
2947
"laravel": {
3048
"providers": [

config/flarum.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
/*
1010
* Model which is authenticatable
1111
*/
12-
'model' => App\User::class,
12+
'model' => config('auth.providers.users.model', App\User::class),
1313

1414
/*
1515
* Flarum session configuration
@@ -23,11 +23,20 @@
2323
/*
2424
* Absolute path to the session directory of Flarum
2525
*/
26-
'path' => base_path('flarum/storage/sessions'),
26+
'path' => env('FLARUM_SESSION_PATH', base_path('flarum/storage/sessions')),
2727
],
2828

2929
/*
3030
* Flarum database connection as defined in config/database.php
3131
*/
3232
'db_connection' => env('FLARUM_DB_CONNECTION', 'flarum'),
33+
34+
/*
35+
* Attributes to update upon successful authentication: Flarum user => local user
36+
*/
37+
'update_attributes' => [
38+
'username' => 'username',
39+
'id' => 'flarum_id',
40+
'email' => 'email',
41+
],
3342
];

phpunit.xml.dist

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
4+
bootstrap="vendor/autoload.php"
5+
colors="true"
6+
testdox="true"
7+
>
8+
<testsuites>
9+
<testsuite name="Flarum Laravel Session Test Suite">
10+
<directory suffix="Test.php">./tests</directory>
11+
</testsuite>
12+
</testsuites>
13+
<filter>
14+
<whitelist processUncoveredFilesFromWhitelist="true">
15+
<directory suffix=".php">./src</directory>
16+
</whitelist>
17+
</filter>
18+
<php>
19+
<env name="DB_CONNECTION" value="testing"/>
20+
</php>
21+
</phpunit>

src/FlarumMiddleware.php renamed to src/FlarumSessionMiddleware.php

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@
33
namespace Bausch\FlarumLaravelSession;
44

55
use Closure;
6+
use Illuminate\Container\Container;
67
use Illuminate\Filesystem\Filesystem;
78
use Illuminate\Foundation\Auth\User;
89
use Illuminate\Http\Request;
910
use Illuminate\Session\FileSessionHandler;
1011
use Illuminate\Session\Store;
11-
use Illuminate\Support\Facades\App;
1212
use Illuminate\Support\Facades\Auth;
1313
use Illuminate\Support\Facades\Config;
1414
use Illuminate\Support\Facades\DB;
1515
use Illuminate\Support\Str;
1616

17-
class FlarumMiddleware
17+
class FlarumSessionMiddleware
1818
{
1919
/**
2020
* Handle an incoming request.
@@ -40,12 +40,7 @@ public function handle(Request $request, Closure $next)
4040
$session_store = new Store('flarum-laravel-session', $this->getFileSessionHandler(), $flarum_session_id);
4141

4242
// Start session
43-
$session_started = $session_store->start();
44-
45-
// Abort if session could'nt be started
46-
if (!$session_started) {
47-
abort(403);
48-
}
43+
$session_store->start();
4944

5045
// Try to get user id
5146
$user_id = $session_store->get('user_id', false);
@@ -56,7 +51,7 @@ public function handle(Request $request, Closure $next)
5651
}
5752

5853
// Get Flarum user from Flarum database
59-
$flarum_user = DB::connection(Config::get('flarum.database_connection'))->table('users')->find($user_id);
54+
$flarum_user = DB::connection(Config::get('flarum.db_connection'))->table('users')->find($user_id);
6055

6156
// Abort if no Flarum user is present in database
6257
if (!$flarum_user) {
@@ -81,7 +76,7 @@ public function handle(Request $request, Closure $next)
8176
protected function getFileSessionHandler(): FileSessionHandler
8277
{
8378
// Create filesystem
84-
$filesystem = new Filesystem();
79+
$filesystem = Container::getInstance()->make(Filesystem::class);
8580

8681
// Get path to session files
8782
$session_path = Config::get('flarum.session.path');
@@ -102,28 +97,25 @@ protected function getFileSessionHandler(): FileSessionHandler
10297
protected function createOrUpdateUser(?User $user, object $flarum_user): User
10398
{
10499
// Get a user instance
105-
if (is_null($user)) {
100+
if (null === $user) {
106101
$user = $this->getUser();
107102
}
108103

109-
// Attributes to update: local user => flarum user
110-
$attributes = [
111-
'username' => 'username',
112-
'nickname' => 'nickname',
113-
'flarum_id' => 'id',
114-
'email' => 'email',
115-
];
104+
// Attributes to update: Flarum user => local user
105+
$update_attributes = Config::get('flarum.update_attributes', []);
116106

117107
// Update attributes
118-
foreach ($attributes as $attribute) {
119-
$user->{$attribute} = $flarum_user->{$attribute};
108+
foreach ($update_attributes as $flarum_attribute => $local_attribute) {
109+
$user->{$local_attribute} = $flarum_user->{$flarum_attribute};
120110
}
121111

122112
// Set a random password
123113
$user->password = bcrypt(Str::random(30));
124114

125115
// Save user
126-
$user->save();
116+
if ($user->isDirty()) {
117+
$user->save();
118+
}
127119

128120
// Return user
129121
return $user;
@@ -134,6 +126,6 @@ protected function createOrUpdateUser(?User $user, object $flarum_user): User
134126
*/
135127
protected function getUser(): User
136128
{
137-
return App::make(config('flarum.model'));
129+
return Container::getInstance()->make(Config::get('flarum.model'));
138130
}
139131
}

0 commit comments

Comments
 (0)