Skip to content

Commit

Permalink
Adding login/password authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
axeloz committed May 16, 2023
1 parent 9a03d54 commit 879242c
Show file tree
Hide file tree
Showing 19 changed files with 340 additions and 36 deletions.
74 changes: 74 additions & 0 deletions app/Console/Commands/CreateUser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'fs:create-user {login?}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';

/**
* Execute the console command.
*/
public function handle()
{
$login = $this->argument('login');

login:
// If user was not provided, asking for it
if (empty($login)) {
$login = $this->ask('Enter the user\'s login');
}

if (! preg_match('~^[a-z0-9]{1,40}$~', $login)) {
$this->error('Invalid login format. Must only contains letters and numbers, between 1 and 40 chars');
unset($login);
goto login;
}

// Checking login unicity
if (Storage::disk('users')->exists($login.'.json')) {
$this->error('User "'.$login.'" already exists');
unset($login);
goto login;
}

password:
// Asking for user's password
$password = $this->secret('Enter the user\'s password');

if (strlen($password) < 5) {
$this->error('Invalid password format. Must only contains 5 chars minimum');
unset($password);
goto password;
}

try {
Storage::disk('users')->put($login.'.json', json_encode([
'login' => $login,
'password' => Hash::make($password)
]));

$this->info('User has been created');
}
catch(Exception $e) {
$this->error('An error occurred, could not create user');
}
}
}
2 changes: 1 addition & 1 deletion app/Console/Commands/PurgeFiles.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class PurgeFiles extends Command
*
* @var string
*/
protected $signature = 'storage:purge-expired';
protected $signature = 'fs:purge-expired';

/**
* The console command description.
Expand Down
1 change: 1 addition & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Kernel extends ConsoleKernel
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
$schedule->command('fs:purge-expired')->hourly();
}

/**
Expand Down
6 changes: 3 additions & 3 deletions app/Http/Controllers/UploadController.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ public function uploadFile(Request $request, String $bundleId) {
$metadata = Upload::getMetadata($bundleId);

// Validating file
abort_if(! $request->hasFile('file'), 401);
abort_if(! $request->file('file')->isValid(), 401);
abort_if(! $request->hasFile('file'), 422);
abort_if(! $request->file('file')->isValid(), 422);

$this->validate($request, [
'file' => 'required|file|max:'.(Upload::fileMaxSize() / 1000)
Expand Down Expand Up @@ -101,7 +101,7 @@ public function deleteFile(Request $request, String $bundleId) {

$metadata = Upload::getMetadata($bundleId);

abort_if(empty($request->file), 401);
abort_if(empty($request->file), 422);

try {
$metadata = Upload::deleteFile($bundleId, $request->file);
Expand Down
51 changes: 48 additions & 3 deletions app/Http/Controllers/WebController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,64 @@

namespace App\Http\Controllers;
use App\Helpers\Upload;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;

class WebController extends Controller
{
function homepage(Request $request)
public function homepage()
{
return view('homepage');
}

public function login() {
return view('login');
}

public function doLogin(Request $request) {
abort_if(! $request->ajax(), 403);

$request->validate([
'login' => 'required',
'password' => 'required'
]);

try {
if (Storage::disk('users')->missing($request->login.'.json')) {
throw new Exception('Authentication failed');
}

$json = Storage::disk('users')->get($request->login.'.json');

if (! $user = json_decode($json, true)) {
throw new Exception('Cannot decode JSON file');
}

if (! Hash::check($request->password, $user['password'])) {
throw new Exception('Authentication failed');
}

$request->session()->put('login', $request->login);
$request->session()->put('authenticated', true);

return response()->json([
'result' => true,
]);
}
catch (Exception $e) {
return response()->json([
'result' => false,
'error' => $e->getMessage()
]);
}
}

function newBundle(Request $request) {
// Aborting if request is not AJAX
abort_if(! $request->ajax(), 401);
abort_if(! $request->ajax(), 403);

$request->validate([
'bundle_id' => 'required',
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class Kernel extends HttpKernel
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'upload' => \App\Http\Middleware\UploadAccess::class,
'can.upload' => \App\Http\Middleware\UploadAccess::class,
'access.owner' => \App\Http\Middleware\OwnerAccess::class,
'access.guest' => \App\Http\Middleware\GuestAccess::class
];
Expand Down
6 changes: 3 additions & 3 deletions app/Http/Middleware/GuestAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class GuestAccess
public function handle(Request $request, Closure $next): Response
{
// Aborting if Bundle ID is not present
abort_if(empty($request->route()->parameter('bundle')), 401);
abort_if(empty($request->route()->parameter('bundle')), 403);

abort_if(empty($request->auth), 401);
abort_if(empty($request->auth), 403);

// Getting metadata
$metadata = Upload::getMetadata($request->route()->parameter('bundle'));
Expand All @@ -28,7 +28,7 @@ public function handle(Request $request, Closure $next): Response
abort_if(empty($metadata), 404);

// Aborting if auth_token is different from URL param
abort_if($metadata['preview_token'] !== $request->auth, 401);
abort_if($metadata['preview_token'] !== $request->auth, 403);

// Checking bundle expiration
abort_if($metadata['expires_at'] < time(), 404);
Expand Down
8 changes: 4 additions & 4 deletions app/Http/Middleware/OwnerAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ class OwnerAccess
public function handle(Request $request, Closure $next): Response
{
// Aborting if request is not AJAX
abort_if(! $request->ajax(), 401);
abort_if(! $request->ajax(), 403);

// Aborting if Bundle ID is not present
abort_if(empty($request->route()->parameter('bundle')), 401);
abort_if(empty($request->route()->parameter('bundle')), 403);

// Aborting if auth is not present
$auth = null;
Expand All @@ -30,7 +30,7 @@ public function handle(Request $request, Closure $next): Response
else if (! empty($request->auth)) {
$auth = $request->auth;
}
abort_if(empty($auth), 401);
abort_if(empty($auth), 403);

// Getting metadata
$metadata = Upload::getMetadata($request->route()->parameter('bundle'));
Expand All @@ -39,7 +39,7 @@ public function handle(Request $request, Closure $next): Response
abort_if(empty($metadata), 404);

// Aborting if auth_token is different from URL param
abort_if($metadata['owner_token'] !== $auth, 401);
abort_if($metadata['owner_token'] !== $auth, 403);

return $next($request);
}
Expand Down
10 changes: 8 additions & 2 deletions app/Http/Middleware/UploadAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,14 @@ class UploadAccess
*/
public function handle(Request $request, Closure $next): Response
{
if (Upload::canUpload($request->ip()) !== true) {
abort(401);
if ($request->session()->missing('authenticated') && Upload::canUpload($request->ip()) !== true) {
//return redirect('login');
if ($request->ajax()) {
abort(401);
}
else {
return response()->view('login');
}
}

return $next($request);
Expand Down
16 changes: 16 additions & 0 deletions config/filesystems.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@
]
],

'users' => [
'driver' => 'local',
'root' => env('STORAGE_PATH', storage_path('app/users')),
'visibility' => 'private',
'permissions' => [
'file' => [
'public' => 0600,
'private' => 0600,
],
'dir' => [
'public' => 0755,
'private' => 0700,
],
]
],

's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
Expand Down
6 changes: 5 additions & 1 deletion lang/en/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@
'expired' => 'Expired',
'existing-bundles' => 'Your existing bundles',
'or-create' => 'New bundle',
'no-existing-bundle' => 'No existing bundle'
'no-existing-bundle' => 'No existing bundle',
'authentication' => 'Authentication',
'login' => 'Username',
'password' => 'Password',
'do-login' => 'Login now'


];
6 changes: 5 additions & 1 deletion lang/fr/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@
'expired' => 'Expirés',
'existing-bundles' => 'Vos archives existantes',
'or-create' => 'Nouvelle archive',
'no-existing-bundle' => 'Aucune archive existante'
'no-existing-bundle' => 'Aucune archive existante',
'authentication' => 'Authentification',
'login' => 'Identifiant',
'password' => 'Mot de passe',
'do-login' => 'S\'authentifier'


];
38 changes: 24 additions & 14 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,45 +1,39 @@
# Files Sharing

> !!!
>
> FILES SHARING VERSION 2 JUST RELEASED
> !!!
>
<p align="center"><img src="https://github.com/axeloz/filesharing/raw/main/public/images/capture.gif" width="700" /></p>

Powered by Laravel
Powered by
<p><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></p>

## Description

This PHP application based on Laravel 10.9 allows to share files like Wetransfer. You may install it **on your own server**. It **does not require** any database system, it works with JSON files into the storage folder. It is **multilingual** and comes with english and french translations for now. You're welcome to help translating the app.

It comes with a droplet. You may drag and drop some files or directories into the droplet, your files will be uploaded to the server as a bundle.

A bundle is like a package containing a various number of files. You may choose the expiration date of the bundle.

This application provides two links per bundle :
- a bundle preview link : you can send this link to your recipients who will see the bundle content. For example: http://yourdomain/bundle/dda2d646b6746b96ea9b?auth=965242. The recipient can see all the files of the bundle, can download one given file only or the entire bundle.
- a bundle download link : you can send this link yo your recipients who will download all the files of the bundle at once (without any preview). For example: http://yourdomain/bundle/dda2d646b6746b96ea9b/download?auth=965242.

Each of these links comes with an authorization code. This code is the same for the preview and the download links. However it is different for the deletion link for obvious reasons.
Each of these links comes with an authorization code. This code is the same for the preview and the download links.

The application also comes with a Laravel Artisan command as a background task who will physically remove expired bundle files of the storage disk. This command is configured to run every five minutes among the Laravel scheduled commands.

Sorry about the design, I'm not very good at this, you're welcome to help and participate.

## Features

- uploader access permission: IP based or login/password
- creation of a new bundle
- define settings : title, description, expiration date, number max of downloads, password...
- upload one or more files via drag and drop or via browsing your computer
- upload one or more files via drag and drop or via browsing your filesystem
- ability to keep adding files to the bundle days later
- sharing link with bundle content preview
- ability to download the entire bundle as ZIP archive (password protected when applicable)
- direct download link (doesn't preview the bundle content)
- garbage collector which removes the expired bundles as a background task
- multilingual (EN and FR)
- easy installation, **no database required**
- upload limitation based on client IP filtering
- secured by tokens, authentication codes and non-publicly-accessible files

## Requirements
Expand Down Expand Up @@ -76,7 +70,9 @@ The application also uses:
- make sure that the PHP process has write permission on the `./storage` folder
- generate the Laravel KEY: `php artisan key:generate`
- run `cp .env.example .env` and edit `.env` to fit your needs
- start the Laravel scheduler (it will delete expired bundles of the storage). For example `0 * * * * /usr/bin/php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1`
- (optional) you may create your first user `php artisan fs:create-user`
- start the Laravel scheduler (it will delete expired bundles of the storage). For example `* * * * * /usr/bin/php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1`
- (optional) to purge bundles manually, run `php artisan fs:purge-expired`


Use your browser to navigate to your domain name (example: files.yourdomain.com) and **that's it**.
Expand All @@ -96,6 +92,21 @@ In order to configure your application, copy the .env.example file into .env. Th
| `UPLOAD_LIMIT_IPS` | (*optional*) a comma separated list of IPs from which you may upload files. Different formats are supported : Full IP address (192.168.10.2), Wildcard format (192.168.10.*), CIDR Format (192.168.10/24 or 1.2.3.4/255.255.255.0) or Start-end IP (192.168.10.0-192.168.10.10). When missing, filtering is disabled. |
| `APP_NAME` | the title of the application |


## Authentication

You may provide a list of IPs to limit access to the upload feature.
Or you can create users with login/password credentials.
You can also **mix the two methods**.

>
> Warning: if your leave the `UPLOAD_LIMIT_IPS` empty and you don't create users, the upload will be publicly accessible
>
## Known issues

If you are using Nginx, you might be required to do additional setup in order to increase the upload max size. Check the Nginx's documentation for `client_max_body_size`.

## Development

If your want to modify the sources, you can use the Laravel Mix features:
Expand All @@ -109,7 +120,6 @@ If your want to modify the sources, you can use the Laravel Mix features:
## Roadmap / Ideas / Improvements

There are many ideas to come. You are welcome to **participate**.
- limit upload permission by a password (or passwords)
- add PHP unit testing
- more testing on heavy files
- customizable / white labeling (logo, name, terms of service, footer ...)
Expand Down
Loading

0 comments on commit 879242c

Please sign in to comment.