Compare commits

..

No commits in common. "master" and "ticket717" have entirely different histories.

214 changed files with 8674 additions and 10122 deletions

View file

@ -42,9 +42,3 @@ MAILJET_APISECRET=
MAILJET_SMSTOKEN= MAILJET_SMSTOKEN=
MAILJET_SMSENDPOINT= MAILJET_SMSENDPOINT=
MAILJET_SMSFROM= MAILJET_SMSFROM=
WEBHOOKS_GITLAB_NOTIFY=
WEBHOOKS_GITLAB_TOKEN=
MEMCACHED_HOST=
MEMCACHED_PORT=

16
.gitignore vendored
View file

@ -3,29 +3,17 @@
/public/storage /public/storage
/public/css /public/css
/public/js /public/js
/public/images
/public/fonts /public/fonts
/public/medias /public/webfonts
/public/uploads
/public/assets /public/assets
/public/cache
/public/mix-manifest.json /public/mix-manifest.json
/storage/*.key /storage/*.key
/vendor /vendor
.env .env
.env.backup .env.backup
.phpunit.result.cache .phpunit.result.cache
docker-compose.override.yml
Homestead.json Homestead.json
Homestead.yaml Homestead.yaml
npm-debug.log npm-debug.log
yarn-error.log yarn-error.log
/.idea .idea/
/.vscode
/public/.htpasswd
/public/.htaccess
/resourcesLegacy

View file

@ -1,54 +0,0 @@
stages:
- Security
- CodingStandards
composer-security:
stage: Security
image: $CI_REGISTRY/service-web-lab/ldc-web-images-docker/ldcweb-qa:php7.3-1.0
script:
- local-php-security-checker --format=json --path=./composer.lock > composer-security-checker-report.json
artifacts:
when: on_failure
expose_as: 'composer-security-checker'
paths:
- composer-security-checker-report.json
allow_failure: true
needs: []
npm-security:
stage: Security
image: node:17.9.1
before_script:
- npm install --location=global audit-ci@^6
script:
- audit-ci -p npm -o json > npm-security-checker-report.json
artifacts:
when: on_failure
expose_as: 'npm-security-checker'
paths:
- npm-security-checker-report.json
allow_failure: true
needs: []
phpcs:
stage: CodingStandards
image: $CI_REGISTRY/service-web-lab/ldc-web-images-docker/ldcweb-qa:php7.3-1.0
before_script:
- composer config gitlab-token.gitlab.com $CI_DEPLOY_USER $CI_DEPLOY_PASSWORD
- composer install
cache:
paths:
- vendor/
script:
- vendor/bin/phpcs --report=junit --report-file=phpcs-report.xml
artifacts:
when: on_failure
expose_as: 'phpcs'
paths:
- phpcs-report.xml
reports:
junit: phpcs-report.xml
allow_failure: false
needs:
- composer-security
- npm-security

23
.vscode/settings.json vendored
View file

@ -1,23 +0,0 @@
{
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#385567",
"activityBar.activeBorder": "#b06e97",
"activityBar.background": "#385567",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#b06e97",
"activityBarBadge.foreground": "#15202b",
"sash.hoverBorder": "#385567",
"statusBar.background": "#263a46",
"statusBar.foreground": "#e7e7e7",
"statusBarItem.hoverBackground": "#385567",
"statusBarItem.remoteBackground": "#263a46",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#263a46",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#263a4699",
"titleBar.inactiveForeground": "#e7e7e799",
"commandCenter.border": "#e7e7e799"
},
"peacock.remoteColor": "#263a46"
}

View file

@ -1,12 +1,78 @@
# LDC WEB <p align="center"><img src="https://res.cloudinary.com/dtfbvvkyp/image/upload/v1566331377/laravel-logolockup-cmyk-red.svg" width="400"></p>
## Installation
``` <p align="center">
cp .env.example .env <a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
php artisan key:generate <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
``` <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
## Front <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
``` </p>
npm install && npm run prod
``` ## About Laravel
## Dependencies
- Memcached Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[British Software Development](https://www.britishsoftware.co)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- [UserInsights](https://userinsights.com)
- [Fragrantica](https://www.fragrantica.com)
- [SOFTonSOFA](https://softonsofa.com/)
- [User10](https://user10.com)
- [Soumettre.fr](https://soumettre.fr/)
- [CodeBrisk](https://codebrisk.com)
- [1Forge](https://1forge.com)
- [TECPRESSO](https://tecpresso.co.jp/)
- [Runtime Converter](http://runtimeconverter.com/)
- [WebL'Agence](https://weblagence.com/)
- [Invoice Ninja](https://www.invoiceninja.com)
- [iMi digital](https://www.imi-digital.de/)
- [Earthlink](https://www.earthlink.ro/)
- [Steadfast Collective](https://steadfastcollective.com/)
- [We Are The Robots Inc.](https://watr.mx/)
- [Understand.io](https://www.understand.io/)
- [Abdel Elrafa](https://abdelelrafa.com)
- [Hyper Host](https://hyper.host)
- [Appoly](https://www.appoly.co.uk)
- [OP.GG](https://op.gg)
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View file

@ -1,117 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* Creates a new user
*/
class CreateAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:create';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a backend admin user';
/**
* Execute the console command.
*
* @return integer
*/
public function handle()
{
$email = $this->getInput(
'Type the wanted user email',
'email',
'required|ends_with:@ldc.fr|unique:users,email|email:rfc,dns',
'equipe.web@ldc.fr'
);
$firstname = $this->getInput(
'Type the wanted user firstname',
'firstname',
'required|min:5,max:255',
'Saitama'
);
$lastname = $this->getInput(
'Type the wanted user lastname',
'lastname',
'required|min:5,max:255',
'Hagemanto'
);
$phone = $this->getInput(
'Type the wanted user phone',
'phone',
'required|phone:FR|unique:users,phone|min:5,max:255'
);
$password = null;
while (
($password = $this->secret(
(!\is_null($password) ? 'Failed to confirm, ' : '') . 'Type the wanted user password'
)) !== $this->secret('Confirm the password')
) {
continue;
};
$admin = new User([
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email,
'phone' => $phone,
'password' => $password,
'equipe_web_member' => $this->confirm('Is the user an member of equipe web ?')
]);
$admin->saveOrFail();
$this->info('User created.');
return 0;
}
/**
* Get User Input
*
* @param string $message
* @param string $inputName
* @param string|array $rules
* @param string|null $defaultValue
* @return mixed
*/
private function getInput(string $message, string $inputName, $rules, ?string $defaultValue = null)
{
$out = null;
while (is_null($out)) {
try {
$tmp = $this->ask($message, $defaultValue);
$validator = Validator::make([$inputName => $tmp], [
$inputName => $rules
]);
$validator->validate();
$out = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
"'Please provide a valid $inputName %s'",
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
return $out;
}
}

View file

@ -2,11 +2,13 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\LDCNetwork; use App\Models\DatastorePcc;
use App\Models\Project; use App\Models\DomainNames;
use App\Models\Server; use App\Models\GitRepos;
use App\Models\LDCNetworks;
use App\Models\Projects;
use App\Models\Servers;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
class ExportDatas extends Command class ExportDatas extends Command
@ -25,30 +27,50 @@ class ExportDatas extends Command
*/ */
protected $description = 'Export data in Excel format'; protected $description = 'Export data in Excel format';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/** /**
* Execute the console command. * Execute the console command.
* *
* @return integer * @return int
*/ */
public function handle() public function handle()
{ {
$this->exportProjects("EDL_WEB.csv"); $this->ExportProjects("EDL_WEB.csv");
$this->exportServers("EDL_Servers.csv"); $this->ExportServers("EDL_Servers.csv");
$this->exportLdcNetworks("EDL_LDC_Networks.csv"); $this->ExportDatastorePcc("EDL_Datastore_pcc.csv");
$this->ExportDomainNames("EDL_Domain_Names.csv");
$this->ExportLdcNetworks("EDL_LDC_Networks.csv");
$this->ExportGitRepos("EDL_GIT_Repos.csv");
return 0; return 0;
} }
/** private function ExportGitRepos($filename)
* Export ldc networks as filename.csv
*
* @param string $filename
* @return void
*/
private function exportLdcNetworks(string $filename)
{ {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\LDCNetwork> */ $repos = GitRepos::orderBy('name', 'ASC')->get();
$networks = LDCNetwork::all(); Storage::disk('export')->append($filename, "Nom");
foreach ($repos as $repo) {
$infos = [
trim($repo->name),
];
Storage::disk('export')->append($filename, implode(";", $infos));
}
}
private function ExportLdcNetworks($filename)
{
$networks = LDCNetworks::all();
Storage::disk('export')->append($filename, "CIDR;First IP;Last IP"); Storage::disk('export')->append($filename, "CIDR;First IP;Last IP");
foreach ($networks as $network) { foreach ($networks as $network) {
$infos = [ $infos = [
@ -61,20 +83,44 @@ class ExportDatas extends Command
} }
} }
/** private function ExportDomainNames($filename)
* Export servers as filename.csv
*
* @param string $filename
* @return void
*/
private function exportServers(string $filename)
{ {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Server> */ $domains = DomainNames::all();
$servers = Server::orderBy('env', 'DESC')->get(); Storage::disk('export')->append($filename, "ASCII;UTF-8;DATE D'EXPIRATION;RENOUVELLEMENT;MARQUE REF.;DNS REDIRIGES;TYPE CERTIFICATS;COMMENTAIRE");
Storage::disk('export')->append( foreach ($domains as $domain) {
$filename, $infos = [
"ENV;NOM;TITRE;FUNCTION;SSH;IP INFRAWEB;VIRTUAL IP;COMMENTAIRE" trim($domain->ascii_name),
); trim($domain->utf8_name),
trim($domain->expiration_date),
$domain->renew === 1 ? 'OUI' : 'NON',
trim($domain->related_brand),
trim($domain->redirect_dns),
trim($domain->certificats),
trim($domain->comment),
];
Storage::disk('export')->append($filename, implode(";", $infos));
}
}
private function ExportDatastorePcc($filename)
{
$datastores = DatastorePcc::all();
Storage::disk('export')->append($filename, "NOM;COMMENTAIRE");
foreach ($datastores as $datastore) {
$infos = [
trim($datastore->title),
trim($datastore->comment)
];
Storage::disk('export')->append($filename, implode(";", $infos));
}
}
private function ExportServers($filename)
{
$servers = Servers::orderBy('env', 'DESC')->get();
Storage::disk('export')->append($filename, "ENV;NOM;TITRE;FUNCTION;SSH;IP INFRAWEB;VIRTUAL IP;DATASTORE PCC;COMMENTAIRE");
foreach ($servers as $server) { foreach ($servers as $server) {
$infos = [ $infos = [
trim($server->env), trim($server->env),
@ -84,6 +130,7 @@ class ExportDatas extends Command
trim($server->ssh), trim($server->ssh),
trim($server->infraweb_ip), trim($server->infraweb_ip),
trim($server->virtual_ip), trim($server->virtual_ip),
!is_null($server->datastore_pcc_id) ? trim(DatastorePcc::find($server->datastore_pcc_id)->title) : '',
trim($server->comment) trim($server->comment)
]; ];
@ -91,16 +138,9 @@ class ExportDatas extends Command
} }
} }
/** private function ExportProjects($filename)
* Export projects as filename.csv
*
* @param string $filename
* @return void
*/
private function exportProjects(string $filename)
{ {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Project> */ $projects = Projects::orderBy('name', 'ASC')->get();
$projects = Project::orderBy('name', 'ASC')->get();
$fields = [ $fields = [
'DEV', 'DEV',
'name', 'name',
@ -123,11 +163,7 @@ class ExportDatas extends Command
'dev_whitelist_fw', 'dev_whitelist_fw',
]; ];
Storage::disk('export')->append( Storage::disk('export')->append($filename, "ENV;NOM;ID HAPROXY;URL;HTTPS;PHP;SERVEUR WEB;SSH;USER UNIX;PWD UNIX;DOCUMENT ROOT;SERVEUR BDD;SSH;USER DB;PWD DB;HTACCESS USER;HTACCESS PWD;COMMENTAIRE;FLUX EAI;WHITELIST FW");
$filename,
// phpcs:ignore
"ENV;NOM;ID HAPROXY;URL;HTTPS;PHP;SERVEUR WEB;SSH;USER UNIX;PWD UNIX;DOCUMENT ROOT;SERVEUR BDD;SSH;USER DB;PWD DB;HTACCESS USER;HTACCESS PWD;COMMENTAIRE;FLUX EAI;WHITELIST FW"
);
$this->writeProjectExport($projects, $fields, $filename); $this->writeProjectExport($projects, $fields, $filename);
$prod = implode(";", $fields); $prod = implode(";", $fields);
@ -140,17 +176,8 @@ class ExportDatas extends Command
$this->writeProjectExport($projects, $fields, $filename); $this->writeProjectExport($projects, $fields, $filename);
} }
/** private function writeProjectExport($projects, $fields, $filename)
* Append Project to filename.csv
*
* @param Collection $projects
* @param string[] $fields
* @param string $filename
* @return void
*/
private function writeProjectExport(Collection $projects, array $fields, string $filename)
{ {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Project> $projects */
foreach ($projects as $project) { foreach ($projects as $project) {
$infos = []; $infos = [];
foreach ($fields as $field) { foreach ($fields as $field) {
@ -166,7 +193,7 @@ class ExportDatas extends Command
case 'dev_db_server_id': case 'dev_db_server_id':
case 'prod_web_server_id': case 'prod_web_server_id':
case 'prod_db_server_id': case 'prod_db_server_id':
$server = Server::find($project->{$field}); $server = Servers::find($project->{$field});
$infos[] = trim($server->name); $infos[] = trim($server->name);
$infos[] = trim($server->ssh); $infos[] = trim($server->ssh);
break; break;
@ -175,9 +202,9 @@ class ExportDatas extends Command
break; break;
default: default:
$infos[] = trim($project->{$field}); $infos[] = trim($project->{$field});
}//end switch }
}//end foreach }
Storage::disk('export')->append($filename, implode(";", $infos)); Storage::disk('export')->append($filename, implode(";", $infos));
}//end foreach }
} }
} }

View file

@ -7,6 +7,15 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/** /**
* Define the application's command schedule. * Define the application's command schedule.
* *
@ -15,6 +24,8 @@ class Kernel extends ConsoleKernel
*/ */
protected function schedule(Schedule $schedule) protected function schedule(Schedule $schedule)
{ {
// $schedule->command('inspire')
// ->hourly();
} }
/** /**

View file

@ -1,40 +0,0 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnumRoutable;
/**
* SMTP Types
*
* @method static self DEV()
* @method static self PROD()
*/
final class Environment extends BaseEnumRoutable
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'DEV' => 0,
'PROD' => 1,
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'DEV' => 'Developpement',
'PROD' => 'Production'
];
}
}

View file

@ -1,49 +0,0 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnumRoutable;
/**
* Servers Different Types
*
* @method static self v5_6()
* @method static self v7_3()
* @method static self v7_4()
* @method static self v8()
* @method static self v8_1()
*/
final class PhpVersion extends BaseEnumRoutable
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'v5_6' => 0,
'v7_3' => 1,
'v7_4' => 2,
'v8' => 3,
'v8_1' => 4
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'v5_6' => 'PHP 5.6',
'v7_3' => 'PHP 7.3',
'v7_4' => 'PHP 7.4',
'v8' => 'PHP 8',
'v8_1' => 'PHP 8.1'
];
}
}

View file

@ -12,13 +12,8 @@ use Kwaadpepper\Enum\BaseEnumRoutable;
* @method static self laravel() Laravel * @method static self laravel() Laravel
* @method static self symfony() Symfony * @method static self symfony() Symfony
*/ */
final class ProjectType extends BaseEnumRoutable final class ProjectTypes extends BaseEnumRoutable
{ {
/**
* Enum values
*
* @return array
*/
protected static function values(): array protected static function values(): array
{ {
return [ return [
@ -29,11 +24,6 @@ final class ProjectType extends BaseEnumRoutable
]; ];
} }
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array protected static function labels(): array
{ {
return [ return [

View file

@ -1,43 +0,0 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnumRoutable;
/**
* Servers Different Types
*
* @method static self DB()
* @method static self WEB()
* @method static self ELASTIC()
*/
final class ServerType extends BaseEnumRoutable
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'DB' => 0,
'WEB' => 1,
'ELASTIC' => 2
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'DB' => trans('Base de données'),
'WEB' => trans('WEB'),
'ELASTIC' => trans('Eslatic Search')
];
}
}

View file

@ -11,13 +11,8 @@ use Kwaadpepper\Enum\BaseEnumRoutable;
* @method static self mailjet() Mailjet Relay * @method static self mailjet() Mailjet Relay
* @method static self sendinblue() Sendinblue Relay * @method static self sendinblue() Sendinblue Relay
*/ */
final class SmtpEnum extends BaseEnumRoutable final class Smtp extends BaseEnumRoutable
{ {
/**
* Enum values
*
* @return array
*/
protected static function values(): array protected static function values(): array
{ {
return [ return [
@ -27,11 +22,6 @@ final class SmtpEnum extends BaseEnumRoutable
]; ];
} }
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array protected static function labels(): array
{ {
return [ return [

View file

@ -2,37 +2,55 @@
namespace App\Exceptions; namespace App\Exceptions;
use Kwaadpepper\ExceptionHandler\Exceptions\ExceptionHandler;
use Throwable; use Throwable;
use Kwaadpepper\ExceptionHandler\Exceptions\ExceptionHandler;
use Illuminate\Support\Facades\Mail;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
{ {
/** /**
* A list of the exception types that are not reported. * A list of the exception types that are not reported.
* *
* @var array<int, class-string<Throwable>> * @var array
*/ */
protected $dontReport = []; protected $dontReport = [
//
];
/** /**
* A list of the inputs that are never flashed for validation exceptions. * A list of the inputs that are never flashed for validation exceptions.
* *
* @var array<int, string> * @var array
*/ */
protected $dontFlash = [ protected $dontFlash = [
'current_password',
'password', 'password',
'password_confirmation', 'password_confirmation',
]; ];
/** /**
* Register the exception handling callbacks for the application. * Report or log an exception.
* *
* @param \Throwable $exception
* @return void * @return void
*
* @throws \Throwable
*/ */
public function register() public function report(Throwable $e)
{ {
$this->reportable(function (Throwable $e) { parent::report($e);
}); }
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function render($request, Throwable $exception)
{
return parent::render($request, $exception);
} }
} }

View file

@ -3,20 +3,20 @@
namespace App\Http\Controllers\API; namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\LDCNetwork; use App\Models\LDCNetworks;
use Illuminate\Http\Request;
class LDCNetworksController extends Controller class LDCNetworksController extends Controller
{ {
/** public function index(Request $request) {
* Api LDC Networks $token = $request->token;
*
* @return \Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory if ($token !== 'CE8S52Qq7stf5k8frF4T')
*/ return response('Unauthorized', 401);
public function index()
{
$ips = []; $ips = [];
$networks = LDCNetwork::all(); $networks = LDCNetworks::all();
foreach ($networks as $network) { foreach ($networks as $network) {
$infos = explode('.', $network->first_ip); $infos = explode('.', $network->first_ip);
$min = $infos[3]; $min = $infos[3];

View file

@ -3,25 +3,44 @@
namespace App\Http\Controllers\API; namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Http\Requests\Api\UpdateProjectStatusRequest; use App\Models\Projects;
use App\Models\ProjectStatusChecker; use App\Models\ProjectsStatusChecker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class StatusCheckerController extends Controller class StatusCheckerController extends Controller
{ {
/** public function index(Request $request) {
* Undocumented function $token = $request->token;
* $datas = $request->datas;
* @param \App\Http\Requests\Api\UpdateProjectStatusRequest $request
* @return \Illuminate\Http\Response|\Illuminate\Contracts\Routing\ResponseFactory
*/
public function index(UpdateProjectStatusRequest $request)
{
/** @var \App\Models\ProjectStatusChecker */
$project_sc = ProjectStatusChecker::where('project_uuid', '=', $request->project_uuid)
->firstOrNew();
$project_sc->fill($request->validated()); if ($token !== 'CE8S52Qq7stf5k8frF4T')
$project_sc->last_call = \now(); return response('Unauthorized', 401);
return $project_sc->save() ? response('OK') : response('KO');
$oDatas = json_decode($datas);
$app_uuid = $oDatas->uuid;
$sitemap = $oDatas->sitemap;
$robots = $oDatas->robots;
$code = json_encode($oDatas->code);
$logs = $oDatas->logs;
$project_sc = ProjectsStatusChecker::where('project_uuid', '=', $app_uuid)->first();
if (!$project_sc) {
$project = Projects::where('uuid', '=', $app_uuid)->first();
if (!$project)
return response('Unknown', 404);
$project_sc = new ProjectsStatusChecker();
$project_sc->project_uuid = $app_uuid;
}
$project_sc->code = $code;
$project_sc->sitemap = $sitemap;
$project_sc->robots = $robots;
$project_sc->logs = $logs;
$project_sc->updated_at = NOW();
$project_sc->save();
return response('OK');
} }
} }

View file

@ -9,7 +9,5 @@ use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController class Controller extends BaseController
{ {
use AuthorizesRequests; use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
use DispatchesJobs;
use ValidatesRequests;
} }

View file

@ -0,0 +1,80 @@
<?php
namespace App\Http\Controllers;
use App\Models\DatastorePcc;
use App\Models\Servers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class DatastorePCCController extends Controller
{
public function index(Request $request) {
$dpccs = DatastorePcc::all();
return view('dpccs.index', ['dpccs' => $dpccs]);
}
public function add(Request $request) {
return view('dpccs.add');
}
public function edit(Request $request) {
$dpcc_id = $request->id;
$dpcc = DatastorePcc::findOrFail($dpcc_id);
return view('dpccs.edit', ['dpcc' => $dpcc]);
}
public function update(Request $request) {
$dpcc_id = $request->id;
$dpcc = DatastorePcc::findOrFail($dpcc_id);
$this->makeChanges($request, $dpcc);
return redirect()->route('dpccs.edit', ['id' => $dpcc->id])->with('status', 'Sauvegardé !');
}
public function store(Request $request) {
$dpcc = new DatastorePcc();
$this->makeChanges($request, $dpcc);
return redirect()->route('dpccs.edit', ['id' => $dpcc->id])->with('status', 'Sauvegardé !');
}
public function delete(Request $request) {
$dpcc_id = $request->id;
$dpcc = DatastorePcc::findOrFail($dpcc_id);
$isUsed = Servers::where('datastore_pcc_id', '=', $dpcc->id)->get();
if ($isUsed->count() === 0)
$isUsed = false;
return view('dpccs.delete', ['dpcc' => $dpcc, 'isUsed' => $isUsed]);
}
public function forceDelete(Request $request)
{
$dpcc_id = $request->id;
$otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$dpcc = DatastorePcc::findOrFail($dpcc_id);
$dpcc->delete();
return redirect()->route('dpccs.index')->with('status', 'Datastore PCC supprimé !');
}else{
return redirect()->route('dpccs.edit', ['id' => $dpcc_id])->with('error', 'Code de vérification invalide.');
}
}
private function makeChanges($request, $dpcc) {
$title = $request->title;
$comment = $request->comment;
$dpcc->title = $title;
$dpcc->comment = $comment;
$dpcc->save();
}
}

View file

@ -0,0 +1,98 @@
<?php
namespace App\Http\Controllers;
use App\Models\DomainNames;
use App\Models\EmailAddresses;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class DomainNamesController extends Controller
{
public function index(Request $request)
{
$dms = DomainNames::all();
return view('domain-names.index', ['dms' => $dms]);
}
public function add(Request $request)
{
return view('domain-names.add');
}
public function edit(Request $request)
{
$dm_id = $request->id;
$dm = DomainNames::findOrFail($dm_id);
return view('domain-names.edit', ['dm' => $dm]);
}
public function update(Request $request)
{
$dm_id = $request->id;
$dm = DomainNames::findOrFail($dm_id);
$this->makeChanges($request, $dm);
return redirect()->route('domain-names.edit', ['id' => $dm->id])->with('status', 'Sauvegardé !');
}
public function store(Request $request)
{
$dm = new DomainNames();
$this->makeChanges($request, $dm);
return redirect()->route('domain-names.edit', ['id' => $dm->id])->with('status', 'Sauvegardé !');
}
public function delete(Request $request)
{
$dm_id = $request->id;
$dm = DomainNames::findOrFail($dm_id);
$isUsed = EmailAddresses::where('domain_name_id', '=', $dm->id)->get();
if ($isUsed->count() === 0)
$isUsed = false;
return view('domain-names.delete', ['dm' => $dm, 'isUsed' => $isUsed]);
}
public function forceDelete(Request $request)
{
$dm_id = $request->id;
$otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$dm = DomainNames::findOrFail($dm_id);
$dm->delete();
return redirect()->route('domain-names.index')->with('status', 'Nom de domaine supprimé !');
} else {
return redirect()->route('domain-names.edit', ['id' => $dm_id])->with('error', 'Code de vérification invalide.');
}
}
private function makeChanges($request, $dm)
{
$ascii_name = $request->ascii_name;
$utf8_name = $request->utf8_name;
$exp_date = $request->expiration_date;
$renew = $request->renew;
$related_brand = $request->related_brand;
$redirect_dns = $request->redirect_dns;
$certificats = $request->certificats;
$comment = $request->comment;
$dm->ascii_name = $ascii_name;
$dm->utf8_name = $utf8_name;
$dm->expiration_date = $exp_date;
$dm->renew = $renew;
$dm->related_brand = $related_brand;
$dm->redirect_dns = $redirect_dns;
$dm->certificats = $certificats;
$dm->comment = $comment;
$dm->save();
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace App\Http\Controllers;
use App\Models\DomainNames;
use App\Models\EmailAddresses;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class EmailAddressesController extends Controller
{
public function index(Request $request) {
$emails = EmailAddresses::all();
return view('email-addresses.index', ['emails' => $emails]);
}
public function add(Request $request) {
$dms = DomainNames::orderBy('utf8_name')->get();
return view('email-addresses.add', ['dms' => $dms]);
}
public function edit(Request $request) {
$email_id = $request->id;
$email = EmailAddresses::findOrFail($email_id);
$dms = DomainNames::orderBy('utf8_name')->get();
return view('email-addresses.edit', ['email' => $email, 'dms' => $dms]);
}
public function update(Request $request) {
$email_id = $request->id;
$email = EmailAddresses::findOrFail($email_id);
$this->makeChanges($request, $email);
return redirect()->route('email-addresses.edit', ['id' => $email->id])->with('status', 'Sauvegardée !');
}
public function store(Request $request) {
$email = new EmailAddresses();
$this->makeChanges($request, $email);
return redirect()->route('email-addresses.edit', ['id' => $email->id])->with('status', 'Sauvegardée !');
}
public function delete(Request $request) {
$email_id = $request->id;
$email = EmailAddresses::findOrFail($email_id);
return view('email-addresses.delete', ['email' => $email]);
}
public function forceDelete(Request $request)
{
$email_id = $request->id;
$otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$email = EmailAddresses::findOrFail($email_id);
$email->delete();
return redirect()->route('email-addresses.index')->with('status', 'Adresse email supprimée !');
}else{
return redirect()->route('email-addresses.edit', ['id' => $email_id])->with('error', 'Code de vérification invalide.');
}
}
private function makeChanges($request, $email) {
$account = $request->account;
$password = $request->password;
$domain_name_id = $request->d_n_id;
$email->account = $account;
$email->password = $password;
$email->domain_name_id = $domain_name_id;
$email->save();
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\GitReposStoreRequest;
use App\Http\Requests\GitReposUpdateRequest;
use App\Models\GitRepos;
class GitReposController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$repos = GitRepos::all();
return view('git-repos.index', compact('repos'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('git-repos.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\GitReposStoreRequest $request
* @return \Illuminate\Http\Response
*/
public function store(GitReposStoreRequest $request)
{
$datas = $request->validated();
$git_repo = new GitRepos();
$git_repo->fill($datas);
$git_repo->save();
return redirect()->route('git-repos.edit', ['git_repo' => $git_repo])->with('status', __('Dépôt Git créé.'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
abort('404');
}
/**
* Show the form for editing the specified resource.
*
* @param GitRepos $git_repo
* @return \Illuminate\Http\Response
*/
public function edit(GitRepos $git_repo)
{
return view('git-repos.edit', compact('git_repo'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\GitReposUpdateRequest $request
* @param GitRepos $git_repo
* @return \Illuminate\Http\Response
*/
public function update(GitReposUpdateRequest $request, GitRepos $git_repo)
{
$datas = $request->validated();
$git_repo->fill($datas);
$git_repo->save();
return redirect()->route('git-repos.edit', ['git_repo' => $git_repo])->with('status', __('Dépôt Git mis à jour.'));
}
/**
* Remove the specified resource from storage.
*
* @param GitRepos $git_repo
* @return \Illuminate\Http\Response
*/
public function destroy(GitRepos $git_repo)
{
$git_repo->delete();
return redirect()->route('git-repos.index')->with('status', __('Dépôt Git supprimé.'));
}
}

View file

@ -2,7 +2,9 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\{Base32,Totp};
use SimpleSoftwareIO\QrCode\Facades\QrCode; use SimpleSoftwareIO\QrCode\Facades\QrCode;
class HomeController extends Controller class HomeController extends Controller
@ -12,26 +14,19 @@ class HomeController extends Controller
* *
* @return \Illuminate\Contracts\Support\Renderable * @return \Illuminate\Contracts\Support\Renderable
*/ */
public function index() public function index(Request $request)
{ {
//$secret = Totp::GenerateSecret(16); //$secret = Totp::GenerateSecret(16);
// Display new key to user so they can enter it in Google Authenticator or Authy # Display new key to user so they can enter it in Google Authenticator or Authy
//echo strtoupper(Base32::encode($secret));exit; //echo strtoupper(Base32::encode($secret));exit;
// otpauth://totp/LDC%20WEB:mail@ldc.fr?secret=secret&issuer=LDC%20WEB // otpauth://totp/LDC%20WEB:mail@ldc.fr?secret=secret&issuer=LDC%20WEB
return view('home'); return view('home');
} }
/**
* Generate QR code
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function qr() public function qr()
{ {
$user = Auth::user(); $user = Auth::user();
$qrcode = QrCode::size(200)->generate( $qrcode = QrCode::size(200)->generate("otpauth://totp/LDC%20WEB:".$user->email."?secret=".$user->totp_secret."&issuer=LDC%20WEB");
"otpauth://totp/LDC%20WEB:$user->email?secret=$user->totp_secret&issuer=LDC%20WEB"
);
return view("qrcode", compact('qrcode')); return view("qrcode", compact('qrcode'));
} }
} }

View file

@ -2,107 +2,82 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\LDCNetworks\StoreLDCNetwork; use App\Models\LDCNetworks;
use App\Http\Requests\LDCNetworks\UpdateLDCNetwork; use Carbon\Carbon;
use App\Http\Requests\ValidateOtpRequest; use Illuminate\Http\Request;
use App\Models\LDCNetwork; use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class LDCNetworkController extends Controller class LDCNetworkController extends Controller
{ {
/** public function index(Request $request) {
* Display a listing of the resource. $networks = LDCNetworks::all();
* return view('ldc-networks.index', ['networks' => $networks]);
* @return \Illuminate\Http\Response }
*/
public function index() public function add(Request $request) {
return view('ldc-networks.add');
}
public function edit(Request $request) {
$network_id = $request->id;
$network = LDCNetworks::findOrFail($network_id);
return view('ldc-networks.edit', ['network' => $network]);
}
public function update(Request $request) {
$network_id = $request->id;
$network = LDCNetworks::findOrFail($network_id);
$this->makeChanges($request, $network);
return redirect()->route('ldc-networks.edit', ['id' => $network->id])->with('status', 'Sauvegardée !');
}
public function store(Request $request) {
$network = new LDCNetworks();
$this->makeChanges($request, $network);
return redirect()->route('ldc-networks.edit', ['id' => $network->id])->with('status', 'Sauvegardée !');
}
public function delete(Request $request) {
$network_id = $request->id;
$network = LDCNetworks::findOrFail($network_id);
return view('ldc-networks.delete', ['network' => $network]);
}
public function forceDelete(Request $request)
{ {
$ldc_networks = LDCNetwork::all(); $network_id = $request->id;
return view('ldc-networks.index', compact('ldc_networks')); $otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$network = LDCNetworks::findOrFail($network_id);
$network->delete();
return redirect()->route('ldc-networks.index')->with('status', 'IP supprimée !');
}else{
return redirect()->route('ldc-networks.edit', ['id' => $network_id])->with('error', 'Code de vérification invalide.');
}
} }
/** private function makeChanges($request, $network) {
* Show the form for creating a new resource. $cidr = $request->cidr;
* $range = $this->cidrToRange($cidr);
* @return \Illuminate\Http\Response
*/ $network->cidr = $cidr;
public function create() $network->first_ip = $range[0];
{ $network->last_ip = $range[1];
return view('ldc-networks.create'); $network->save();
} }
/** private function cidrToRange($cidr) {
* Store a newly created resource in storage. $range = array();
* $cidr = explode('/', $cidr);
* @param \App\Http\Requests\LDCNetworks\StoreLDCNetwork $request $range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
* @return \Illuminate\Http\Response $range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
*/ return $range;
public function store(StoreLDCNetwork $request)
{
$ldc_network = new LDCNetwork();
$ldc_network->fill($request->validated());
if ($ldc_network->saveOrFail()) {
return redirect()->route('ldc-networks.edit', compact('ldc_network'))
->with('success', trans('LDC Network créé.'));
}
return \back();
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\LDCNetwork $ldc_network
* @return \Illuminate\Http\Response
*/
public function edit(LDCNetwork $ldc_network)
{
return view('ldc-networks.edit', ['ldc_network' => $ldc_network]);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\LDCNetworks\UpdateLDCNetwork $request
* @param \App\Models\LDCNetwork $ldc_network
* @return \Illuminate\Http\Response
*/
public function update(UpdateLDCNetwork $request, LDCNetwork $ldc_network)
{
$ldc_network->fill($request->validated());
if ($ldc_network->saveOrFail()) {
return redirect()->route('ldc-networks.edit', compact('ldc_network'))
->with('success', trans('LDC Network mis à jour.'));
}
return \back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\LDCNetwork $ldc_network
* @return \Illuminate\Http\Response
*/
public function destroy(LDCNetwork $ldc_network)
{
return view('ldc-networks.delete', ['ldc_network' => $ldc_network]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Http\Requests\ValidateOtpRequest $request
* @param \App\Models\LDCNetwork $ldc_network
* @return \Illuminate\Http\Response
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
*/
public function destroySubmit(ValidateOtpRequest $request, LDCNetwork $ldc_network)
{
// phpcs:enable
if ($ldc_network->deleteOrFail()) {
return redirect()->route('ldc-networks.index')
->with('warning', 'LDC Network supprimé !');
}
return back();
} }
} }

View file

@ -2,79 +2,63 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\ValidateOtpRequest;
use App\Providers\RouteServiceProvider; use App\Providers\RouteServiceProvider;
use GuzzleHttp\Exception\RequestException; use Carbon\Carbon;
use lfkeitel\phptotp\Base32; use Illuminate\Http\Request;
use lfkeitel\phptotp\Totp; use lfkeitel\phptotp\{Base32,Totp};
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class OTPController extends Controller class OTPController extends Controller
{ {
/** public function verify(Request $request) {
* Show verifiy otp page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function verify()
{
$user = session()->get('tmpUserOTP'); $user = session()->get('tmpUserOTP');
if (!$user) { if (!$user)
return redirect(RouteServiceProvider::HOME); return redirect(RouteServiceProvider::HOME);
}
return view('auth.verify'); return view('auth.verify');
} }
/** public function check(Request $request) {
* Check OPT request $otp = $request->otp;
* $user = session()->get('tmpUserOTP');
* @param ValidateOtpRequest $request if (!$user)
* @return \Illuminate\Http\RedirectResponse return redirect(RouteServiceProvider::HOME);
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
*/ $lastCode = (new Totp())->GenerateToken(Base32::decode($user->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
public function check(ValidateOtpRequest $request) $code = (new Totp())->GenerateToken(Base32::decode($user->totp_secret));
{
//phpcs:enable if ($otp === $code || $otp === $lastCode) {
Auth::login(session()->get('tmpUserOTP')); Auth::login($user);
return \response()->redirectTo(RouteServiceProvider::HOME); return redirect(RouteServiceProvider::HOME);
} else {
Auth::logout();
Session::flush();
return redirect()->route('verification_failed');
}
} }
/** public function sendOTPBySMS()
* Send OPT by SMS
*
* @return \Illuminate\Http\RedirectResponse
*/
public function sendOtpBySms()
{ {
$user = session()->get('tmpUserOTP'); $user = session()->get('tmpUserOTP');
if (!$user) { if (!$user)
return back()->withErrors('User not found.'); return back()->withErrors('User not found.');
}
if (is_null($user->phone)) { if (is_null($user->phone))
return back()->withErrors('Phone number missing.'); return back()->withErrors('Phone number missing.');
}
$otp = (new Totp())->GenerateToken(Base32::decode($user->totp_secret)); $otp = (new Totp())->GenerateToken(Base32::decode($user->totp_secret));
if (!$otp) {
return back()->withErrors('Erreur lors de la génération du code OTP');
}
/** @var \App\Lib\LDC\MailjetSms */ /** @var \App\Lib\LDC\MailjetSms */
$mj = app('MailjetSms'); $mj = app('MailjetSms');
try {
$mjResponse = $mj->send("OTP : " . implode(' ', str_split($otp)), $user->phone); $mjResponse = $mj->send("OTP : " . implode(' ', str_split($otp)), $user->phone);
/** @var \GuzzleHttp\Psr7\Response $mjResponse */ /** @var \GuzzleHttp\Psr7\Response $mjResponse */
$responseStatus = $mjResponse->getStatusCode(); $responseStatus = $mjResponse->getStatusCode(); //"200"
$responsePhrase = $mjResponse->getReasonPhrase(); //"OK"
if ($responseStatus == 200) { if ($responseStatus == 200) {
return back()->with('success', 'SMS envoyé.'); $mjSmsResponse = $mjResponse->getBody()->getContents();
return back()->with('success', "SMS envoyé.");
} }
return back()->withErrors('SMS not sent.'); return back()->withErrors('SMS not sent.');
} catch (RequestException $e) {
report($e);
return back()->withErrors('Erreur lors de l\'envoi du SMS');
}
} }
} }

View file

@ -1,161 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Enums\Environment;
use App\Enums\ServerType;
use App\Http\Requests\Projects\StoreProjectRequest;
use App\Http\Requests\Projects\UpdateProjectRequest;
use App\Http\Requests\ValidateOtpRequest;
use App\Models\Project;
use App\Models\Server;
use Ramsey\Uuid\Uuid;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projects = Project::orderBy('name')->get();
return view('projects.index', ['projects' => $projects]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$dev_db_server = Server::where([
['env', Environment::DEV()],
['type', ServerType::DB()]
])->get();
$dev_web_server = Server::where([
['env', Environment::DEV()],
['type', ServerType::WEB()]
])->get();
$prod_db_server = Server::where([
['env', Environment::PROD()],
['type', ServerType::DB()]
])->get();
$prod_web_server = Server::where([
['env', Environment::PROD()],
['type', ServerType::WEB()]
])->get();
return view('projects.create', \compact(
'dev_db_server',
'dev_web_server',
'prod_db_server',
'prod_web_server'
));
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\Projects\StoreProjectRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreProjectRequest $request)
{
$project = new Project();
$project->uuid = Uuid::uuid4();
$project->fill($request->validated());
$project->dev_login = \json_decode($project->dev_login);
$project->prod_login = \json_decode($project->prod_login);
if ($project->saveOrFail()) {
return redirect()->route('projects.edit', compact('project'))
->with('success', trans('Projet ajouté.'));
}
return \back();
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
*/
public function edit(Project $project)
{
// phpcs:enable
$dev_db_server = Server::where([
['env', Environment::DEV()],
['type', ServerType::DB()]
])->get();
$dev_web_server = Server::where([
['env', Environment::DEV()],
['type', ServerType::WEB()]
])->get();
$prod_db_server = Server::where([
['env', Environment::PROD()],
['type', ServerType::DB()]
])->get();
$prod_web_server = Server::where([
['env', Environment::PROD()],
['type', ServerType::WEB()]
])->get();
return view('projects.edit', \compact(
'project',
'dev_db_server',
'dev_web_server',
'prod_db_server',
'prod_web_server'
));
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\Projects\UpdateProjectRequest $request
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function update(UpdateProjectRequest $request, Project $project)
{
$project->fill($request->validated());
$project->dev_login = \json_decode($project->dev_login);
$project->prod_login = \json_decode($project->prod_login);
if ($project->saveOrFail()) {
return redirect()->route('projects.edit', compact('project'))
->with('success', trans('Projet mis à jour.'));
}
return \back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
return view('projects.delete', ['project' => $project]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Http\Requests\ValidateOtpRequest $request
* @param \App\Models\Project $project
* @return \Illuminate\Http\Response
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
*/
public function destroySubmit(ValidateOtpRequest $request, Project $project)
{
// phpcs:enable
if ($project->deleteOrFail()) {
return redirect()->route('projects.index')
->with('warning', 'Projet supprimé !');
}
return back();
}
}

View file

@ -0,0 +1,223 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Projects\StoreProjects;
use App\Http\Requests\Projects\UpdateProjects;
use App\Models\Projects;
use App\Models\Servers;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
use Ramsey\Uuid\Uuid;
class ProjectsController extends Controller
{
public function index(Request $request)
{
$projects = Projects::orderBy('name')->get();
return view('projects.index', ['projects' => $projects]);
}
public function WpAutoLogin(Request $request)
{
$url = $request->url;
$login = $request->login;
$pwd = $request->pwd;
return view('projects.wp-auto-login', ['url' => $url, 'login' => $login, 'pwd' => $pwd]);
}
public function add(Request $request)
{
$dev_db_server = Servers::where([
['env', 'DEV'],
['type', 'DB']
])->get();
$dev_web_server = Servers::where([
['env', 'DEV'],
['type', 'WEB']
])->get();
$prod_db_server = Servers::where([
['env', 'PROD'],
['type', 'DB']
])->get();
$prod_web_server = Servers::where([
['env', 'PROD'],
['type', 'WEB']
])->get();
return view('projects.add', ['dev_db_server' => $dev_db_server, 'dev_web_server' => $dev_web_server, 'prod_db_server' => $prod_db_server, 'prod_web_server' => $prod_web_server]);
}
public function edit(Request $request)
{
$uuid = $request->uuid;
$project = Projects::where('uuid', '=', $uuid)->first();
if (!$project)
abort(404);
$dev_db_server = Servers::where([
['env', 'DEV'],
['type', 'DB']
])->get();
$dev_web_server = Servers::where([
['env', 'DEV'],
['type', 'WEB']
])->get();
$prod_db_server = Servers::where([
['env', 'PROD'],
['type', 'DB']
])->get();
$prod_web_server = Servers::where([
['env', 'PROD'],
['type', 'WEB']
])->get();
return view('projects.edit', ['project' => $project, 'dev_db_server' => $dev_db_server, 'dev_web_server' => $dev_web_server, 'prod_db_server' => $prod_db_server, 'prod_web_server' => $prod_web_server]);
}
public function update(UpdateProjects $request)
{
$uuid = $request->uuid;
$project = Projects::where('uuid', '=', $uuid)->first();
if (!$project)
abort(404);
$this->makeChanges($request, $project);
return redirect()->route('projects.edit', ['uuid' => $project->uuid])->with('status', 'Sauvegardé !');
}
public function store(StoreProjects $request)
{
$project = new Projects();
$project->uuid = Uuid::uuid4();
$this->makeChanges($request, $project);
return redirect()->route('projects.edit', ['uuid' => $project->uuid])->with('status', 'Sauvegardé !');
}
public function delete(Request $request)
{
$uuid = $request->uuid;
$project = Projects::where('uuid', '=', $uuid)->first();
if (!$project)
abort(404);
return view('projects.delete', ['project' => $project]);
}
public function forceDelete(Request $request)
{
$uuid = $request->uuid;
$otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$project = Projects::where('uuid', '=', $uuid)->first();
if (!$project)
abort(404);
$project->delete();
return redirect()->route('projects.index')->with('status', 'Projet supprimé !');
} else {
return redirect()->route('projects.edit', ['uuid' => $uuid])->with('error', 'Code de vérification invalide.');
}
}
private function makeChanges(Request $request, $project)
{
$name = $request->name;
$display_name = $request->display_name;
$php = $request->php;
$type = $request->type;
$https = $request->https;
$prod_haproxy_id = $request->prod_haproxy_id;
$dev_haproxy_id = $request->dev_haproxy_id;
$prod_url = $request->prod_url;
$dev_url = $request->dev_url;
$prod_document_root = $request->prod_document_root;
$dev_document_root = $request->dev_document_root;
$prod_unix_user = $request->prod_unix_user;
$dev_unix_user = $request->dev_unix_user;
$prod_unix_pwd = $request->prod_unix_pwd;
$dev_unix_pwd = $request->dev_unix_pwd;
$prod_db_user = $request->prod_db_user;
$dev_db_user = $request->dev_db_user;
$prod_db_pwd = $request->prod_db_pwd;
$dev_db_pwd = $request->dev_db_pwd;
$prod_db_schema = $request->prod_db_schema;
$dev_db_schema = $request->dev_db_schema;
$prod_db_server_id = $request->prod_db_server_id;
$dev_db_server_id = $request->dev_db_server_id;
$prod_web_server_id = $request->prod_web_server_id;
$dev_web_server_id = $request->dev_web_server_id;
$prod_comment = $request->prod_comment;
$dev_comment = $request->dev_comment;
$prod_eai = $request->prod_eai;
$dev_eai = $request->dev_eai;
$prod_whitelist_fw = $request->prod_whitelist_fw;
$dev_whitelist_fw = $request->dev_whitelist_fw;
$dev_htaccess_user = $request->dev_htaccess_user;
$dev_htaccess_pwd = $request->dev_htaccess_pwd;
$prod_ga_id = $request->prod_ga_id;
$prod_laravel_app_key = $request->prod_laravel_app_key;
$dev_laravel_app_key = $request->dev_laravel_app_key;
$prod_smtp_config = $request->prod_smtp_config;
$prod_smtp_key = $request->prod_smtp_key;
if (Auth::user()->role === 1) {
$prod_login = $request->prod_login;
$dev_login = $request->dev_login;
$prod_bo_url = $request->prod_bo_url;
$dev_bo_url = $request->dev_bo_url;
}
$project->name = $name;
$project->display_name = $display_name;
$project->php = $php;
$project->type = $type;
$project->https = $https;
$project->prod_haproxy_id = $prod_haproxy_id;
$project->dev_haproxy_id = $dev_haproxy_id;
$project->prod_url = $prod_url;
$project->dev_url = $dev_url;
$project->prod_document_root = $prod_document_root;
$project->dev_document_root = $dev_document_root;
$project->prod_unix_user = $prod_unix_user;
$project->dev_unix_user = $dev_unix_user;
$project->prod_unix_pwd = $prod_unix_pwd;
$project->dev_unix_pwd = $dev_unix_pwd;
$project->prod_db_user = $prod_db_user;
$project->dev_db_user = $dev_db_user;
$project->prod_db_pwd = $prod_db_pwd;
$project->dev_db_pwd = $dev_db_pwd;
$project->prod_db_schema = $prod_db_schema;
$project->dev_db_schema = $dev_db_schema;
$project->prod_db_server_id = $prod_db_server_id;
$project->dev_db_server_id = $dev_db_server_id;
$project->prod_web_server_id = $prod_web_server_id;
$project->dev_web_server_id = $dev_web_server_id;
$project->prod_comment = $prod_comment;
$project->dev_comment = $dev_comment;
$project->prod_eai = $prod_eai;
$project->dev_eai = $dev_eai;
$project->prod_whitelist_fw = $prod_whitelist_fw;
$project->dev_whitelist_fw = $dev_whitelist_fw;
$project->dev_htaccess_user = $dev_htaccess_user;
$project->dev_htaccess_pwd = $dev_htaccess_pwd;
$project->prod_ga_id = $prod_ga_id;
$project->prod_laravel_app_key = $prod_laravel_app_key;
$project->dev_laravel_app_key = $dev_laravel_app_key;
$project->prod_smtp_config = $prod_smtp_config;
$project->prod_smtp_key = $prod_smtp_key;
if (Auth::user()->role === 1) {
$project->prod_login = $prod_login;
$project->dev_login = $dev_login;
$project->prod_bo_url = $prod_bo_url;
$project->dev_bo_url = $dev_bo_url;
}
$project->save();
}
}

View file

@ -1,120 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Servers\StoreServerRequest;
use App\Http\Requests\Servers\UpdateServerRequest;
use App\Http\Requests\ValidateOtpRequest;
use App\Models\Project;
use App\Models\Server;
class ServerController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$servers = Server::all();
return view('servers.index', compact('servers'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('servers.create');
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\Servers\StoreServerRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreServerRequest $request)
{
$server = new Server();
$server->fill($request->validated());
if ($server->saveOrFail()) {
return redirect()->route('servers.edit', compact('server'))
->with('success', trans('Server créé.'));
}
return \back();
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Server $server
* @return \Illuminate\Http\Response
*/
public function edit(Server $server)
{
return view('servers.edit', ['server' => $server]);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\Servers\UpdateServerRequest $request
* @param \App\Models\Server $server
* @return \Illuminate\Http\Response
*/
public function update(UpdateServerRequest $request, Server $server)
{
$server->fill($request->validated());
if ($server->saveOrFail()) {
return redirect()->route('servers.edit', compact('server'))
->with('success', trans('Server mis à jour.'));
}
return \back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Server $server
* @return \Illuminate\Http\Response
*/
public function destroy(Server $server)
{
$isUsed = false;
if ($server->type === 'DB' || $server->type === 'WEB') {
$projects = Project::where('dev_db_server_id', '=', $server->id)
->orWhere('dev_web_server_id', '=', $server->id)
->orWhere('prod_db_server_id', '=', $server->id)
->orWhere('prod_web_server_id', '=', $server->id)
->get();
$isUsed = $projects->count() ? $projects : false;
}
return view('servers.delete', ['server' => $server, 'isUsed' => $isUsed]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Http\Requests\ValidateOtpRequest $request
* @param \App\Models\Server $server
* @return \Illuminate\Http\Response
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
*/
public function destroySubmit(ValidateOtpRequest $request, Server $server)
{
// phpcs:enable
if ($server->deleteOrFail()) {
return redirect()->route('servers.index')
->with('warning', 'Server supprimé !');
}
return back();
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace App\Http\Controllers;
use App\Models\DatastorePcc;
use App\Models\Projects;
use App\Models\Servers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class ServersController extends Controller
{
public function index(Request $request) {
$servers = Servers::all();
return view('servers.index', ['servers' => $servers]);
}
public function add(Request $request) {
$datastores_pcc = DatastorePcc::orderBy('title')->get();
return view('servers.add', ['datastores_pcc' => $datastores_pcc]);
}
public function edit(Request $request) {
$server_id = $request->id;
$server = Servers::findOrFail($server_id);
$datastores_pcc = DatastorePcc::orderBy('title')->get();
return view('servers.edit', ['server' => $server, 'datastores_pcc' => $datastores_pcc]);
}
public function update(Request $request) {
$server_id = $request->id;
$server = Servers::findOrFail($server_id);
$this->makeChanges($request, $server);
return redirect()->route('servers.edit', ['id' => $server_id])->with('status', 'Sauvegardé !');
}
public function store(Request $request) {
$server = new Servers();
$this->makeChanges($request, $server);
return redirect()->route('servers.edit', ['id' => $server->id])->with('status', 'Sauvegardé !');
}
public function delete(Request $request) {
$server_id = $request->id;
$server = Servers::findOrFail($server_id);
if ($server->type === 'DB' || $server->type === 'WEB') {
$isUsed = Projects::where('dev_db_server_id', '=', $server->id)->orWhere('dev_web_server_id', '=', $server->id)->orWhere('prod_db_server_id', '=', $server->id)->orWhere('prod_web_server_id', '=', $server->id)->get();
if ($isUsed->count() === 0)
$isUsed = false;
} else {
$isUsed = false;
}
return view('servers.delete', ['server' => $server, 'isUsed' => $isUsed]);
}
public function forceDelete(Request $request)
{
$server_id = $request->id;
$otp = $request->otp;
$lastCode = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret), Carbon::now()->subSeconds(30)->timestamp);
$code = (new Totp())->GenerateToken(Base32::decode(Auth::user()->totp_secret));
if ($otp === $code || $otp === $lastCode) {
$server = Servers::findOrFail($server_id);
$server->delete();
return redirect()->route('servers.index')->with('status', 'Serveur supprimé !');
}else{
return redirect()->route('servers.edit', ['id' => $server_id])->with('error', 'Code de vérification invalide.');
}
}
private function makeChanges($request, $server) {
$env = $request->env;
$virtual_ip = $request->virtual_ip;
$ssh = $request->ssh;
$infraweb_ip = $request->infraweb_ip;
$title = $request->title;
$name = $request->name;
$function = $request->function;
$dpcc = $request->datastore_pcc_id;
$comment = $request->comment;
$type = $request->type;
$server->env = $env;
$server->virtual_ip = $virtual_ip;
$server->ssh = $ssh;
$server->infraweb_ip = $infraweb_ip;
$server->title = $title;
$server->name = $name;
$server->function = $function;
$server->datastore_pcc_id = $dpcc;
$server->comment = $comment;
$server->type = $type;
$server->save();
}
}

View file

@ -1,110 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ServiceAccounts\StoreServiceAccountsRequest;
use App\Http\Requests\ServiceAccounts\UpdateServiceAccountsRequest;
use App\Http\Requests\ValidateOtpRequest;
use App\Models\ServiceAccount;
class ServiceAccountsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$service_accounts = ServiceAccount::all()->sortBy('name');
return view('service-accounts.index', compact('service_accounts'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('service-accounts.create');
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\ServiceAccounts\StoreServiceAccountsRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreServiceAccountsRequest $request)
{
$service_account = new ServiceAccount();
$service_account->fill($request->validated());
if ($service_account->saveOrFail()) {
return redirect()->route('service-accounts.edit', compact('service_account'))
->with('success', trans('Compte de service créé.'));
}
return \back();
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\ServiceAccount $service_account
* @return \Illuminate\Http\Response
*/
public function edit(ServiceAccount $service_account)
{
return view('service-accounts.edit', [
'service_account' => $service_account
]);
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\ServiceAccounts\UpdateServiceAccountsRequest $request
* @param \App\Models\ServiceAccount $service_account
* @return \Illuminate\Http\Response
*/
public function update(UpdateServiceAccountsRequest $request, ServiceAccount $service_account)
{
$service_account->fill($request->validated());
if ($service_account->saveOrFail()) {
return redirect()->route('service-accounts.edit', compact('service_account'))
->with('success', trans('Compte de service mis à jour.'));
}
return \back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\ServiceAccount $service_account
* @return \Illuminate\Http\Response
*/
public function destroy(ServiceAccount $service_account)
{
return view('service-accounts.delete', ['service_account' => $service_account]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Http\Requests\ValidateOtpRequest $request
* @param \App\Models\ServiceAccount $service_account
* @return \Illuminate\Http\Response
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
*/
public function destroySubmit(ValidateOtpRequest $request, ServiceAccount $service_account)
{
// phpcs:enable
if ($service_account->deleteOrFail()) {
return redirect()->route('service-accounts.index')
->with('warning', 'Compte de service supprimé !');
}
return back();
}
}

View file

@ -2,31 +2,28 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Project; use App\Models\Projects;
use Illuminate\Support\Facades\Http; use Illuminate\Http\Request;
class StatusCheckerController extends Controller class StatusCheckerController extends Controller
{ {
/** public function index(Request $request) {
* Fetch Status $wp_endpoint = 'https://api.wordpress.org/core/version-check/1.7/';
* $client = new \GuzzleHttp\Client();
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory $response = $client->request('GET', $wp_endpoint);
*/ $content = $response->getBody();
public function index() $oContent = json_decode($content);
{
$wpReleases = Http::get(config('status-checker.wp_endpoint'))->json();
$laravelReleases = Http::withOptions([
'allow_redirects' => false,
])->asJson()->get(config('status-checker.laravel_endpoint'))->json();
$wp_latest = collect(collect(\collect($wpReleases)->get('offers'))->first())->get('version'); $laravel_endpoint = 'https://github.com/laravel/laravel/releases/latest';
$laravel_latest = ltrim(collect(collect($laravelReleases)->first())->get('tag_name'), 'v'); $client = new \GuzzleHttp\Client();
$response = $client->request('GET', $laravel_endpoint, [
'allow_redirects' => false
]);
$content = $response->getBody()->getContents();
$laravel_latest = substr($content, 84);
$laravel_latest = substr($laravel_latest, 0, -31);
$projects = Project::orderBy('name')->get(); $projects = Projects::orderBy('name')->get();
return view('status-checker.index', compact( return view('status-checker.index', ['projects' => $projects, 'wp_latest' => $oContent->offers[0]->version, 'laravel_latest' => $laravel_latest]);
'projects',
'wp_latest',
'laravel_latest'
));
} }
} }

View file

@ -1,47 +0,0 @@
<?php
namespace App\Http\Controllers\Webhooks;
use App\Http\Controllers\Controller;
use App\Http\Requests\Webhooks\GitlabRequest;
use App\Mail\Webhooks\Gitlab;
use Illuminate\Support\Facades\Mail;
class GitlabController extends Controller
{
/**
* Handle gitlab request
*
* @param GitlabRequest $request
* @return void
*/
public function handle(GitlabRequest $request)
{
// TODO: Check all request inputs, before sending unvalidated data by mail.
$event_type = $request->event_type;
if ($event_type === 'merge_request') {
// Si le state est <> de opened on ne fait rien .
if ($request->object_attributes['state'] !== 'opened') {
exit;
}
// Si l'action est set et egale à approved on ne fait rien .
if (isset($request->object_attributes['action']) && $request->object_attributes['action'] === 'approved') {
exit;
}
$datas = [];
$datas['user'] = $request->user['name'];
$datas['project_name'] = $request->project['name'];
$datas['project_path'] = $request->project['path_with_namespace'];
$datas['attributes_description'] = $request->object_attributes['description'];
$datas['attributes_status'] = $request->object_attributes['merge_status'];
$datas['attributes_request_status'] = $request->object_attributes['state'];
$datas['attributes_source_branch'] = $request->object_attributes['source_branch'];
$datas['attributes_target_branch'] = $request->object_attributes['target_branch'];
$datas['attributes_url'] = $request->object_attributes['url'];
$datas['last_commit_author'] = $request->object_attributes['last_commit']['author']['name'];
Mail::to(\explode(',', config('webhooks.gitlab.notify')))->send(new Gitlab($datas));
}//end if
}
}

View file

@ -11,13 +11,11 @@ class Kernel extends HttpKernel
* *
* These middleware are run during every request to your application. * These middleware are run during every request to your application.
* *
* @var array<int, class-string|string> * @var array
*/ */
protected $middleware = [ protected $middleware = [
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class, \App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class, \App\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class, \App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
@ -26,19 +24,17 @@ class Kernel extends HttpKernel
/** /**
* The application's route middleware groups. * The application's route middleware groups.
* *
* @var array<string, array<int, class-string|string>> * @var array
*/ */
protected $middlewareGroups = [ protected $middlewareGroups = [
'web' => [ 'web' => [
'htmlsanitize',
\App\Http\Middleware\EncryptCookies::class, \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class, \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SecureHeaders::class
], ],
'api' => [ 'api' => [
@ -58,7 +54,7 @@ class Kernel extends HttpKernel
* *
* These middleware may be assigned to groups or used individually. * These middleware may be assigned to groups or used individually.
* *
* @var array<string, class-string|string> * @var array
*/ */
protected $routeMiddleware = [ protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class, 'auth' => \App\Http\Middleware\Authenticate::class,
@ -71,9 +67,6 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'htmlsanitize' => \App\Http\Middleware\HtmlSanitizer::class,
'apiCheck' => \App\Http\Middleware\ApiCheckCredentialMiddleware::class,
'ldcnetwork' => \App\Http\Middleware\LDCNetwork::class
]; ];
/** /**

View file

@ -1,23 +0,0 @@
<?php
namespace App\Http\Middleware;
class ApiCheckCredentialMiddleware
{
/**
* Handle an incoming request.
*
* @param mixed $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
if ($request->token !== \config('api.key')) {
return response('Unauthorized', 401);
}
/** @var \Illuminate\Http\Request $request */
return $next($request);
}
}

View file

@ -10,12 +10,11 @@ class Authenticate extends Middleware
/** /**
* Get the path the user should be redirected to when they are not authenticated. * Get the path the user should be redirected to when they are not authenticated.
* *
* @param mixed $request * @param \Illuminate\Http\Request $request
* @return string|null * @return string|null
*/ */
protected function redirectTo($request) protected function redirectTo($request)
{ {
/** @var \Illuminate\Http\Request $request */
if (!$request->expectsJson()) { if (!$request->expectsJson()) {
session(['redirectURL' => URL::full()]); session(['redirectURL' => URL::full()]);
return route('saml2_login', 'ldc'); return route('saml2_login', 'ldc');

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -12,5 +12,6 @@ class EncryptCookies extends Middleware
* @var array * @var array
*/ */
protected $except = [ protected $except = [
//
]; ];
} }

View file

@ -1,46 +0,0 @@
<?php
namespace App\Http\Middleware;
use App\Lib\ToolboxHelper;
use Illuminate\Http\Request;
class HtmlSanitizer
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$params
* @return mixed
*/
public function handle(Request $request, \Closure $next, ...$params)
{
$inputs = $request->all();
array_walk_recursive($inputs, function (&$input, $name) use ($params) {
if (!is_string($input)) {
return;
}
if (in_array($name, $params)) {
// ? Is a json input ?
if ($isJson = \json_decode($input, true) and is_array($isJson)) {
// ! Decode each json field recursive.
\array_walk_recursive($isJson, function (&$item) {
if (\is_string($item)) {
$item = clean($item);
$item = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($item);
}
});
} else {
$input = clean($input);
$input = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($input);
}
} else {
$input = strip_tags($input);
}
});
$request->merge($inputs);
return $next($request);
}
}

View file

@ -2,52 +2,22 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Models\LDCNetwork as ModelsLDCNetwork;
use Closure; use Closure;
use Illuminate\Support\Facades\Cache; use Symfony\Component\HttpFoundation\IpUtils;
class LDCNetwork class LDCNetwork
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param mixed $request * @param \Illuminate\Http\Request $request
* @param \Closure $next * @param \Closure $next
* @return mixed * @return mixed
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
if (\config('app.env') === 'local' || (\config('app.env') === 'production' && \config('app.debug') === true)) { //IpUtils::checkIp();
// https://github.com/symfony/http-foundation/blob/master/IpUtils.php#L36
return $next($request); return $next($request);
} }
/** HA PROXY HACK */
$ip = request()->server('HTTP_X_FORWARDED_FOR') ?? request()->getClientIp();
$restrictedIps = Cache::get('ldcweb_ip_ranges');
if (\is_null($restrictedIps)) {
$networks = ModelsLDCNetwork::all();
$networks = $networks->map(function (ModelsLDCNetwork $network) {
$infos = collect(explode('.', strval($network->first_ip)));
$min = intval($infos->get(3));
$max = collect(explode('.', strval($network->last_ip)))->get(3);
for ($i = $min; $i <= $max; $i++) {
$restrictedIps[] = $infos->get(0) . '.' .
$infos->get(1) . '.' .
$infos->get(2) . ".$i";
}
return $restrictedIps;
});
$restrictedIps = [];
foreach ($networks->toArray() as $network) {
$restrictedIps = array_merge($restrictedIps, $network);
}
Cache::put('ldcweb_ip_ranges', $restrictedIps, now()->addHours(4));
}
if (!is_null($restrictedIps) && in_array($ip, $restrictedIps)) {
return $next($request);
}
abort(403);
}
} }

View file

@ -1,15 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [];
}

View file

@ -5,7 +5,7 @@ namespace App\Http\Middleware;
use Aacotroneo\Saml2\Saml2Auth; use Aacotroneo\Saml2\Saml2Auth;
use App\Providers\RouteServiceProvider; use App\Providers\RouteServiceProvider;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\URL;
class RedirectIfAuthenticated class RedirectIfAuthenticated
@ -15,13 +15,13 @@ class RedirectIfAuthenticated
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Closure $next * @param \Closure $next
* @param string|null $guard
* @return mixed * @return mixed
*/ */
public function handle(Request $request, Closure $next) public function handle($request, Closure $next, $guard = null)
{ {
if ($request->ajax()) { if ($request->ajax()) {
// Or, return a response that causes client side js to redirect to '/routesPrefix/myIdp1/login' . return response('Unauthorized.', 401); // Or, return a response that causes client side js to redirect to '/routesPrefix/myIdp1/login'
return response('Unauthorized.', 401);
} else { } else {
$saml2Auth = new Saml2Auth(Saml2Auth::loadOneLoginAuthFromIpdConfig('ldc')); $saml2Auth = new Saml2Auth(Saml2Auth::loadOneLoginAuthFromIpdConfig('ldc'));
session(['redirectURL' => URL::full()]); session(['redirectURL' => URL::full()]);

View file

@ -1,81 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
class SecureHeaders
{
/**
* Enumerate headers which you do not want in your application's responses.
* Great starting point would be to go check out @Scott_Helme's:
* https://securityheaders.com/
*
* @var array
*/
private $unwantedHeaderList = [
'X-Powered-By',
'Server',
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
View::share('nonce', $nonce = \uniqid());
// * For VueJS dev tool to execute
$cssDev = config('app.debug') ? "'unsafe-inline'" : "'nonce-$nonce'";
$jsDev = config('app.debug') ? "'unsafe-eval' 'unsafe-inline'" : "'nonce-$nonce'";
$reportUri = Route::has('cspReportUri') ?
\sprintf('report-uri %s', \parse_url(route('cspReportUri'), \PHP_URL_PATH)) : '';
$this->removeUnwantedHeaders($this->unwantedHeaderList);
$response = $next($request);
$response->headers->set('Referrer-Policy', 'no-referrer-when-downgrade');
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains;');
$cspPolicies = [
"default-src 'none';",
// * CKEDITOR Specific https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/csp.html
"connect-src 'self' blob:;",
"img-src * data: blob:;",
"frame-src https://www.youtube.com;",
"font-src 'self' data: https://fonts.gstatic.com;",
// ! Using CKEditor wiill must have unsafe-inline style
// phpcs:ignore Generic.Files.LineLength.TooLong
// "style-src 'self' 'unsafe-inline';",
// ! If you dont use ckeditor use this
"style-src 'self' $cssDev https://fonts.googleapis.com;",
// phpcs:ignore Generic.Files.LineLength.TooLong
"script-src 'self' $jsDev;"
];
$response->headers->set(
'Content-Security-Policy',
implode(' ', $cspPolicies) . $reportUri
);
$response->headers->set('Feature-Policy', 'fullscreen \'self\';');
return $response;
}
/**
* Remove unwanted headers
*
* @param array $headerList
* @return void
*/
private function removeUnwantedHeaders(array $headerList)
{
foreach ($headerList as $header) {
header_remove($header);
}
}
}

View file

@ -1,20 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View file

@ -17,7 +17,7 @@ class TrustProxies extends Middleware
/** /**
* The headers that should be used to detect proxies. * The headers that should be used to detect proxies.
* *
* @var integer * @var int
*/ */
protected $headers = Request::HEADER_X_FORWARDED_FOR; protected $headers = Request::HEADER_X_FORWARDED_ALL;
} }

View file

@ -9,7 +9,7 @@ class VerifyCsrfToken extends Middleware
/** /**
* Indicates whether the XSRF-TOKEN cookie should be set on the response. * Indicates whether the XSRF-TOKEN cookie should be set on the response.
* *
* @var boolean * @var bool
*/ */
protected $addHttpCookie = true; protected $addHttpCookie = true;
@ -19,6 +19,6 @@ class VerifyCsrfToken extends Middleware
* @var array * @var array
*/ */
protected $except = [ protected $except = [
'webhooks/*' //
]; ];
} }

View file

@ -1,51 +0,0 @@
<?php
namespace App\Http\Requests\Api;
use Illuminate\Foundation\Http\FormRequest;
class UpdateProjectStatusRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return ($this->token === \config('api.key')) && !\is_null($this->datas);
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$data = \json_decode($this->datas, true);
$this->merge([
'project_uuid' => collect($data)->get('uuid'),
'sitemap' => collect($data)->get('sitemap') === 'true' ? true : false,
'robots' => collect($data)->get('robots') === 'true' ? true : false,
'code' => collect($data)->get('code'),
'logs' => collect($data)->get('logs')
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'project_uuid' => 'required|exists:projects,uuid',
'sitemap' => 'required|boolean',
'robots' => 'required|boolean',
'code' => 'required|array',
'logs' => 'required|numeric',
];
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
class GitReposStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => [
'string',
'required',
Rule::unique('git_repos', 'name'),
],
'login' => [
Rule::requiredIf(function () {
return !is_null($this->password);
})
],
'password' => [
Rule::requiredIf(function () {
return !is_null($this->login);
})
],
];
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
class GitReposUpdateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => [
'string',
'required',
Rule::unique('git_repos', 'name')->ignore($this->git_repo->id),
],
'login' => [
Rule::requiredIf(function () {
return !is_null($this->password);
})
],
'password' => [
Rule::requiredIf(function () {
return !is_null($this->login);
})
],
];
}
}

View file

@ -1,64 +0,0 @@
<?php
namespace App\Http\Requests\LDCNetworks;
use App\Rules\CidrRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class StoreLDCNetwork extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return Auth::check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge($this->cidrToRange());
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'cidr' => ['required', new CidrRule()],
'first_ip' => 'required|ipv4',
'last_ip' => 'required|ipv4'
];
}
/**
* cidr To Ranges
*
* @return array ['first_ip', 'last_ip']
*/
private function cidrToRange(): array
{
$first_ip = '';
$last_ip = '';
$cidr = collect(explode('/', \strval($this->cidr)));
try {
$first_ip = long2ip(intval(ip2long($cidr->get(0))) & ((-1 << (32 - intval($cidr->get(1))))));
$last_ip = long2ip(intval(ip2long(\strval($first_ip))) + pow(2, (32 - intval($cidr->get(1)))) - 1);
} catch (\Error $e) {
Session::flash('warning', trans('Le CIDR est mal formé'));
}
return \compact('first_ip', 'last_ip');
}
}

View file

@ -1,7 +0,0 @@
<?php
namespace App\Http\Requests\LDCNetworks;
class UpdateLDCNetwork extends StoreLDCNetwork
{
}

View file

@ -1,112 +0,0 @@
<?php
namespace App\Http\Requests\Projects;
use App\Enums\PhpVersion;
use App\Enums\ProjectType;
use App\Enums\SmtpEnum;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
class StoreProjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return Auth::check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'https' => $this->https ? true : false
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [];
if (Auth::user()->equipe_web_member) {
$rules = [
'prod_login' => 'required|json',
'dev_login' => 'required|json',
'prod_bo_url' => 'required|url',
'dev_bo_url' => 'required|url',
];
}
return \array_merge($rules, [
'name' => 'required|string|min:2|max:255',
'display_name' => 'required|string|min:2|max:255',
'php' => ['required', new EnumIsValidRule(PhpVersion::class)],
'type' => ['required', new EnumIsValidRule(ProjectType::class)],
'https' => 'required|boolean',
'prod_haproxy_id' => 'nullable|regex:/^P?\d{3}$/',
'dev_haproxy_id' => 'nullable|regex:/^P?\d{3}$/',
'prod_url' => 'nullable|url|max:255',
'dev_url' => 'nullable|url|max:255',
'prod_document_root' => 'nullable|regex:/^(\/)?([^\/\0]+(\/)?)+$/|max:255',
'dev_document_root' => 'nullable|regex:/^(\/)?([^\/\0]+(\/)?)+$/|max:255',
'prod_unix_user' => 'nullable|string|max:255',
'prod_unix_pwd' => 'nullable|string|max:255',
'dev_unix_user' => 'nullable|string|max:255',
'dev_unix_pwd' => 'nullable|string|max:255',
'prod_db_user' => 'nullable|string|max:255',
'prod_db_pwd' => 'nullable|string|max:255',
'dev_db_user' => 'nullable|string|max:255',
'dev_db_pwd' => 'nullable|string|max:255',
'prod_db_schema' => 'nullable|string|max:255',
'dev_db_schema' => 'nullable|string|max:255',
'prod_db_server_id' => 'sometimes|exists:servers,id',
'dev_db_server_id' => 'sometimes|exists:servers,id',
'prod_web_server_id' => 'sometimes|exists:servers,id',
'dev_web_server_id' => 'sometimes|exists:servers,id',
'prod_comment' => 'nullable|string|max:255',
'dev_comment' => 'nullable|string|max:255',
'prod_eai' => 'nullable|string|max:255',
'dev_eai' => 'nullable|string|max:255',
'prod_whitelist_fw' => 'nullable|string|max:255',
'dev_whitelist_fw' => 'nullable|string|max:255',
'dev_htaccess_user' => 'required|string|min:2|max:255',
'dev_htaccess_pwd' => 'required|string|min:2|max:255',
'prod_ga_id' => 'nullable|string|max:50',
// phpcs:ignore Generic.Files.LineLength.TooLong
'prod_laravel_app_key' => 'nullable|regex:/^base64:(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/|max:255',
// phpcs:ignore Generic.Files.LineLength.TooLong
'dev_laravel_app_key' => 'nullable|regex:/^base64:(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/|max:255',
'prod_smtp_config' => [
'required', new EnumIsValidRule(SmtpEnum::class)
],
'prod_smtp_key' => 'required_if:prod_smtp_config,3|max:255|max:255',
]);
}
}

View file

@ -1,20 +1,20 @@
<?php <?php
namespace App\Http\Requests\ServiceAccounts; namespace App\Http\Requests\Projects;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
class StoreServiceAccountsRequest extends FormRequest class StoreProjects extends FormRequest
{ {
/** /**
* Determine if the user is authorized to make this request. * Determine if the user is authorized to make this request.
* *
* @return boolean * @return bool
*/ */
public function authorize() public function authorize()
{ {
return Auth::check(); return Auth::checK();
} }
/** /**
@ -25,10 +25,9 @@ class StoreServiceAccountsRequest extends FormRequest
public function rules() public function rules()
{ {
return [ return [
'name' => 'required|min:2|max:255', // TODO : compléter les rules
'url' => 'required|min:2|max:255|url', 'prod_smtp_config' => 'integer|required',
'account' => 'required|min:2|max:255', 'prod_smtp_key' => 'required_if:prod_smtp_config,3'
'password' => 'required|max:255'
]; ];
} }
} }

View file

@ -2,8 +2,21 @@
namespace App\Http\Requests\Projects; namespace App\Http\Requests\Projects;
class UpdateProjectRequest extends StoreProjectRequest use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class UpdateProjects extends FormRequest
{ {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return Auth::checK();
}
/** /**
* Get the validation rules that apply to the request. * Get the validation rules that apply to the request.
* *
@ -11,12 +24,12 @@ class UpdateProjectRequest extends StoreProjectRequest
*/ */
public function rules() public function rules()
{ {
return \array_merge(parent::rules(), [ return [
// TODO : compléter les rules . // TODO : compléter les rules
'prod_laravel_app_key' => 'required_if:type,3', 'prod_laravel_app_key' => 'required_if:type,3',
'dev_laravel_app_key' => 'required_if:type,3', 'dev_laravel_app_key' => 'required_if:type,3',
'prod_smtp_config' => 'integer|required', 'prod_smtp_config' => 'integer|required',
'prod_smtp_key' => 'required_if:prod_smtp_config,3' 'prod_smtp_key' => 'required_if:prod_smtp_config,3'
]); ];
} }
} }

View file

@ -1,46 +0,0 @@
<?php
namespace App\Http\Requests\Servers;
use App\Enums\Environment;
use App\Enums\ServerType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
class StoreServerRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'env' => [
'required', new EnumIsValidRule(Environment::class)
],
'virtual_ip' => 'required|ipV4',
'ssh' => 'required',
'infraweb_ip' => 'required|ipV4',
'title' => 'required|min:2|max:50',
'name' => 'required|min:2|max:50',
'function' => 'required|min:2|max:50',
'comment' => 'nullable|string',
'type' => [
'required', new EnumIsValidRule(ServerType::class)
],
];
}
}

View file

@ -1,7 +0,0 @@
<?php
namespace App\Http\Requests\Servers;
class UpdateServerRequest extends StoreServerRequest
{
}

View file

@ -1,7 +0,0 @@
<?php
namespace App\Http\Requests\ServiceAccounts;
class UpdateServiceAccountsRequest extends StoreServiceAccountsRequest
{
}

View file

@ -1,51 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Carbon;
use lfkeitel\phptotp\Base32;
use lfkeitel\phptotp\Totp;
class ValidateOtpRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
if (!session()->get('tmpUserOTP')) {
return false;
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'otp' => [
'string',
'required',
function ($attribute, $value, $fail) {
$user = session()->get('tmpUserOTP');
$lastCode = (new Totp())->GenerateToken(
Base32::decode($user->totp_secret),
Carbon::now()->subSeconds(30)->timestamp
);
$code = (new Totp())->GenerateToken(Base32::decode($user->totp_secret));
if (!($value === $code || $value === $lastCode)) {
$fail("Code de vérification $attribute invalide.");
}
}
]
];
}
}

View file

@ -1,31 +0,0 @@
<?php
namespace App\Http\Requests\Webhooks;
use Illuminate\Foundation\Http\FormRequest;
class GitlabRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return $this->header('X-Gitlab-Token') !== null &&
$this->header('X-Gitlab-Token') === config('webhooks.gitlab.token');
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'event_type' => 'required|in:merge_request'
];
}
}

View file

@ -4,44 +4,29 @@ namespace App\Lib\LDC;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
class MailjetSms class MailjetSms
{ {
/** @var Application $app */ /** @var Application $app */
protected $app; protected $app;
/** @var array $config */ /** @var array $config */
protected $config = []; protected $config = [];
/**
* MailjetSms
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
public function __construct(Application $app) public function __construct(Application $app)
{ {
$this->app = $app; $this->app = $app;
$this->loadDefaultOptions(); $this->loadDefaultOptions();
} }
/** protected function loadDefaultOptions(): MailjetSms
* loadDefaultOptions
*
* @return \App\Lib\LDC\MailjetSms
*/
protected function loadDefaultOptions(): \App\Lib\LDC\MailjetSms
{ {
$this->config = $this->app['config']->get('services.mailjet'); $this->config = $this->app['config']->get('services.mailjet');
return $this; return $this;
} }
/** protected function buildHttpClient(): Client
* buildHttpClient
*
* @return \GuzzleHttp\Client
*/
protected function buildHttpClient(): \GuzzleHttp\Client
{ {
return new Client([ return new Client([
'allow_redirects' => false, 'allow_redirects' => false,
@ -57,16 +42,7 @@ class MailjetSms
]); ]);
} }
/** public function send(string $message, string $to, $from = null): ResponseInterface
* send sms
*
* @param string $message
* @param string $to
* @param string|null $from
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\RequestException If Mailsms send service call failed.
*/
public function send(string $message, string $to, ?string $from = null): ResponseInterface
{ {
$from = $from ?? $this->config['sms_from']; $from = $from ?? $this->config['sms_from'];
$client = $this->buildHttpClient(); $client = $this->buildHttpClient();
@ -79,10 +55,15 @@ class MailjetSms
'To' => $to, 'To' => $to,
] ]
]); ]);
} catch (\GuzzleHttp\Exception\RequestException $e) { } catch (\GuzzleHttp\Exception\RequestException $ex) {
report($e); Log::debug('error ' . $ex->getMessage());
throw $e; if (!is_null($ex->getResponse())){
Log::debug((string) $ex->getResponse()->getBody());
} }
throw $ex;
}
return $response; return $response;
} }

View file

@ -1,228 +0,0 @@
<?php
namespace App\Lib;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ToolboxHelper
{
/**
* Strip scheme (https) on oembed urls
* Only embed allowed are for MP4 self hosted videos right now
*
* https is force by ckeditor MediaElements which natively supports
* only cloud hosted medias (youtube, spotify etc..)
*
* @param string $input
* @return string
*/
public static function stripCkEditorSchemesOnMediaInputs(string $input): string
{
$input = \preg_replace('/(?<=<oembed url=")(https:\/\/)(?=.*?">)/m', '', $input);
return $input;
}
/**
* Assert That no Back Office url is present on txt
*
* @param string $field
* @param string $text
* @return string
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
*/
public static function assertNoInternalBoUrls(string $field, string $text): string
{
$routes = Route::getRoutes();
// * Url replace and email replace.
$text = preg_replace_callback(
// phpcs:ignore Generic.Files.LineLength.TooLong
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
function ($matches) use ($routes, $field) {
$match = collect($matches)->first() ?? '';
$url = $match;
try {
$request = Request::create($url);
// If a route is match then it do not throws exception.
if (
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
trim($routes->match($request)->getPrefix() ?? '', '/') === 'bo'
) {
// Removes the matched url.
throw ValidationException::withMessages([
$field => sprintf(
'%s : Il est interdit de coller une url du back office dans ce champ',
trans($field)
)
]);
}
return $match;
} catch (NotFoundHttpException $e) {
return $match;
}
},
$text
);
return $text;
}
/**
* Assert That only external url is present on txt
*
* @param string $field
* @param string $text
* @return string
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
*/
public static function assertNoInternalUrls(string $field, string $text): string
{
self::assertNoInternalBoUrls($field, $text);
$routes = Route::getRoutes();
// * Url replace and email replace.
$text = preg_replace_callback(
// phpcs:ignore Generic.Files.LineLength.TooLong
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
function ($matches) use ($routes, $field) {
$match = collect($matches)->first() ?? '';
$url = $match;
try {
$request = Request::create($url);
// If a route is match then it do not throws exception.
if (
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
$routes->match($request)
) {
// Removes the matched url.
throw ValidationException::withMessages([
$field => sprintf(
'%s : Il est interdit de coller une url de %s dans ce champ',
trans($field),
config('app.name')
)
]);
}
return $match;
} catch (NotFoundHttpException $e) {
return $match;
}
},
$text
);
return $text;
}
/**
* Generates an array from a dot separated string
*
* @param string $path
* @param mixed $value
* @param string $separator
* @return array
*/
public static function dotStringToNestedArray(string $path, $value, string $separator = '.'): array
{
$arr = $value;
$keys = array_reverse(explode($separator, $path));
foreach ($keys as $key) {
$arr = [$key => $arr];
}
return $arr;
}
/**
* Destroy image
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $attribute
* @return void
*/
public static function removeImage(Model $model, string $attribute)
{
$path = ltrim($model->{$attribute}, '/');
if (File::exists($path) and \strpos($path, 'storage') === 0) {
File::delete($path);
}
}
/**
* Destroy image
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $attribute
* @return void
*/
public static function removeOldImage(Model $model, string $attribute)
{
$originalPath = ltrim($model->getOriginal($attribute), '/');
if (File::exists($originalPath) and \strpos($originalPath, 'storage') === 0) {
File::delete($originalPath);
}
}
/**
* Store an image of different types
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param \Illuminate\Http\UploadedFile|\SplFileInfo|string $image
* @return string
* @throws \ErrorException If file copy fails.
*/
public static function storeImage(Model $model, $image): string
{
$table = $model->getTable();
if (\is_object($image) and $image instanceof \Illuminate\Http\UploadedFile) {
/** @var \Illuminate\Http\UploadedFile $image */
$newPath = self::prepareMoveFile($table, \filter_var(
\strip_tags(\urldecode($image->getClientOriginalName())),
\FILTER_SANITIZE_STRING
));
$newPath = str_replace(storage_path('app'), '', $newPath);
$image->storePubliclyAs(
pathinfo($newPath, \PATHINFO_DIRNAME),
pathinfo($newPath, \PATHINFO_BASENAME)
);
return 'storage' . str_replace('/public', '', $newPath);
}
if (\is_object($image) and $image instanceof \SplFileInfo) {
/** @var \SplFileInfo $image */
$newPath = self::prepareMoveFile($table, $image->getBaseName());
if (!File::copy($image->getRealPath(), $newPath)) {
throw new \ErrorException(sprintf(
'Failed to copy file %s to %s',
$image->getRealPath(),
$newPath
));
}
return \ltrim(str_replace(\storage_path('app/public'), '/storage', $newPath), '/');
}
return \ltrim(strval($image), '/');
}
/**
* Prepare storage path and return
* the image full path
*
* @param string $table Model table name.
* @param string $filename The basename for the file.
* @return string
*/
private static function prepareMoveFile(string $table, string $filename): string
{
$pathFolder = \storage_path(sprintf('app/public/images/%s', $table));
if (!File::exists($pathFolder)) {
File::makeDirectory($pathFolder, 0755, true);
}
$filename = sprintf('%s-%s', Str::uuid(), $filename);
$fullPath = sprintf('%s/%s', $pathFolder, $filename);
if (File::exists($fullPath)) {
File::delete($fullPath);
}
return $fullPath;
}
}

View file

@ -1,40 +0,0 @@
<?php
namespace App\Mail\Webhooks;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Gitlab extends Mailable
{
use Queueable;
use SerializesModels;
/**
* Mail data
*
* @var array
*/
public $data;
/**
* Create a new message instance.
*
* @param array $data
*/
public function __construct(array $data)
{
$this->data = $data;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->text('emails.webhooks.gitlab');
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DatastorePcc extends Model
{
protected $table = 'datastore_pcc';
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DomainNames extends Model
{
//
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class EmailAddresses extends Model
{
public function getDomainNameAttribute() {
$dn = DomainNames::findOrFail($this->domain_name_id);
return $dn->utf8_name;
}
}

10
app/Models/GitRepos.php Normal file
View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class GitRepos extends Model
{
protected $fillable = ['name', 'login', 'password'];
}

View file

@ -1,24 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class LDCNetwork extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'ldc_networks';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'cidr', 'first_ip', 'last_ip'
];
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class LDCNetworks extends Model
{
protected $table = 'ldc_networks';
}

View file

@ -1,232 +0,0 @@
<?php
namespace App\Models;
use App\Enums\PhpVersion;
use App\Enums\ProjectType;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Kwaadpepper\Enum\Traits\CastsEnums;
class Project extends Model
{
use CastsEnums;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'dev_login' => 'array',
'prod_login' => 'array',
'https' => 'boolean'
];
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'php' => PhpVersion::class,
'type' => ProjectType::class,
'smtp' => SmtpEnum::class
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'display_name', 'php', 'type', 'https', 'prod_haproxy_id',
'dev_haproxy_id', 'prod_url', 'dev_url', 'prod_bo_url', 'dev_bo_url', 'prod_login', 'dev_login',
'prod_document_root', 'dev_document_root', 'prod_unix_user', 'dev_unix_user',
'prod_unix_pwd', 'dev_unix_pwd', 'prod_db_user', 'dev_db_user',
'prod_db_pwd', 'dev_db_pwd', 'prod_db_schema', 'dev_db_schema',
'prod_db_server_id', 'dev_db_server_id', 'prod_web_server_id',
'dev_web_server_id', 'prod_comment', 'dev_comment', 'prod_eai',
'dev_eai', 'prod_whitelist_fw', 'dev_whitelist_fw',
'dev_htaccess_user', 'dev_htaccess_pwd', 'prod_ga_id',
'prod_laravel_app_key', 'dev_laravel_app_key',
'prod_smtp_config', 'prod_smtp_key',
];
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName(): string
{
return 'uuid';
}
// * METHODS
/**
* get dev_web_ip attribute
*
* @return mixed
*/
public function getDevWebIpAttribute()
{
$value = Server::find($this->dev_web_server_id);
if ($value) {
$value = $value->ssh;
}
return $value;
}
/**
* get dev_db_ip attribute
*
* @return mixed
*/
public function getDevDbIpAttribute()
{
$value = Server::find($this->dev_db_server_id);
if ($value) {
$value = $value->ssh;
}
return $value;
}
/**
* get prod_web_ip attribute
*
* @return mixed
*/
public function getProdWebIpAttribute()
{
$value = Server::find($this->prod_web_server_id);
if ($value) {
$value = $value->ssh;
}
return $value;
}
/**
* get prod_db_ip attribute
*
* @return mixed
*/
public function getProdDbIpAttribute()
{
$value = Server::find($this->prod_db_server_id);
if ($value) {
$value = $value->ssh;
}
return $value;
}
/**
* get checked attribute
*
* @return mixed
*/
public function getCheckedAttribute()
{
$value = ProjectStatusChecker::select('last_call')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->last_call;
$dt = Carbon::now();
if ($dt->diffInMinutes($value) > 30) {
$value = 'false';
} else {
$value = 'true';
}
}
return $value;
}
/**
* get sitemap_checked attribute
*
* @return mixed
*/
public function getSitemapCheckedAttribute()
{
$value = ProjectStatusChecker::select('sitemap')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->sitemap;
}
return $value;
}
/**
* get robots_checked attribute
*
* @return mixed
*/
public function getRobotsCheckedAttribute()
{
$value = ProjectStatusChecker::select('robots')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->robots;
}
return $value;
}
/**
* get logs_checked attribute
*
* @return mixed
*/
public function getLogsCheckedAttribute()
{
$value = ProjectStatusChecker::select('logs')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->logs;
}
return $value;
}
/**
* get code attribute
*
* @return mixed
*/
public function getCodeAttribute()
{
$value = ProjectStatusChecker::select('code')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->code;
}
return $value;
}
/**
* get logs_hr attribute
*
* @return string
*/
public function getLogsHrAttribute(): string
{
$value = ProjectStatusChecker::select('logs')->where('project_uuid', '=', $this->uuid)->first();
return $this->humanFilesize($value->logs);
}
/**
* Human readable file size
*
* @param float $size
* @return string
*/
private function humanFilesize(float $size): string
{
$i = \floatval(floor(log($size, 1024)));
return round($size / pow(1024, $i), [0,0,2,2,3][$i]) . [' O',' Ko',' Mo',' Go',' To'][$i];
}
}

View file

@ -1,28 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProjectStatusChecker extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'code' => 'array',
'sitemap' => 'boolean',
'robots' => 'boolean'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'project_uuid', 'code', 'sitemap', 'robots', 'logs', 'last_call'
];
}

102
app/Models/Projects.php Normal file
View file

@ -0,0 +1,102 @@
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
public function getDevWebIpAttribute() {
$value = Servers::find($this->dev_web_server_id);
if ($value)
$value = $value->ssh;
return $value;
}
public function getDevDbIpAttribute() {
$value = Servers::find($this->dev_db_server_id);
if ($value)
$value = $value->ssh;
return $value;
}
public function getProdWebIpAttribute() {
$value = Servers::find($this->prod_web_server_id);
if ($value)
$value = $value->ssh;
return $value;
}
public function getProdDbIpAttribute() {
$value = Servers::find($this->prod_db_server_id);
if ($value)
$value = $value->ssh;
return $value;
}
public function getCheckedAttribute() {
$value = ProjectsStatusChecker::select('updated_at')->where('project_uuid', '=', $this->uuid)->first();
if (!$value) {
$value = 'missing';
} else {
$value = $value->updated_at;
$dt = Carbon::now();
if ($dt->diffInMinutes($value) > 30) {
$value = 'false';
} else {
$value = 'true';
}
}
return $value;
}
public function getSitemapCheckedAttribute() {
$value = ProjectsStatusChecker::select('sitemap')->where('project_uuid', '=', $this->uuid)->first();
if(!$value) {
$value = 'missing';
} else {
$value = $value->sitemap;
}
return $value;
}
public function getRobotsCheckedAttribute() {
$value = ProjectsStatusChecker::select('robots')->where('project_uuid', '=', $this->uuid)->first();
if(!$value) {
$value = 'missing';
} else {
$value = $value->robots;
}
return $value;
}
public function getLogsCheckedAttribute() {
$value = ProjectsStatusChecker::select('logs')->where('project_uuid', '=', $this->uuid)->first();
if(!$value) {
$value = 'missing';
} else {
$value = $value->logs;
}
return $value;
}
public function getCodeAttribute() {
$value = ProjectsStatusChecker::select('code')->where('project_uuid', '=', $this->uuid)->first();
if(!$value) {
$value = 'missing';
} else {
$value = $value->code;
}
return $value;
}
public function getLogsHrAttribute() {
$value = ProjectsStatusChecker::select('logs')->where('project_uuid', '=', $this->uuid)->first();
return $this->human_filesize($value->logs);
}
private function human_filesize($size, $precision = 2) {
$i = floor(log($size, 1024));
return round($size / pow(1024, $i), [0,0,2,2,3][$i]).[' O',' Ko',' Mo',' Go',' To'][$i];
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProjectsStatusChecker extends Model
{
protected $table = 'projects_status_checker';
}

View file

@ -1,36 +0,0 @@
<?php
namespace App\Models;
use App\Enums\Environment;
use App\Enums\ServerType;
use Illuminate\Database\Eloquent\Model;
use Kwaadpepper\Enum\Traits\CastsEnums;
class Server extends Model
{
use CastsEnums;
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'env' => Environment::class,
'type' => ServerType::class
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'env', 'virtual_ip',
'ssh', 'infraweb_ip',
'title', 'name', 'function',
'comment',
'type'
];
}

10
app/Models/Servers.php Normal file
View file

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Servers extends Model
{
//
}

View file

@ -1,17 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ServiceAccount extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'account', 'password', 'url'
];
}

View file

@ -2,13 +2,21 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/** /**
* Bootstrap any application services. * Bootstrap any application services.
* *
@ -16,34 +24,8 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function boot() public function boot()
{ {
if (!app()->environment('local')) {
URL::forceScheme('https'); URL::forceScheme('https');
}
// * LOCAL FORCE eg: for Carbon
// * Remove numeric to prevent float seperator to breaking numeric transactions
\collect([\LC_TIME, \LC_MESSAGES, \LC_COLLATE, \LC_CTYPE, \LC_MONETARY])
->map(function ($contant) {
setlocale(
$contant,
\sprintf(
'%s_%s.UTF-8',
config('app.locale'),
\strtoupper(config('app.locale'))
)
);
});
Carbon::setLocale(config('app.locale'));
// * Force bootstrap paginator
Paginator::useBootstrap();
// * HA PROXY FIX
app()->singleton('clientIp', function () {
if (
config('app.env') === 'local'
) {
return request()->getClientIp();
}
return request()->server('HTTP_X_FORWARDED_FOR') ?? request()->getClientIp();
});
} }
} }

View file

@ -3,15 +3,18 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider class AuthServiceProvider extends ServiceProvider
{ {
/** /**
* The policy mappings for the application. * The policy mappings for the application.
* *
* @var array<class-string, class-string> * @var array
*/ */
protected $policies = []; protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/** /**
* Register any authentication / authorization services. * Register any authentication / authorization services.
@ -21,5 +24,7 @@ class AuthServiceProvider extends ServiceProvider
public function boot() public function boot()
{ {
$this->registerPolicies(); $this->registerPolicies();
//
} }
} }

View file

@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View file

@ -3,8 +3,9 @@
namespace App\Providers; namespace App\Providers;
use Aacotroneo\Saml2\Events\Saml2LoginEvent; use Aacotroneo\Saml2\Events\Saml2LoginEvent;
use App\Models\User; use App\User;
use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Event;
@ -19,6 +20,7 @@ class EventServiceProvider extends ServiceProvider
*/ */
protected $listen = [ protected $listen = [
Registered::class => [ Registered::class => [
SendEmailVerificationNotification::class,
], ],
]; ];
@ -32,63 +34,21 @@ class EventServiceProvider extends ServiceProvider
parent::boot(); parent::boot();
Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) { Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
$messageId = $event->getSaml2Auth()->getLastMessageId(); $messageId = $event->getSaml2Auth()->getLastMessageId();
// TODO : Add your own code preventing reuse of a $messageId to stop replay attacks
if (class_exists('Memcached')) {
$cache = new \Memcached();
$cache->addServer(
config('cache.stores.memcached.servers.0.host'),
config('cache.stores.memcached.servers.0.port')
);
$fromCache = $cache->get(config('cache.prefix') . "_saml_message_id_" . $messageId);
if (!in_array($cache->getResultCode(), [\Memcached::RES_SUCCESS, \Memcached::RES_NOTFOUND])) {
throw new \Exception(
\sprintf(
"SAML MESSAGE ID HANDLER - Memcached Error : %d - %s",
$cache->getResultCode(),
"https://www.php.net/manual/en/memcached.getresultcode.php"
)
);
}
if ($fromCache) {
logger()->error(
'SAML MESSAGE ID HANDLER',
[
'error' => 'Message ID : ' . $messageId . " replayed !"
]
);
abort(403);
} else {
// Cache for 8h.
$cache->set(config('cache.prefix') . "_saml_message_id_" . $messageId, $messageId, 28800);
if ($cache->getResultCode() === \Memcached::RES_NOTSTORED) {
throw new \Exception('SAML MESSAGE ID HANDLER - Memcached Error : NOT STORED');
}
}
} else {
throw new \Exception("SAML MESSAGE ID HANDLER - Memcached is missing");
} //end if
$user = $event->getSaml2User(); $user = $event->getSaml2User();
$email = $user->getNameId(); $email = $user->getNameId();
$lUser = User::where('email', '=', $email)->first(); $lUser = User::where('email', '=', $email)->first();
if (!$lUser) { if (!$lUser) {
abort(redirect()->route('unauthorized')); abort(redirect()->route('unauthorized'));
} }
session(['sessionIndex' => $user->getSessionIndex()]); session(['sessionIndex' => $user->getSessionIndex()]);
session(['nameId' => $email]);
session(['tmpUserOTP' => $lUser]); session(['tmpUserOTP' => $lUser]);
abort(redirect()->route('auth.verify')); abort(redirect()->route('auth.verify'));
}); });
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) { Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) {
Auth::logout(); Auth::logout();
Session::save(); Session::save();

View file

@ -2,6 +2,7 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use App\Lib\LDC\MailjetSms; use App\Lib\LDC\MailjetSms;
@ -14,6 +15,7 @@ class MailjetSmsServiceProvider extends ServiceProvider
*/ */
public function register() public function register()
{ {
//
} }
/** /**
@ -23,7 +25,7 @@ class MailjetSmsServiceProvider extends ServiceProvider
*/ */
public function boot() public function boot()
{ {
$this->app->singleton('MailjetSms', function ($app) { App::singleton('MailjetSms', function ($app) {
return new MailjetSms($app); return new MailjetSms($app);
}); });
} }

View file

@ -2,18 +2,22 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider class RouteServiceProvider extends ServiceProvider
{ {
/** /**
* The path to the "home" route for your application. * This namespace is applied to your controller routes.
* *
* This is used by Laravel authentication to redirect users after login. * In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* The path to the "home" route for your application.
* *
* @var string * @var string
*/ */
@ -26,35 +30,51 @@ class RouteServiceProvider extends ServiceProvider
*/ */
public function boot() public function boot()
{ {
$this->configureRateLimiting(); //
$this->routes(function () { parent::boot();
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web-bo.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web-fo.php'));
Route::middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
} }
/** /**
* Configure the rate limiters for the application. * Define the routes for the application.
* *
* @return void * @return void
*/ */
protected function configureRateLimiting() public function map()
{ {
RateLimiter::for('web', function (Request $request) { $this->mapApiRoutes();
return Limit::perMinute(150)->by(optional($request->user())->id ?: app('clientIp'));
}); $this->mapWebRoutes();
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(150)->by(optional($request->user())->id ?: app('clientIp')); //
}); }
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
} }
} }

View file

@ -1,77 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;
class TranslationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
foreach ($this->collectLocalesStrings() as $locale) {
// * Suported locales
Cache::rememberForever(sprintf('translations.%s', $locale), function () use ($locale) {
$translations = [
'php' => $this->phpTranslations($locale),
'json' => $this->jsonTranslations($locale),
];
return $translations;
});
}
}
/**
* Gather provided langs checking from files
*
* @return Collection
*/
private function collectLocalesStrings(): Collection
{
return collect(File::allFiles(resource_path('lang/')))->flatMap(function ($file) {
if ($file->getRelativePath()) {
return [$file->getRelativePath() => ''];
}
})->keys();
}
/**
* Gather all php translations
*
* @param string $locale
* @return array
*/
private function phpTranslations(string $locale): array
{
$path = resource_path("lang/$locale");
return collect(File::allFiles($path))->flatMap(function ($file) use ($locale) {
$translation = $file->getBasename('.php');
return [$translation => trans($translation, [], $locale)];
})->all();
}
/**
* Gather json translations
*
* @param string $locale
* @return array
*/
private function jsonTranslations(string $locale): array
{
$path = resource_path("lang/$locale.json");
if (is_string($path) && is_readable($path)) {
return json_decode(file_get_contents($path), true) ?? [];
}
return [];
}
}

View file

@ -1,57 +0,0 @@
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CidrRule implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param mixed $attribute
* @param mixed $value
* @return boolean
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
*/
public function passes($attribute, $value)
{
// phpcs:enable
$m = true;
if (strpos($value, ":") !== false) {
// * ipv6
if (strpos($value, "/") !== false) {
list($value, $mask) = explode("/", $value);
$m = filter_var(
$mask,
\FILTER_VALIDATE_INT,
["options" => ["min_range" => 0, "max_range" => 128]]
);
}
return $m && filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6);
} else {
// * ipv4
if (strpos($value, "/") !== false) {
list($value, $mask) = explode("/", $value);
$m = filter_var(
$mask,
\FILTER_VALIDATE_INT,
["options" => ["min_range" => 0, "max_range" => 32]]
);
}
return $m && filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4);
} //end if
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return "The :attribute must be a valid IP address or CIDR range.";
}
}

View file

@ -1,7 +1,8 @@
<?php <?php
namespace App\Models; namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
@ -15,12 +16,7 @@ class User extends Authenticatable
* @var array * @var array
*/ */
protected $fillable = [ protected $fillable = [
'firstname', 'name', 'email', 'phone', 'password',
'lastname',
'email',
'phone',
'password',
'equipe_web_member'
]; ];
/** /**
@ -38,7 +34,6 @@ class User extends Authenticatable
* @var array * @var array
*/ */
protected $casts = [ protected $casts = [
'equipe_web_member' => 'boolean',
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
]; ];
} }

View file

@ -8,31 +8,25 @@
], ],
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^7.3", "php": "^7.2",
"aacotroneo/laravel-saml2": "^2.1", "aacotroneo/laravel-saml2": "^2.1",
"fideloper/proxy": "^4.0", "fideloper/proxy": "^4.0",
"fruitcake/laravel-cors": "^2.2",
"guzzlehttp/guzzle": "^7.0.1", "guzzlehttp/guzzle": "^7.0.1",
"kwaadpepper/enum": "^2.1", "kwaadpepper/enum": "^2.1",
"kwaadpepper/exception-handler": "^0.0.8", "kwaadpepper/exception-handler": "^0.0.6",
"laravel/framework": "^8.75", "laravel/framework": "^8.0",
"laravel/tinker": "^2.5", "laravel/tinker": "^2.0",
"laravel/ui": "^3.0", "laravel/ui": "^3.0",
"lfkeitel/phptotp": " 1.0", "lfkeitel/phptotp": " 1.0",
"mews/purifier": "^3.3",
"propaganistas/laravel-phone": "^4.3",
"simplesoftwareio/simple-qrcode": "^4.2", "simplesoftwareio/simple-qrcode": "^4.2",
"slevomat/coding-standard": "^7.0" "slevomat/coding-standard": "^7.0"
}, },
"require-dev": { "require-dev": {
"doctrine/dbal": "^3.3", "facade/ignition": "^2.3.6",
"facade/ignition": "^2.5", "fzaninotto/faker": "^1.9.1",
"fakerphp/faker": "^1.9.1", "mockery/mockery": "^1.0",
"laravel/sail": "^1.0.1", "nunomaduro/collision": "^5.0",
"mockery/mockery": "^1.4.4", "phpunit/phpunit": "^9.0"
"nunomaduro/collision": "^5.10",
"phpunit/phpunit": "^9.5.10",
"slevomat/coding-standard": "^7.2"
}, },
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,

2059
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,5 +0,0 @@
<?php
return [
'key' => 'CE8S52Qq7stf5k8frF4T'
];

View file

@ -139,7 +139,6 @@ return [
/* /*
* Laravel Framework Service Providers... * Laravel Framework Service Providers...
*/ */
Illuminate\Auth\AuthServiceProvider::class, Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class, Illuminate\Bus\BusServiceProvider::class,
@ -170,12 +169,11 @@ return [
/* /*
* Application Service Providers... * Application Service Providers...
*/ */
App\Providers\AppServiceProvider::class, App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class, App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class, App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class, App\Providers\RouteServiceProvider::class,
App\Providers\TranslationServiceProvider::class,
App\Providers\MailjetSmsServiceProvider::class, App\Providers\MailjetSmsServiceProvider::class,
], ],
@ -229,6 +227,8 @@ return [
'Validator' => Illuminate\Support\Facades\Validator::class, 'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class, 'View' => Illuminate\Support\Facades\View::class,
'SmtpEnum' => App\Enums\Smtp::class, 'SmtpEnum' => App\Enums\Smtp::class,
'ProjectTypesEnum' => App\Enums\ProjectTypes::class,
], ],
]; ];

View file

@ -68,8 +68,13 @@ return [
'providers' => [ 'providers' => [
'users' => [ 'users' => [
'driver' => 'eloquent', 'driver' => 'eloquent',
'model' => App\Models\User::class, 'model' => App\User::class,
], ],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
], ],
/* /*

View file

@ -59,7 +59,9 @@ return [
env('MEMCACHED_USERNAME'), env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'), env('MEMCACHED_PASSWORD'),
], ],
'options' => [], 'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [ 'servers' => [
[ [
'host' => env('MEMCACHED_HOST', '127.0.0.1'), 'host' => env('MEMCACHED_HOST', '127.0.0.1'),

View file

@ -1,17 +1,9 @@
<?php <?php
use Illuminate\Database\DBAL\TimestampType;
use Illuminate\Support\Str; use Illuminate\Support\Str;
return [ return [
// * https://github.com/laravel/docs/blob/master/migrations.md#prerequisites .
'dbal' => [
'types' => [
'timestamp' => TimestampType::class,
],
],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Default Database Connection Name | Default Database Connection Name

View file

@ -1,14 +1,14 @@
<?php <?php
// If you choose to use ENV vars to define these values, give this IdP its own env var names // If you choose to use ENV vars to define these values, give this IdP its own env var names
// so you can define different values for each IdP, all starting with 'SAML2_'.$this_idp_env_id. // so you can define different values for each IdP, all starting with 'SAML2_'.$this_idp_env_id
$this_idp_env_id = 'ldc'; $this_idp_env_id = 'ldc';
//This is variable is for simplesaml example only. //This is variable is for simplesaml example only.
// For real IdP, you must set the url values in the 'idp' config to conform to the IdP's real urls. // For real IdP, you must set the url values in the 'idp' config to conform to the IdP's real urls.
$idp_host = env('SAML2_'.$this_idp_env_id.'_IDP_HOST', 'http://localhost:8000/simplesaml'); $idp_host = env('SAML2_'.$this_idp_env_id.'_IDP_HOST', 'http://localhost:8000/simplesaml');
$settings = array( return $settings = array(
/***** /*****
* One Login Settings * One Login Settings
@ -18,21 +18,21 @@ $settings = array(
// or unencrypted messages if it expects them signed or encrypted // or unencrypted messages if it expects them signed or encrypted
// Also will reject the messages if not strictly follow the SAML // Also will reject the messages if not strictly follow the SAML
// standard: Destination, NameId, Conditions ... are validated too. // standard: Destination, NameId, Conditions ... are validated too.
'strict' => true, 'strict' => true, //@todo: make this depend on laravel config
// TODO: make this depend on laravel config
// Enable debug mode (to print errors). // Enable debug mode (to print errors)
'debug' => env('APP_DEBUG', false), 'debug' => env('APP_DEBUG', false),
// Service Provider Data that we are deploying. // Service Provider Data that we are deploying
'sp' => array( 'sp' => array(
// Specifies constraints on the name identifier to be used to // Specifies constraints on the name identifier to be used to
// represent the requested subject. // represent the requested subject.
// Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported. // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported
'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress', 'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
// Usually x509cert and privateKey of the SP are provided by files placed at // Usually x509cert and privateKey of the SP are provided by files placed at
// the certs folder. But we can also provide them with the following parameters. // the certs folder. But we can also provide them with the following parameters
'x509cert' => env('SAML2_'.$this_idp_env_id.'_SP_x509',''), 'x509cert' => env('SAML2_'.$this_idp_env_id.'_SP_x509',''),
'privateKey' => env('SAML2_'.$this_idp_env_id.'_SP_PRIVATEKEY',''), 'privateKey' => env('SAML2_'.$this_idp_env_id.'_SP_PRIVATEKEY',''),
@ -45,7 +45,7 @@ $settings = array(
'assertionConsumerService' => array( 'assertionConsumerService' => array(
// URL Location where the <Response> from the IdP will be returned, // URL Location where the <Response> from the IdP will be returned,
// using HTTP-POST binding. // using HTTP-POST binding.
// Leave blank to use the '{idpName}_acs' route, e.g. 'test_acs'. // Leave blank to use the '{idpName}_acs' route, e.g. 'test_acs'
'url' => '', 'url' => '',
), ),
// Specifies info about where and how the <Logout Response> message MUST be // Specifies info about where and how the <Logout Response> message MUST be
@ -54,16 +54,16 @@ $settings = array(
'singleLogoutService' => array( 'singleLogoutService' => array(
// URL Location where the <Response> from the IdP will be returned, // URL Location where the <Response> from the IdP will be returned,
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
// Leave blank to use the '{idpName}_sls' route, e.g. 'test_sls'. // Leave blank to use the '{idpName}_sls' route, e.g. 'test_sls'
'url' => '', 'url' => '',
), ),
), ),
// Identity Provider Data that we want connect with our SP. // Identity Provider Data that we want connect with our SP
'idp' => array( 'idp' => array(
// Identifier of the IdP entity (must be a URI). // Identifier of the IdP entity (must be a URI)
'entityId' => env('SAML2_'.$this_idp_env_id.'_IDP_ENTITYID', $idp_host . '/saml2/idp/metadata.php'), 'entityId' => env('SAML2_'.$this_idp_env_id.'_IDP_ENTITYID', $idp_host . '/saml2/idp/metadata.php'),
// SSO endpoint info of the IdP. (Authentication Request protocol). // SSO endpoint info of the IdP. (Authentication Request protocol)
'singleSignOnService' => array( 'singleSignOnService' => array(
// URL Target of the IdP where the SP will send the Authentication Request Message, // URL Target of the IdP where the SP will send the Authentication Request Message,
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
@ -75,15 +75,12 @@ $settings = array(
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SL_URL', $idp_host . '/saml2/idp/SingleLogoutService.php'), 'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SL_URL', $idp_host . '/saml2/idp/SingleLogoutService.php'),
), ),
// Public x509 certificate of the IdP. // Public x509 certificate of the IdP
// phpcs:ignore Generic.Files.LineLength.TooLong
'x509cert' => env('SAML2_'.$this_idp_env_id.'_IDP_x509', 'MIID/TCCAuWgAwIBAgIJAI4R3WyjjmB1MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjAeFw0xNDEyMDExNDM2MjVaFw0yNDExMzAxNDM2MjVaMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbzW/EpEv+qqZzfT1Buwjg9nnNNVrxkCfuR9fQiQw2tSouS5X37W5h7RmchRt54wsm046PDKtbSz1NpZT2GkmHN37yALW2lY7MyVUC7itv9vDAUsFr0EfKIdCKgxCKjrzkZ5ImbNvjxf7eA77PPGJnQ/UwXY7W+cvLkirp0K5uWpDk+nac5W0JXOCFR1BpPUJRbz2jFIEHyChRt7nsJZH6ejzNqK9lABEC76htNy1Ll/D3tUoPaqo8VlKW3N3MZE0DB9O7g65DmZIIlFqkaMH3ALd8adodJtOvqfDU/A6SxuwMfwDYPjoucykGDu1etRZ7dF2gd+W+1Pn7yizPT1q8CAwEAAaNQME4wHQYDVR0OBBYEFPsn8tUHN8XXf23ig5Qro3beP8BuMB8GA1UdIwQYMBaAFPsn8tUHN8XXf23ig5Qro3beP8BuMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAGu60odWFiK+DkQekozGnlpNBQz5lQ/bwmOWdktnQj6HYXu43e7sh9oZWArLYHEOyMUekKQAxOK51vbTHzzw66BZU91/nqvaOBfkJyZKGfluHbD0/hfOl/D5kONqI9kyTu4wkLQcYGyuIi75CJs15uA03FSuULQdY/Liv+czS/XYDyvtSLnu43VuAQWN321PQNhuGueIaLJANb2C5qq5ilTBUw6PxY9Z+vtMjAjTJGKEkE/tQs7CvzLPKXX3KTD9lIILmX5yUC3dLgjVKi1KGDqNApYGOMtjr5eoxPQrqDBmyx3flcy0dQTdLXud3UjWVW3N0PYgJtw5yBsS74QTGD4='), 'x509cert' => env('SAML2_'.$this_idp_env_id.'_IDP_x509', 'MIID/TCCAuWgAwIBAgIJAI4R3WyjjmB1MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjAeFw0xNDEyMDExNDM2MjVaFw0yNDExMzAxNDM2MjVaMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbzW/EpEv+qqZzfT1Buwjg9nnNNVrxkCfuR9fQiQw2tSouS5X37W5h7RmchRt54wsm046PDKtbSz1NpZT2GkmHN37yALW2lY7MyVUC7itv9vDAUsFr0EfKIdCKgxCKjrzkZ5ImbNvjxf7eA77PPGJnQ/UwXY7W+cvLkirp0K5uWpDk+nac5W0JXOCFR1BpPUJRbz2jFIEHyChRt7nsJZH6ejzNqK9lABEC76htNy1Ll/D3tUoPaqo8VlKW3N3MZE0DB9O7g65DmZIIlFqkaMH3ALd8adodJtOvqfDU/A6SxuwMfwDYPjoucykGDu1etRZ7dF2gd+W+1Pn7yizPT1q8CAwEAAaNQME4wHQYDVR0OBBYEFPsn8tUHN8XXf23ig5Qro3beP8BuMB8GA1UdIwQYMBaAFPsn8tUHN8XXf23ig5Qro3beP8BuMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAGu60odWFiK+DkQekozGnlpNBQz5lQ/bwmOWdktnQj6HYXu43e7sh9oZWArLYHEOyMUekKQAxOK51vbTHzzw66BZU91/nqvaOBfkJyZKGfluHbD0/hfOl/D5kONqI9kyTu4wkLQcYGyuIi75CJs15uA03FSuULQdY/Liv+czS/XYDyvtSLnu43VuAQWN321PQNhuGueIaLJANb2C5qq5ilTBUw6PxY9Z+vtMjAjTJGKEkE/tQs7CvzLPKXX3KTD9lIILmX5yUC3dLgjVKi1KGDqNApYGOMtjr5eoxPQrqDBmyx3flcy0dQTdLXud3UjWVW3N0PYgJtw5yBsS74QTGD4='),
/* /*
* Instead of use the whole x509cert you can use a fingerprint * Instead of use the whole x509cert you can use a fingerprint
* (openssl x509 -noout -fingerprint -in "idp.crt" to generate it) * (openssl x509 -noout -fingerprint -in "idp.crt" to generate it)
*/ */
// 'certFingerprint' => '', // 'certFingerprint' => '',
), ),
@ -95,7 +92,7 @@ $settings = array(
* *
* *
*/ */
// Security settings. // Security settings
'security' => array( 'security' => array(
'signatureAlgorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1', 'signatureAlgorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
@ -108,7 +105,7 @@ $settings = array(
'nameIdEncrypted' => false, 'nameIdEncrypted' => false,
// Indicates whether the <samlp:AuthnRequest> messages sent by this SP // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
// will be signed. [The Metadata of the SP will offer this info]. // will be signed. [The Metadata of the SP will offer this info]
'authnRequestsSigned' => true, 'authnRequestsSigned' => true,
// Indicates whether the <samlp:logoutRequest> messages sent by this SP // Indicates whether the <samlp:logoutRequest> messages sent by this SP
@ -119,42 +116,37 @@ $settings = array(
// will be signed. // will be signed.
'logoutResponseSigned' => true, 'logoutResponseSigned' => true,
/** /* Sign the Metadata
* Sign the Metadata False || True (use sp certs) || array (
* False || True (use sp certs) || array ( keyFileName => 'metadata.key',
* keyFileName => 'metadata.key', certFileName => 'metadata.crt'
* certFileName => 'metadata.crt' )
* )
*/ */
'signMetadata' => true, 'signMetadata' => true,
/** signatures and encryptions required */ /** signatures and encryptions required **/
// Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and // Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and
// <samlp:LogoutResponse> elements received by this SP to be signed. // <samlp:LogoutResponse> elements received by this SP to be signed.
'wantMessagesSigned' => true, 'wantMessagesSigned' => true,
// Indicates a requirement for the <saml:Assertion> elements received by // Indicates a requirement for the <saml:Assertion> elements received by
// this SP to be signed. [The Metadata of the SP will offer this info]. // this SP to be signed. [The Metadata of the SP will offer this info]
'wantAssertionsSigned' => true, 'wantAssertionsSigned' => true,
// Indicates a requirement for the NameID received by // Indicates a requirement for the NameID received by
// this SP to be encrypted. // this SP to be encrypted.
'wantNameIdEncrypted' => false, 'wantNameIdEncrypted' => false,
/** // Authentication context.
* Authentication context. // Set to false and no AuthContext will be sent in the AuthNRequest,
* Set to false and no AuthContext will be sent in the AuthNRequest, // Set true or don't present thi parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
* Set true or don't present thi parameter and you will get an // Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'),
* AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
* Set an array with the possible auth context values: array
* ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'),
*/
'requestedAuthnContext' => false, 'requestedAuthnContext' => false,
), ),
// Contact information template, it is recommended to suply a technical and support contacts. // Contact information template, it is recommended to suply a technical and support contacts
'contactPerson' => array( 'contactPerson' => array(
'technical' => array( 'technical' => array(
'givenName' => 'Vincent BRIDIER', 'givenName' => 'Vincent BRIDIER',
@ -166,7 +158,7 @@ $settings = array(
), ),
), ),
// Organization information template, the info in en_US lang is recomended, add more if required. // Organization information template, the info in en_US lang is recomended, add more if required
'organization' => array( 'organization' => array(
'fr-FR' => array( 'fr-FR' => array(
'name' => 'LDC', 'name' => 'LDC',
@ -175,8 +167,7 @@ $settings = array(
), ),
), ),
/* /* Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] http://saml2int.org/profile/current
Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] http://saml2int.org/profile/current
'authnRequestsSigned' => false, // SP SHOULD NOT sign the <samlp:AuthnRequest>, 'authnRequestsSigned' => false, // SP SHOULD NOT sign the <samlp:AuthnRequest>,
// MUST NOT assume that the IdP validates the sign // MUST NOT assume that the IdP validates the sign
@ -186,5 +177,3 @@ $settings = array(
*/ */
); );
return $settings;

View file

@ -1,14 +1,14 @@
<?php <?php
// If you choose to use ENV vars to define these values, give this IdP its own env var names // If you choose to use ENV vars to define these values, give this IdP its own env var names
// so you can define different values for each IdP, all starting with 'SAML2_'.$this_idp_env_id. // so you can define different values for each IdP, all starting with 'SAML2_'.$this_idp_env_id
$this_idp_env_id = 'ldc'; $this_idp_env_id = 'ldc';
//This is variable is for simplesaml example only. //This is variable is for simplesaml example only.
// For real IdP, you must set the url values in the 'idp' config to conform to the IdP's real urls. // For real IdP, you must set the url values in the 'idp' config to conform to the IdP's real urls.
$idp_host = env('SAML2_'.$this_idp_env_id.'_IDP_HOST', 'http://localhost:8000/simplesaml'); $idp_host = env('SAML2_'.$this_idp_env_id.'_IDP_HOST', 'http://localhost:8000/simplesaml');
$settings = array( return $settings = array(
/***** /*****
* One Login Settings * One Login Settings
@ -18,21 +18,21 @@ $settings = array(
// or unencrypted messages if it expects them signed or encrypted // or unencrypted messages if it expects them signed or encrypted
// Also will reject the messages if not strictly follow the SAML // Also will reject the messages if not strictly follow the SAML
// standard: Destination, NameId, Conditions ... are validated too. // standard: Destination, NameId, Conditions ... are validated too.
'strict' => true, 'strict' => true, //@todo: make this depend on laravel config
// TODO: make this depend on laravel config.
// Enable debug mode (to print errors) . // Enable debug mode (to print errors)
'debug' => env('APP_DEBUG', false), 'debug' => env('APP_DEBUG', false),
// Service Provider Data that we are deploying. // Service Provider Data that we are deploying
'sp' => array( 'sp' => array(
// Specifies constraints on the name identifier to be used to // Specifies constraints on the name identifier to be used to
// represent the requested subject. // represent the requested subject.
// Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported. // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported
'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent', 'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
// Usually x509cert and privateKey of the SP are provided by files placed at // Usually x509cert and privateKey of the SP are provided by files placed at
// the certs folder. But we can also provide them with the following parameters. // the certs folder. But we can also provide them with the following parameters
'x509cert' => env('SAML2_'.$this_idp_env_id.'_SP_x509',''), 'x509cert' => env('SAML2_'.$this_idp_env_id.'_SP_x509',''),
'privateKey' => env('SAML2_'.$this_idp_env_id.'_SP_PRIVATEKEY',''), 'privateKey' => env('SAML2_'.$this_idp_env_id.'_SP_PRIVATEKEY',''),
@ -45,7 +45,7 @@ $settings = array(
'assertionConsumerService' => array( 'assertionConsumerService' => array(
// URL Location where the <Response> from the IdP will be returned, // URL Location where the <Response> from the IdP will be returned,
// using HTTP-POST binding. // using HTTP-POST binding.
// Leave blank to use the '{idpName}_acs' route, e.g. 'test_acs'. // Leave blank to use the '{idpName}_acs' route, e.g. 'test_acs'
'url' => '', 'url' => '',
), ),
// Specifies info about where and how the <Logout Response> message MUST be // Specifies info about where and how the <Logout Response> message MUST be
@ -54,16 +54,16 @@ $settings = array(
'singleLogoutService' => array( 'singleLogoutService' => array(
// URL Location where the <Response> from the IdP will be returned, // URL Location where the <Response> from the IdP will be returned,
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
// Leave blank to use the '{idpName}_sls' route, e.g. 'test_sls'. // Leave blank to use the '{idpName}_sls' route, e.g. 'test_sls'
'url' => '', 'url' => '',
), ),
), ),
// Identity Provider Data that we want connect with our SP. // Identity Provider Data that we want connect with our SP
'idp' => array( 'idp' => array(
// Identifier of the IdP entity (must be a URI). // Identifier of the IdP entity (must be a URI)
'entityId' => env('SAML2_'.$this_idp_env_id.'_IDP_ENTITYID', $idp_host . '/saml2/idp/metadata.php'), 'entityId' => env('SAML2_'.$this_idp_env_id.'_IDP_ENTITYID', $idp_host . '/saml2/idp/metadata.php'),
// SSO endpoint info of the IdP. (Authentication Request protocol). // SSO endpoint info of the IdP. (Authentication Request protocol)
'singleSignOnService' => array( 'singleSignOnService' => array(
// URL Target of the IdP where the SP will send the Authentication Request Message, // URL Target of the IdP where the SP will send the Authentication Request Message,
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
@ -75,15 +75,12 @@ $settings = array(
// using HTTP-Redirect binding. // using HTTP-Redirect binding.
'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SL_URL', $idp_host . '/saml2/idp/SingleLogoutService.php'), 'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SL_URL', $idp_host . '/saml2/idp/SingleLogoutService.php'),
), ),
// Public x509 certificate of the IdP. // Public x509 certificate of the IdP
//phpcs:ignore Generic.Files.LineLength.TooLong
'x509cert' => env('SAML2_'.$this_idp_env_id.'_IDP_x509', 'MIID/TCCAuWgAwIBAgIJAI4R3WyjjmB1MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjAeFw0xNDEyMDExNDM2MjVaFw0yNDExMzAxNDM2MjVaMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbzW/EpEv+qqZzfT1Buwjg9nnNNVrxkCfuR9fQiQw2tSouS5X37W5h7RmchRt54wsm046PDKtbSz1NpZT2GkmHN37yALW2lY7MyVUC7itv9vDAUsFr0EfKIdCKgxCKjrzkZ5ImbNvjxf7eA77PPGJnQ/UwXY7W+cvLkirp0K5uWpDk+nac5W0JXOCFR1BpPUJRbz2jFIEHyChRt7nsJZH6ejzNqK9lABEC76htNy1Ll/D3tUoPaqo8VlKW3N3MZE0DB9O7g65DmZIIlFqkaMH3ALd8adodJtOvqfDU/A6SxuwMfwDYPjoucykGDu1etRZ7dF2gd+W+1Pn7yizPT1q8CAwEAAaNQME4wHQYDVR0OBBYEFPsn8tUHN8XXf23ig5Qro3beP8BuMB8GA1UdIwQYMBaAFPsn8tUHN8XXf23ig5Qro3beP8BuMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAGu60odWFiK+DkQekozGnlpNBQz5lQ/bwmOWdktnQj6HYXu43e7sh9oZWArLYHEOyMUekKQAxOK51vbTHzzw66BZU91/nqvaOBfkJyZKGfluHbD0/hfOl/D5kONqI9kyTu4wkLQcYGyuIi75CJs15uA03FSuULQdY/Liv+czS/XYDyvtSLnu43VuAQWN321PQNhuGueIaLJANb2C5qq5ilTBUw6PxY9Z+vtMjAjTJGKEkE/tQs7CvzLPKXX3KTD9lIILmX5yUC3dLgjVKi1KGDqNApYGOMtjr5eoxPQrqDBmyx3flcy0dQTdLXud3UjWVW3N0PYgJtw5yBsS74QTGD4='), 'x509cert' => env('SAML2_'.$this_idp_env_id.'_IDP_x509', 'MIID/TCCAuWgAwIBAgIJAI4R3WyjjmB1MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjAeFw0xNDEyMDExNDM2MjVaFw0yNDExMzAxNDM2MjVaMIGUMQswCQYDVQQGEwJBUjEVMBMGA1UECAwMQnVlbm9zIEFpcmVzMRUwEwYDVQQHDAxCdWVub3MgQWlyZXMxDDAKBgNVBAoMA1NJVTERMA8GA1UECwwIU2lzdGVtYXMxFDASBgNVBAMMC09yZy5TaXUuQ29tMSAwHgYJKoZIhvcNAQkBFhFhZG1pbmlAc2l1LmVkdS5hcjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbzW/EpEv+qqZzfT1Buwjg9nnNNVrxkCfuR9fQiQw2tSouS5X37W5h7RmchRt54wsm046PDKtbSz1NpZT2GkmHN37yALW2lY7MyVUC7itv9vDAUsFr0EfKIdCKgxCKjrzkZ5ImbNvjxf7eA77PPGJnQ/UwXY7W+cvLkirp0K5uWpDk+nac5W0JXOCFR1BpPUJRbz2jFIEHyChRt7nsJZH6ejzNqK9lABEC76htNy1Ll/D3tUoPaqo8VlKW3N3MZE0DB9O7g65DmZIIlFqkaMH3ALd8adodJtOvqfDU/A6SxuwMfwDYPjoucykGDu1etRZ7dF2gd+W+1Pn7yizPT1q8CAwEAAaNQME4wHQYDVR0OBBYEFPsn8tUHN8XXf23ig5Qro3beP8BuMB8GA1UdIwQYMBaAFPsn8tUHN8XXf23ig5Qro3beP8BuMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAGu60odWFiK+DkQekozGnlpNBQz5lQ/bwmOWdktnQj6HYXu43e7sh9oZWArLYHEOyMUekKQAxOK51vbTHzzw66BZU91/nqvaOBfkJyZKGfluHbD0/hfOl/D5kONqI9kyTu4wkLQcYGyuIi75CJs15uA03FSuULQdY/Liv+czS/XYDyvtSLnu43VuAQWN321PQNhuGueIaLJANb2C5qq5ilTBUw6PxY9Z+vtMjAjTJGKEkE/tQs7CvzLPKXX3KTD9lIILmX5yUC3dLgjVKi1KGDqNApYGOMtjr5eoxPQrqDBmyx3flcy0dQTdLXud3UjWVW3N0PYgJtw5yBsS74QTGD4='),
/* /*
* Instead of use the whole x509cert you can use a fingerprint * Instead of use the whole x509cert you can use a fingerprint
* (openssl x509 -noout -fingerprint -in "idp.crt" to generate it) * (openssl x509 -noout -fingerprint -in "idp.crt" to generate it)
*/ */
// 'certFingerprint' => '', // 'certFingerprint' => '',
), ),
@ -95,7 +92,7 @@ $settings = array(
* *
* *
*/ */
// Security settings. // Security settings
'security' => array( 'security' => array(
/** signatures and encryptions offered */ /** signatures and encryptions offered */
@ -104,10 +101,8 @@ $settings = array(
// will be encrypted. // will be encrypted.
'nameIdEncrypted' => false, 'nameIdEncrypted' => false,
/** // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
* Indicates whether the <samlp:AuthnRequest> messages sent by this SP // will be signed. [The Metadata of the SP will offer this info]
* will be signed. [The Metadata of the SP will offer this info]
*/
'authnRequestsSigned' => false, 'authnRequestsSigned' => false,
// Indicates whether the <samlp:logoutRequest> messages sent by this SP // Indicates whether the <samlp:logoutRequest> messages sent by this SP
@ -118,46 +113,37 @@ $settings = array(
// will be signed. // will be signed.
'logoutResponseSigned' => false, 'logoutResponseSigned' => false,
/** /* Sign the Metadata
* Sign the Metadata False || True (use sp certs) || array (
* False || True (use sp certs) || array ( keyFileName => 'metadata.key',
* keyFileName => 'metadata.key', certFileName => 'metadata.crt'
* certFileName => 'metadata.crt' )
* )
*/ */
'signMetadata' => false, 'signMetadata' => false,
/** signatures and encryptions required */ /** signatures and encryptions required **/
// Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and // Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and
// <samlp:LogoutResponse> elements received by this SP to be signed. // <samlp:LogoutResponse> elements received by this SP to be signed.
'wantMessagesSigned' => false, 'wantMessagesSigned' => false,
/** // Indicates a requirement for the <saml:Assertion> elements received by
* Indicates a requirement for the <saml:Assertion> elements received by // this SP to be signed. [The Metadata of the SP will offer this info]
* this SP to be signed.
* [The Metadata of the SP will offer this info]
* */
'wantAssertionsSigned' => false, 'wantAssertionsSigned' => false,
// Indicates a requirement for the NameID received by // Indicates a requirement for the NameID received by
// this SP to be encrypted. // this SP to be encrypted.
'wantNameIdEncrypted' => false, 'wantNameIdEncrypted' => false,
/** // Authentication context.
* Authentication context. // Set to false and no AuthContext will be sent in the AuthNRequest,
* Set to false and no AuthContext will be sent in the AuthNRequest, // Set true or don't present thi parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
* Set true or don't present thi parameter and you will get an // Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'),
* AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
* Set an array with the possible auth context values: array
* ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'),
*/
'requestedAuthnContext' => true, 'requestedAuthnContext' => true,
), ),
// Contact information template, it is recommended to suply a technical and support contacts. // Contact information template, it is recommended to suply a technical and support contacts
'contactPerson' => array( 'contactPerson' => array(
'technical' => array( 'technical' => array(
'givenName' => 'name', 'givenName' => 'name',
@ -169,7 +155,7 @@ $settings = array(
), ),
), ),
// Organization information template, the info in en_US lang is recomended, add more if required. // Organization information template, the info in en_US lang is recomended, add more if required
'organization' => array( 'organization' => array(
'en-US' => array( 'en-US' => array(
'name' => 'Name', 'name' => 'Name',
@ -178,8 +164,7 @@ $settings = array(
), ),
), ),
/* /* Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] http://saml2int.org/profile/current
Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] http://saml2int.org/profile/current
'authnRequestsSigned' => false, // SP SHOULD NOT sign the <samlp:AuthnRequest>, 'authnRequestsSigned' => false, // SP SHOULD NOT sign the <samlp:AuthnRequest>,
// MUST NOT assume that the IdP validates the sign // MUST NOT assume that the IdP validates the sign
@ -189,5 +174,3 @@ $settings = array(
*/ */
); );
return $settings;

View file

@ -1,6 +1,6 @@
<?php <?php
$settings = array( return $settings = array(
/** /**
* Array of IDP prefixes to be configured e.g. 'idpNames' => ['test1', 'test2', 'test3'], * Array of IDP prefixes to be configured e.g. 'idpNames' => ['test1', 'test2', 'test3'],
@ -58,8 +58,15 @@ $settings = array(
// e.g X-Forwarded-Proto / HTTP_X_FORWARDED_PROTO. This is useful if // e.g X-Forwarded-Proto / HTTP_X_FORWARDED_PROTO. This is useful if
// your application is running behind a load balancer which terminates // your application is running behind a load balancer which terminates
// SSL. // SSL.
// LDC WEB SET FALSE IF LOCAL. // LDC WEB SET FALSE IF LOCAL
'proxyVars' => true, 'proxyVars' => true,
);
return $settings; /**
* (Optional) Which class implements the route functions.
* If commented out, defaults to this lib's controller (Aacotroneo\Saml2\Http\Controllers\Saml2Controller).
* If you need to extend Saml2Controller (e.g. to override the `login()` function to pass
* a `$returnTo` argument), this value allows you to pass your own controller, and have
* it used in the routes definition.
*/
// 'saml2_controller' => '',
);

View file

@ -194,6 +194,6 @@ return [
| |
*/ */
'same_site' => 'lax', 'same_site' => null,
]; ];

View file

@ -1,6 +0,0 @@
<?php
return [
'wp_endpoint' => 'https://api.wordpress.org/core/version-check/1.7/',
'laravel_endpoint' => 'https://api.github.com/repos/laravel/laravel/releases'
];

View file

@ -1,8 +0,0 @@
<?php
return [
'gitlab' => [
'notify' => env('WEBHOOKS_GITLAB_NOTIFY', 'equipe.web@ldc.fr'),
'token' => env('WEBHOOKS_GITLAB_TOKEN')
]
];

View file

@ -1,41 +0,0 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
// * password
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGitReposTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('git_repos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('login')->nullable();
$table->string('password')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('git_repos');
}
}

View file

@ -1,83 +0,0 @@
<?php
use App\Enums\PhpVersion;
use App\Models\Project;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class ChangeProjectPhpToEnum extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$projects = Project::all();
DB::table('projects')->update(array('php' => '0'));
Schema::table('projects', function (Blueprint $table) {
$table->unsignedSmallInteger('php')->nullable(false)->comment('PHP version Enum')->change();
$table->timestamp('created_at')->nullable()->default(null)->change();
$table->timestamp('updated_at')->nullable()->default(null)->change();
});
$projects->map(function (Project $project) {
switch ($project->getRawOriginal('php')) {
case '5.6':
$project->php = PhpVersion::v5_6();
break;
case '7.3':
$project->php = PhpVersion::v7_3();
break;
case '7.4':
$project->php = PhpVersion::v7_4();
break;
case '8.0':
$project->php = PhpVersion::v8();
break;
case '8.1':
$project->php = PhpVersion::v8_1();
break;
}
$project->saveOrFail();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$projects = Project::all();
$projects->map(function (Project $project) {
switch ($project->getRawOriginal('php')) {
case PhpVersion::v5_6()->value:
$project->php = '5.6';
break;
case PhpVersion::v7_3()->value:
$project->php = '7.3';
break;
case PhpVersion::v7_4()->value:
$project->php = '7.4';
break;
case PhpVersion::v8()->value:
$project->php = '8.0';
break;
case PhpVersion::v8_1()->value:
$project->php = '8.1';
break;
}
$project->saveOrFail();
});
Schema::table('projects', function (Blueprint $table) {
$table->string('php', 20)->nullable(true)->change();
});
$projects->map(function (Project $project) {
$project->saveOrFail();
});
}
}

View file

@ -1,48 +0,0 @@
<?php
use App\Enums\Environment;
use App\Models\Server;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class ChangeServerEnToEnum extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$servers = Server::all();
DB::table('servers')->update(array('env' => '0'));
Schema::table('servers', function (Blueprint $table) {
$table->unsignedSmallInteger('env')->comment('Environement Enum')->change();
$table->timestamp('created_at')->nullable()->default(null)->change();
$table->timestamp('updated_at')->nullable()->default(null)->change();
});
$servers->map(function (Server $server) {
$server->env = $server->getRawOriginal('env') === 'PROD' ? Environment::PROD() : Environment::DEV();
$server->saveOrFail();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$servers = Server::all();
Schema::table('servers', function (Blueprint $table) {
$table->string('env', 20)->change();
});
$servers->map(function (Server $server) {
$server->env = $server->getRawOriginal('env') === Environment::PROD()->value ? 'PROD' : 'DEV';
$server->saveOrFail();
});
}
}

View file

@ -1,69 +0,0 @@
<?php
use App\Enums\ServerType;
use App\Models\Server;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class ChangeServerTypeToEnum extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$servers = Server::all();
DB::table('servers')->update(array('type' => '0'));
Schema::table('servers', function (Blueprint $table) {
$table->unsignedSmallInteger('type')->comment('Server Type Enum')->nullable()->change();
});
$servers->map(function (Server $server) {
switch ($server->getRawOriginal('type')) {
case 'DB':
$server->type = ServerType::DB();
break;
case 'WEB':
$server->type = ServerType::WEB();
break;
case 'ELASTIC':
$server->type = ServerType::ELASTIC();
break;
}
$server->saveOrFail();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$servers = Server::all();
$servers->map(function (Server $server) {
switch ($server->getRawOriginal('type')) {
case ServerType::DB()->value:
$server->type = 'DB';
break;
case ServerType::WEB()->value:
$server->type = 'WEB';
break;
case ServerType::ELASTIC()->value:
$server->type = 'ELASTIC';
break;
}
$server->saveOrFail();
});
Schema::table('servers', function (Blueprint $table) {
$table->string('type', 20)->change();
});
$servers->map(function (Server $server) {
$server->saveOrFail();
});
}
}

Some files were not shown because too many files have changed in this diff Show more