Compare commits

...

3 Commits

Author SHA1 Message Date
Alexis Bruneteau
15e56fea50 merged 2025-06-28 12:40:55 +02:00
Alexis Bruneteau
907c476567 fix 2025-06-28 12:30:33 +02:00
Alexis Bruneteau
fc9431db44 laravel almost done 2025-06-18 23:49:55 +02:00
90 changed files with 14817 additions and 150 deletions

3
.gitignore vendored
View File

@ -1,3 +1,6 @@
data/
.idea/
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/

View File

@ -116,3 +116,11 @@ All routes are prefixed with `/api/private` and require a **Bearer token**.
---
# Public API:
## Routes :
```
GET|HEAD api/artists
GET|HEAD api/galleries
GET|HEAD api/galleries/{gallery}/artworks
```

View File

@ -55,25 +55,30 @@ Listen 443
SSLCertificateKeyFile /usr/local/apache2/conf/server.key
# OIDC config - point to Keycloak via auth.local
OIDCProviderMetadataURL http://keycloak:8080/realms/soa/.well-known/openid-configuration
OIDCProviderMetadataURL https://auth.local/realms/master/.well-known/openid-configuration
OIDCClientID soa
OIDCRedirectURI https://api.local/api/redirect
OIDCClientSecret NuLgdHzPldRauqIln0I0TN5216PgX3Ty
OIDCRedirectURI https://api.local/api/private/redirect
OIDCClientSecret mysecret
OIDCCryptoPassphrase fdfd8280-13b5-11f0-a320-080027e6dc53
OIDCPassClaimsAs both
OIDCPassClaimsAs headers
OIDCClaimPrefix OIDC-
OIDCPassUserInfoAs claims
OIDCRemoteUserClaim email
OIDCScope "openid email profile"
OIDCSessionInactivityTimeout 86400
OIDCSSLValidateServer Off
# Proxy public API (no auth)
ProxyPass /public/ http://public_api:5001/
ProxyPassReverse /public/ http://public_api:5001/
ProxyPass /api/public http://public_api:5001/
ProxyPassReverse /api/public http://public_api:5001/
# Proxy private API (OIDC protected)
ProxyPass /private/ http://user_api:5002/
ProxyPassReverse /private/ http://user_api:5002/
ProxyPass /api/private http://private_api:5002/api/private
ProxyPassReverse /api/private http://private_api:5002/api/private
<Location /private>
<Location /api/private>
AuthType openid-connect
Require valid-user
RequestHeader set X-User-Email "%{HTTP_OIDC_EMAIL}i"
RequestHeader set X-User-Name "%{HTTP_OIDC_PREFERRED_USERNAME}i"
</Location>
</VirtualHost>

View File

@ -0,0 +1,11 @@
meta {
name: Artists
type: http
seq: 3
}
get {
url: {{URL}}/api/artists
body: none
auth: inherit
}

View File

@ -0,0 +1,11 @@
meta {
name: Galleries
type: http
seq: 1
}
get {
url: {{URL}}/api/galleries
body: none
auth: inherit
}

View File

@ -0,0 +1,11 @@
meta {
name: Gallery Artwork
type: http
seq: 2
}
get {
url: {{URL}}/api/galleries/{{gallery_id}}/artworks
body: none
auth: inherit
}

View File

@ -0,0 +1,8 @@
meta {
name: Public
seq: 2
}
auth {
mode: inherit
}

9
bruno/SOA/bruno.json Normal file
View File

@ -0,0 +1,9 @@
{
"version": "1",
"name": "SOA",
"type": "collection",
"ignore": [
"node_modules",
".git"
]
}

View File

@ -0,0 +1,4 @@
vars {
gallery_id: 6
URL: http://localhost:8000
}

View File

@ -1,6 +1,7 @@
version: '3.8'
services:
keycloak-db:
image: postgres:15
environment:
@ -35,7 +36,7 @@ services:
public_api:
build:
context: ./public
context: ./laravel
depends_on:
- keycloak
- mysql
@ -44,7 +45,7 @@ services:
networks:
- soa
user_api:
private_api:
build:
context: ./private
depends_on:
@ -65,7 +66,7 @@ services:
depends_on:
- keycloak
- public_api
- user_api
- private_api
volumes:
- ./apache/logs:/usr/local/apache2/conf/logs
environment:

75
keyclock-setup.sh Executable file
View File

@ -0,0 +1,75 @@
#!/bin/bash
# Variables
KC_HOST="http://localhost:8080"
REALM="master"
CLIENT_ID="soa"
CLIENT_SECRET="mysecret"
USERNAME="alexis"
PASSWORD="password"
# Fonction d'attente
wait_for_keycloak() {
echo "⏳ Attente de Keycloak..."
until curl -s "$KC_HOST" > /dev/null; do
sleep 2
done
echo "✅ Keycloak est prêt."
}
# Obtenir un token admin
get_admin_token() {
curl -s -X POST "$KC_HOST/realms/master/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin" \
-d "password=admin" \
-d "grant_type=password" \
-d "client_id=admin-cli" |
jq -r .access_token
}
# Créer un realm, client et utilisateur
setup_keycloak() {
TOKEN=$(get_admin_token)
echo "🛠️ Création du realm $REALM..."
curl -s -X POST "$KC_HOST/admin/realms" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"realm\":\"$REALM\",\"enabled\":true}" > /dev/null
echo "🛠️ Création du client $CLIENT_ID..."
curl -s -X POST "$KC_HOST/admin/realms/$REALM/clients" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"clientId\": \"$CLIENT_ID\",
\"enabled\": true,
\"publicClient\": false,
\"secret\": \"$CLIENT_SECRET\",
\"redirectUris\": [\"*\"],
\"standardFlowEnabled\": true
}" > /dev/null
echo "👤 Création de l'utilisateur $USERNAME..."
curl -s -X POST "$KC_HOST/admin/realms/$REALM/users" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"username\": \"$USERNAME\",
\"enabled\": true,
\"credentials\": [{
\"type\": \"password\",
\"value\": \"$PASSWORD\",
\"temporary\": false
}]
}" > /dev/null
echo "✅ Configuration terminée !"
echo "🔐 Utilisateur: $USERNAME / $PASSWORD"
echo "🪪 Client secret: $CLIENT_SECRET"
}
# Lancer le setup
wait_for_keycloak
setup_keycloak

18
laravel/.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

65
laravel/.env.example Normal file
View File

@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

11
laravel/.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
laravel/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

73
laravel/Dockerfile Normal file
View File

@ -0,0 +1,73 @@
# ---------- Stage 1: Build with Composer ----------
FROM php:8.2-cli-alpine AS build
WORKDIR /app
# Install Composer and build dependencies
RUN apk add --no-cache \
libzip-dev zip unzip curl git oniguruma-dev libxml2-dev
# Install PHP extensions for Laravel
RUN docker-php-ext-install zip mbstring xml
# Install Composer
RUN curl -sS https://getcomposer.org/installer | php && \
mv composer.phar /usr/local/bin/composer
# Copy project files and install dependencies
COPY . .
RUN composer install --no-dev --optimize-autoloader --no-interaction
# ---------- Stage 2: Production Image ----------
FROM php:8.2-fpm-alpine
# Set working directory
WORKDIR /var/www
# Install system and PHP dependencies
RUN apk add --no-cache \
nginx \
supervisor \
bash \
mysql-client \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
libxml2-dev \
oniguruma-dev \
libzip-dev \
curl \
git \
openssh \
php-pear \
gcc g++ make autoconf libtool linux-headers
# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg && \
docker-php-ext-install pdo pdo_mysql mbstring gd xml zip && \
pecl install redis && \
docker-php-ext-enable redis
# Clean up build tools
RUN apk del gcc g++ make autoconf libtool
# Install Ansible
RUN apk add --no-cache ansible
# Copy built app from previous stage
COPY --from=build /app /var/www
# Set proper permissions for Laravel
RUN chown -R www-data:www-data /var/www/storage /var/www/bootstrap/cache /var/www/database && \
chmod -R 755 /var/www/storage /var/www/bootstrap/cache /var/www/database
# Copy config files
COPY nginx.conf /etc/nginx/nginx.conf
COPY supervisord.conf /etc/supervisord.conf
# Expose HTTP port
EXPOSE 80
# Start services
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]

61
laravel/README.md Normal file
View File

@ -0,0 +1,61 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
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.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of 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 Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## 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

@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
class ArtistController extends Controller
{
/**
* Affiche la liste des utilisateurs qui sont artistes.
* Un "artiste" est défini comme un utilisateur qui possède au moins une galerie.
*/
public function index()
{
$artists = User::whereHas('ownedGalleries')
->select('id', 'username', 'first_name', 'last_name', 'bio', 'profile_picture_url')
->paginate(15);
return UserResource::collection($artists);
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\Gallery;
use Illuminate\Http\Request;
use App\Http\Resources\GalleryResource;
class GalleryController extends Controller
{
/**
* Affiche la liste des galeries publiques.
*/
public function index()
{
$publicGalleries = Gallery::where('is_public', true)
->with('owner:id,username,first_name,last_name') // Eager loading pour la performance
->latest() // Trie par date de création (la plus récente d'abord)
->paginate(15);
return GalleryResource::collection($publicGalleries);
}
/**
* Affiche les oeuvres d'une galerie spécifique, si elle est publique.
*/
public function showArtworks(Gallery $gallery)
{
// Vérification cruciale : la galerie doit être publique
if (!$gallery->is_public) {
return response()->json(['message' => 'Gallery not found.'], 404);
}
$artworks = $gallery->artworks()
->with('creator:id,username')
->where('is_public', true)
->paginate(15);
return response()->json($artworks);
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class ArtworkResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'isPublic' => $this->is_public,
'publishedOn' => $this->publication_date ? $this->publication_date->toIso8601String() : null,
'owner' => new UserResource($this->whenLoaded('owner')), // Charge la ressource User si l'owner est chargé
];
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class GalleryResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'isPublic' => $this->is_public,
'publishedOn' => $this->publication_date,
'owner' => new UserResource($this->whenLoaded('owner')), // Charge la ressource User si l'owner est chargé
];
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'username' => $this->username,
'fullName' => $this->first_name . ' ' . $this->last_name,
'bio' => $this->bio,
'avatar' => $this->profile_picture_url,
];
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Artwork extends Model
{
use HasFactory;
protected $fillable = [
'gallery_id',
'creator_id',
'title',
'description',
'image_url',
'medium',
'dimensions',
'creation_year',
'price',
'is_visible',
'is_for_sale',
];
/**
* Le créateur de l'oeuvre.
*/
public function creator()
{
return $this->belongsTo(User::class, 'creator_id');
}
/**
* La galerie à laquelle l'oeuvre appartient.
*/
public function gallery()
{
return $this->belongsTo(Gallery::class);
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
use HasFactory;
protected $fillable = [
'owner_id',
'title',
'description',
'is_public',
'publication_date',
];
/**
* Le propriétaire de la galerie.
*/
public function owner()
{
return $this->belongsTo(User::class, 'owner_id');
}
/**
* Les oeuvres contenues dans cette galerie.
*/
public function artworks()
{
return $this->hasMany(Artwork::class);
}
}

198
laravel/app/Models/User.php Normal file
View File

@ -0,0 +1,198 @@
<?php
namespace App\Models;
use database\GalleryMember;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'username',
'email',
'alias',
'password_hash',
'first_name',
'last_name',
'bio',
'profile_picture_url'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password_hash',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
/**
* Get the password for the user (Laravel Auth compatibility).
*/
public function getAuthPassword()
{
return $this->password_hash;
}
/**
* Set the password hash when setting password.
*/
public function setPasswordAttribute($password)
{
$this->attributes['password_hash'] = bcrypt($password);
}
/**
* Get the user's full name.
*/
public function getFullNameAttribute(): string
{
return trim($this->first_name . ' ' . $this->last_name);
}
/**
* Scope pour rechercher par nom d'utilisateur ou email.
*/
public function scopeSearch($query, $search)
{
return $query->where('username', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%")
->orWhere('first_name', 'like', "%{$search}%")
->orWhere('last_name', 'like', "%{$search}%");
}
// ===== RELATIONS =====
/**
* Galeries possédées par cet utilisateur.
*/
public function ownedGalleries()
{
return $this->hasMany(Gallery::class, 'owner_id');
}
/**
* Œuvres créées par cet utilisateur.
*/
public function artworks()
{
return $this->hasMany(Artwork::class, 'creator_id');
}
/**
* Galeries auxquelles cet utilisateur a accès (invitations).
*/
public function galleryMemberships()
{
return $this->hasMany(GalleryMember::class, 'user_id');
}
/**
* Galeries auxquelles l'utilisateur a accès avec statut accepté.
*/
public function accessibleGalleries()
{
return $this->belongsToMany(Gallery::class, 'gallery_members', 'user_id', 'gallery_id')
->wherePivot('status', 'accepted')
->withPivot(['role', 'status', 'invited_at', 'updated_at']);
}
/**
* Invitations en attente pour cet utilisateur.
*/
public function pendingInvitations()
{
return $this->belongsToMany(Gallery::class, 'gallery_members', 'user_id', 'gallery_id')
->wherePivot('status', 'pending')
->withPivot(['role', 'status', 'invited_at', 'updated_at']);
}
/**
* Vérifier si l'utilisateur peut accéder à une galerie.
*/
public function canAccessGallery($galleryId): bool
{
// Propriétaire de la galerie
if ($this->ownedGalleries()->where('id', $galleryId)->exists()) {
return true;
}
// Membre avec accès accepté
return $this->galleryMemberships()
->where('gallery_id', $galleryId)
->where('status', 'accepted')
->exists();
}
/**
* Vérifier si l'utilisateur peut éditer une galerie.
*/
public function canEditGallery($galleryId): bool
{
// Propriétaire
if ($this->ownedGalleries()->where('id', $galleryId)->exists()) {
return true;
}
// Membre avec rôle editor
return $this->galleryMemberships()
->where('gallery_id', $galleryId)
->where('status', 'accepted')
->where('role', 'editor')
->exists();
}
/**
* Obtenir le rôle de l'utilisateur dans une galerie.
*/
public function getRoleInGallery($galleryId): ?string
{
// Propriétaire
if ($this->ownedGalleries()->where('id', $galleryId)->exists()) {
return 'owner';
}
// Membre
$membership = $this->galleryMemberships()
->where('gallery_id', $galleryId)
->where('status', 'accepted')
->first();
return $membership ? $membership->role : null;
}
/**
* Statistiques de l'utilisateur.
*/
public function getStatsAttribute(): array
{
return [
'galleries_count' => $this->ownedGalleries()->count(),
'artworks_count' => $this->artworks()->count(),
'public_galleries_count' => $this->ownedGalleries()->where('is_public', true)->count(),
'artworks_for_sale_count' => $this->artworks()->where('is_for_sale', true)->count(),
];
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

18
laravel/artisan Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

19
laravel/bootstrap/app.php Normal file
View File

@ -0,0 +1,19 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

2
laravel/bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,5 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

78
laravel/composer.json Normal file
View File

@ -0,0 +1,78 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": [
"laravel",
"framework"
],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.13",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.3"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8091
laravel/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
laravel/config/app.php Normal file
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

115
laravel/config/auth.php Normal file
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

108
laravel/config/cache.php Normal file
View File

@ -0,0 +1,108 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

174
laravel/config/database.php Normal file
View File

@ -0,0 +1,174 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

View File

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

132
laravel/config/logging.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
laravel/config/mail.php Normal file
View File

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

112
laravel/config/queue.php Normal file
View File

@ -0,0 +1,112 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

View File

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'resend' => [
'key' => env('RESEND_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
laravel/config/session.php Normal file
View File

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

1
laravel/database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,36 @@
<?php
namespace database;
use App\Models\Gallery;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class GalleryMember extends Model
{
use HasFactory;
protected $table = 'gallery_members';
protected $primaryKey = ['gallery_id', 'user_id'];
public $timestamps = true;
protected $fillable = [
'gallery_id',
'user_id',
'role',
'status',
'invited_at',
'entered_at',
'updated_at',
];
public function gallery()
{
return $this->belongsTo(Gallery::class, 'gallery_id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,34 @@
<?php
// database/migrations/2024_01_01_000000_create_users_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id(); // Auto-increment primary key
$table->string('username', 50)->unique();
$table->string('email', 255)->unique();
$table->string('password_hash', 255);
$table->string('first_name', 100)->nullable();
$table->string('last_name', 100)->nullable();
$table->text('bio')->nullable();
$table->string('profile_picture_url', 255)->nullable();
$table->timestamps(); // created_at et updated_at
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration');
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('artworks', function (Blueprint $table) {
$table->id();
$table->foreignId('gallery_id')->constrained('galleries')->onDelete('cascade');
$table->foreignId('creator_id')->constrained('users')->onDelete('cascade');
$table->string('title');
$table->text('description')->nullable();
$table->string('image_url');
$table->string('medium', 100)->nullable();
$table->string('dimensions', 50)->nullable();
$table->year('creation_year')->nullable();
$table->decimal('price', 10, 2)->nullable();
$table->boolean('is_for_sale')->default(false);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('artworks');
}
};

View File

@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('galleries', function (Blueprint $table) {
$table->id();
$table->foreignId('owner_id')->constrained('users')->onDelete('cascade');
$table->string('title');
$table->text('description')->nullable();
$table->boolean('is_public')->default(false);
$table->timestamp('publication_date')->nullable();
$table->timestamps(); // created_at et updated_at
});
}
public function down(): void
{
Schema::dropIfExists('galleries');
}
};

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('gallery_members', function (Blueprint $table) {
$table->foreignId('gallery_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('role', 50)->default('viewer');
$table->string('status', 50)->default('pending');
$table->timestamp('invited_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
// Clé primaire composite
$table->primary(['gallery_id', 'user_id']);
});
}
public function down(): void
{
Schema::dropIfExists('gallery_members');
}
};

View File

@ -0,0 +1,171 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class ArtworkSeeder extends Seeder
{
public function run()
{
$artworks = [
// Galerie de Monet (id: 1)
[
'gallery_id' => 1,
'creator_id' => 1,
'title' => 'Nymphéas, Matin',
'description' => 'Capturer la lumière matinale sur l\'étang de mon jardin reste un défi constant. Cette œuvre représente la sérénité du petit matin.',
'image_url' => 'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=800&h=600',
'medium' => 'Huile sur toile',
'dimensions' => '200cm x 300cm',
'creation_year' => 1920,
'price' => 2500000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(35),
'updated_at' => Carbon::now()->subDays(20),
],
[
'gallery_id' => 1,
'creator_id' => 1,
'title' => 'Le Pont Japonais au Coucher du Soleil',
'description' => 'Mon pont japonais sous une lumière dorée. Les reflets dans l\'eau créent une symphonie de couleurs chaudes.',
'image_url' => 'https://images.unsplash.com/photo-1541961017774-22349e4a1262?w=800&h=600',
'medium' => 'Huile sur toile',
'dimensions' => '150cm x 120cm',
'creation_year' => 1922,
'price' => 1800000.00,
'is_for_sale' => true,
'created_at' => Carbon::now()->subDays(32),
'updated_at' => Carbon::now()->subDays(18),
],
// Galerie de Frida (id: 2)
[
'gallery_id' => 2,
'creator_id' => 2,
'title' => 'Autoportrait aux Épines',
'description' => 'Un regard introspectif sur ma douleur physique et émotionnelle. Les épines représentent les épreuves de ma vie.',
'image_url' => 'https://images.unsplash.com/photo-1571115764595-644a1f56a55c?w=800&h=600',
'medium' => 'Huile sur masonite',
'dimensions' => '40cm x 30cm',
'creation_year' => 1940,
'price' => 3200000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(30),
'updated_at' => Carbon::now()->subDays(15),
],
[
'gallery_id' => 2,
'creator_id' => 2,
'title' => 'Les Deux Fridas',
'description' => 'Mes deux identités : la Frida aimée par Diego et celle qui existe indépendamment. Une œuvre sur la dualité de l\'être.',
'image_url' => 'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=800&h=600',
'medium' => 'Huile sur toile',
'dimensions' => '173cm x 173cm',
'creation_year' => 1939,
'price' => 5000000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(28),
'updated_at' => Carbon::now()->subDays(12),
],
// Galerie de Van Gogh (id: 3)
[
'gallery_id' => 3,
'creator_id' => 3,
'title' => 'La Nuit Étoilée sur le Rhône',
'description' => 'Les étoiles ont toujours fasciné mon esprit tourmenté. Cette toile capture la magie d\'une nuit d\'été à Arles.',
'image_url' => 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600',
'medium' => 'Huile sur toile',
'dimensions' => '72cm x 92cm',
'creation_year' => 1888,
'price' => 4500000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(20),
'updated_at' => Carbon::now()->subDays(10),
],
// Galerie de Leonardo (id: 4)
[
'gallery_id' => 4,
'creator_id' => 4,
'title' => 'Étude Anatomique - Main Gauche',
'description' => 'Une étude détaillée de l\'anatomie humaine, base essentielle pour tout artiste souhaitant représenter le corps avec précision.',
'image_url' => 'https://images.unsplash.com/photo-1594736797933-d0151ba6e056?w=800&h=600',
'medium' => 'Sanguine sur papier',
'dimensions' => '25cm x 35cm',
'creation_year' => 1510,
'price' => 8000000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(45),
'updated_at' => Carbon::now()->subDays(25),
],
// Galerie de Picasso (id: 5)
[
'gallery_id' => 5,
'creator_id' => 5,
'title' => 'Femme Assise - Période Bleue',
'description' => 'Une œuvre de ma période bleue, empreinte de mélancolie mais d\'une beauté saisissante. Le bleu exprime toute ma tristesse de l\'époque.',
'image_url' => 'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=800&h=600',
'medium' => 'Huile sur toile',
'dimensions' => '100cm x 80cm',
'creation_year' => 1903,
'price' => 6200000.00,
'is_for_sale' => true,
'created_at' => Carbon::now()->subDays(18),
'updated_at' => Carbon::now()->subDays(8),
],
// Galerie collaborative de Maya (id: 6)
[
'gallery_id' => 6,
'creator_id' => 1, // Monet contribue
'title' => 'Hommage aux Maîtres - Variation Moderne',
'description' => 'Une interprétation contemporaine de mes techniques impressionnistes, créée spécialement pour cette exposition collaborative.',
'image_url' => 'https://images.unsplash.com/photo-1541961017774-22349e4a1262?w=800&h=600',
'medium' => 'Acrylique sur toile',
'dimensions' => '120cm x 90cm',
'creation_year' => 2024,
'price' => 45000.00,
'is_for_sale' => true,
'created_at' => Carbon::now()->subDays(12),
'updated_at' => Carbon::now()->subDays(3),
],
[
'gallery_id' => 6,
'creator_id' => 5, // Picasso contribue
'title' => 'Cubisme Digital',
'description' => 'Si j\'avais eu accès aux outils numériques, voici comment j\'aurais exploré le cubisme. Une œuvre qui mélange tradition et innovation.',
'image_url' => 'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=800&h=600',
'medium' => 'Art numérique imprimé sur toile',
'dimensions' => '80cm x 80cm',
'creation_year' => 2024,
'price' => 25000.00,
'is_for_sale' => true,
'created_at' => Carbon::now()->subDays(10),
'updated_at' => Carbon::now()->subDays(2),
],
// Galerie privée de Monet (id: 7)
[
'gallery_id' => 7,
'creator_id' => 1,
'title' => 'Impression, Soleil Levant - Étude Préparatoire N°1',
'description' => 'La toute première esquisse de ce qui deviendrait l\'œuvre fondatrice de l\'impressionnisme. Un moment historique capturé.',
'image_url' => 'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=800&h=600',
'medium' => 'Huile sur carton',
'dimensions' => '30cm x 40cm',
'creation_year' => 1872,
'price' => 12000000.00,
'is_for_sale' => false,
'created_at' => Carbon::now()->subDays(50),
'updated_at' => Carbon::now()->subDays(40),
],
];
DB::table('artworks')->insert($artworks);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
\DB::statement('PRAGMA foreign_keys = OFF;');
// Supprimer les données existantes dans l'ordre inverse des dépendances
\DB::table('gallery_members')->delete();
\DB::table('artworks')->delete();
\DB::table('galleries')->delete();
\DB::table('users')->delete();
// Réactiver les contraintes
\DB::statement('PRAGMA foreign_keys = ON;');
// Lancer nos seeders personnalisés
$this->call([
UserSeeder::class,
GallerySeeder::class,
ArtworkSeeder::class,
GalleryMemberSeeder::class,
]);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class GalleryMemberSeeder extends Seeder
{
public function run()
{
$memberships = [
// Maya (collectionneuse) invitée à voir plusieurs galeries privées
[
'gallery_id' => 3, // Galerie privée de Van Gogh
'user_id' => 6, // Maya
'role' => 'viewer',
'status' => 'accepted',
'invited_at' => Carbon::now()->subDays(15),
'updated_at' => Carbon::now()->subDays(12),
],
[
'gallery_id' => 7, // Galerie privée de Monet
'user_id' => 6, // Maya
'role' => 'viewer',
'status' => 'accepted',
'invited_at' => Carbon::now()->subDays(20),
'updated_at' => Carbon::now()->subDays(18),
],
// Collaborations entre artistes
[
'gallery_id' => 6, // Galerie collaborative de Maya
'user_id' => 1, // Monet invité comme contributeur
'role' => 'editor',
'status' => 'accepted',
'invited_at' => Carbon::now()->subDays(10),
'updated_at' => Carbon::now()->subDays(8),
],
[
'gallery_id' => 6, // Galerie collaborative de Maya
'user_id' => 5, // Picasso invité comme contributeur
'role' => 'editor',
'status' => 'accepted',
'invited_at' => Carbon::now()->subDays(9),
'updated_at' => Carbon::now()->subDays(7),
],
[
'gallery_id' => 6, // Galerie collaborative de Maya
'user_id' => 2, // Frida invitée mais n'a pas encore répondu
'role' => 'editor',
'status' => 'pending',
'invited_at' => Carbon::now()->subDays(5),
'updated_at' => Carbon::now()->subDays(5),
],
// Leonardo donne accès à Van Gogh à sa galerie pour inspiration
[
'gallery_id' => 4, // Galerie de Leonardo
'user_id' => 3, // Van Gogh
'role' => 'viewer',
'status' => 'accepted',
'invited_at' => Carbon::now()->subDays(25),
'updated_at' => Carbon::now()->subDays(22),
],
// Picasso refuse l'accès à sa galerie à un utilisateur
[
'gallery_id' => 5, // Galerie de Picasso
'user_id' => 4, // Leonardo
'role' => 'viewer',
'status' => 'rejected',
'invited_at' => Carbon::now()->subDays(8),
'updated_at' => Carbon::now()->subDays(6),
],
// Invitations en attente
[
'gallery_id' => 1, // Galerie de Monet
'user_id' => 2, // Frida
'role' => 'viewer',
'status' => 'pending',
'invited_at' => Carbon::now()->subDays(3),
'updated_at' => Carbon::now()->subDays(3),
],
[
'gallery_id' => 2, // Galerie de Frida
'user_id' => 3, // Van Gogh
'role' => 'viewer',
'status' => 'pending',
'invited_at' => Carbon::now()->subDays(2),
'updated_at' => Carbon::now()->subDays(2),
],
];
DB::table('gallery_members')->insert($memberships);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class GallerySeeder extends Seeder
{
public function run()
{
$galleries = [
[
'owner_id' => 1, // Claude Monet
'title' => 'Les Nymphéas - Collection Privée',
'description' => 'Une collection exclusive de mes œuvres inspirées par mon jardin de Giverny. Ces toiles capturent la beauté changeante des nénuphars selon les saisons et les heures du jour.',
'is_public' => true,
'publication_date' => Carbon::now()->subDays(30),
'created_at' => Carbon::now()->subDays(35),
'updated_at' => Carbon::now()->subDays(20),
],
[
'owner_id' => 2, // Frida Kahlo
'title' => 'Autoportraits et Douleur',
'description' => 'Une exposition intime de mes autoportraits les plus personnels, explorant les thèmes de la souffrance, de l\'amour et de l\'identité mexicaine.',
'is_public' => true,
'publication_date' => Carbon::now()->subDays(25),
'created_at' => Carbon::now()->subDays(30),
'updated_at' => Carbon::now()->subDays(15),
],
[
'owner_id' => 3, // Van Gogh
'title' => 'Nuit Étoilée - Série Complète',
'description' => 'Ma fascination pour les ciels nocturnes et les étoiles. Cette galerie présente l\'évolution de mon style à travers différentes représentations de la nuit.',
'is_public' => false,
'publication_date' => null,
'created_at' => Carbon::now()->subDays(20),
'updated_at' => Carbon::now()->subDays(10),
],
[
'owner_id' => 4, // Leonardo
'title' => 'Renaissance et Innovation',
'description' => 'Mes œuvres qui allient art et science. Découvrez comment j\'ai révolutionné la peinture en étudiant l\'anatomie et la perspective.',
'is_public' => true,
'publication_date' => Carbon::now()->subDays(40),
'created_at' => Carbon::now()->subDays(45),
'updated_at' => Carbon::now()->subDays(25),
],
[
'owner_id' => 5, // Picasso
'title' => 'Période Bleue Revisitée',
'description' => 'Un retour sur ma période bleue avec des œuvres inédites et des variations sur mes thèmes favoris de cette époque mélancolique.',
'is_public' => true,
'publication_date' => Carbon::now()->subDays(15),
'created_at' => Carbon::now()->subDays(18),
'updated_at' => Carbon::now()->subDays(8),
],
[
'owner_id' => 6, // Maya
'title' => 'Curation Contemporaine',
'description' => 'Ma sélection personnelle d\'œuvres d\'artistes contemporains émergents. Une galerie collaborative pour promouvoir les nouveaux talents.',
'is_public' => true,
'publication_date' => Carbon::now()->subDays(10),
'created_at' => Carbon::now()->subDays(12),
'updated_at' => Carbon::now()->subDays(3),
],
[
'owner_id' => 1, // Claude Monet - 2ème galerie
'title' => 'Impression, Soleil Levant - Études',
'description' => 'Les études préparatoires et variations autour de mon œuvre la plus célèbre qui a donné son nom à l\'impressionnisme.',
'is_public' => false,
'publication_date' => null,
'created_at' => Carbon::now()->subDays(50),
'updated_at' => Carbon::now()->subDays(40),
],
];
DB::table('galleries')->insert($galleries);
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
class UserSeeder extends Seeder
{
public function run()
{
$users = [
[
'username' => 'claude_monet',
'email' => 'claude.monet@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Claude',
'last_name' => 'Monet',
'bio' => 'Peintre impressionniste français, passionné par les jeux de lumière et les paysages aquatiques. Créateur de la série des Nymphéas.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(120),
'updated_at' => Carbon::now()->subDays(120),
],
[
'username' => 'frida_kahlo',
'email' => 'frida.kahlo@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Frida',
'last_name' => 'Kahlo',
'bio' => 'Artiste peintre mexicaine, connue pour ses autoportraits et son style unique mêlant réalisme et surréalisme.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1494790108755-2616b9a7e4b3?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(90),
'updated_at' => Carbon::now()->subDays(45),
],
[
'username' => 'vincent_van_gogh',
'email' => 'vincent.vangogh@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Vincent',
'last_name' => 'Van Gogh',
'bio' => 'Peintre et dessinateur néerlandais post-impressionniste. Passionné par les couleurs vives et les coups de pinceau expressifs.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(75),
'updated_at' => Carbon::now()->subDays(30),
],
[
'username' => 'leonardo_da_vinci',
'email' => 'leo.davinci@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Leonardo',
'last_name' => 'Da Vinci',
'bio' => 'Artiste, inventeur et scientifique de la Renaissance. Maître de la peinture, de la sculpture et de l\'innovation.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(60),
'updated_at' => Carbon::now()->subDays(15),
],
[
'username' => 'pablo_picasso',
'email' => 'pablo.picasso@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Pablo',
'last_name' => 'Picasso',
'bio' => 'Peintre, sculpteur et céramiste espagnol. Co-fondateur du mouvement cubiste et l\'un des artistes les plus influents du XXe siècle.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1463453091185-61582044d556?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(45),
'updated_at' => Carbon::now()->subDays(10),
],
[
'username' => 'maya_art_collector',
'email' => 'maya.collector@art.com',
'password_hash' => Hash::make('password123'),
'first_name' => 'Maya',
'last_name' => 'Rodriguez',
'bio' => 'Collectionneuse d\'art contemporain et curatrice indépendante. Passionnée par la découverte de nouveaux talents.',
'profile_picture_url' => 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=300&h=300&fit=crop&crop=face',
'created_at' => Carbon::now()->subDays(30),
'updated_at' => Carbon::now()->subDays(5),
],
];
DB::table('users')->insert($users);
}
}

33
laravel/nginx.conf Normal file
View File

@ -0,0 +1,33 @@
worker_processes 1;
events { worker_connections 1024; }
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 5001;
root /var/www/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
}

2419
laravel/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

17
laravel/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.8.2",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^1.2.0",
"tailwindcss": "^4.0.0",
"vite": "^6.2.4"
}
}

33
laravel/phpunit.xml Normal file
View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>

25
laravel/public/.htaccess Normal file
View File

@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

View File

20
laravel/public/index.php Normal file
View File

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

View File

@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

View File

@ -0,0 +1 @@
import './bootstrap';

4
laravel/resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

File diff suppressed because one or more lines are too long

18
laravel/routes/api.php Normal file
View File

@ -0,0 +1,18 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\V1\GalleryController;
use App\Http\Controllers\Api\V1\ArtistController;
// On peut préfixer et grouper par version
Route::prefix('public')->group(function () {
// Route pour obtenir les galeries publiques
Route::get('/galleries', [GalleryController::class, 'index']);
// Route pour obtenir les oeuvres d'une galerie publique spécifique
Route::get('/galleries/{gallery}/artworks', [GalleryController::class, 'showArtworks']);
// Route pour obtenir la liste des artistes
Route::get('/artists', [ArtistController::class, 'index']);
});

View File

@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

7
laravel/routes/web.php Normal file
View File

@ -0,0 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

4
laravel/storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
laravel/storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

9
laravel/storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
laravel/storage/logs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

13
laravel/supervisord.conf Normal file
View File

@ -0,0 +1,13 @@
[supervisord]
nodaemon=true
[supervisorctl]
serverurl=unix:///var/run/supervisor.sock
[program:php-fpm]
command=/usr/local/sbin/php-fpm
[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"

View File

@ -0,0 +1,19 @@
<?php
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

View File

@ -0,0 +1,16 @@
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}

13
laravel/vite.config.js Normal file
View File

@ -0,0 +1,13 @@
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
tailwindcss(),
],
});

View File

@ -3,7 +3,7 @@ FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask flask_sqlalchemy pyjwt requests pymysql cryptography redis
RUN pip install flask flask_sqlalchemy pyjwt requests pymysql cryptography redis python-jose
CMD ["python", "app.py"]

View File

@ -1,11 +1,13 @@
from flask import Flask, jsonify, request, abort
from flask import Flask, request, jsonify, g, abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from jose import jwt, JWTError
import requests
import jwt
import time
import pymysql
import redis
import json
from functools import wraps
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://myuser:mypassword@mysql:3306/mydb'
@ -13,6 +15,7 @@ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
MYSQL_HOST = "mysql"
MYSQL_PORT = 3306
MYSQL_USER = "myuser"
@ -38,81 +41,821 @@ while True:
print("Waiting for MySQL...", e)
time.sleep(2)
class Visite(db.Model):
print('Creating DB')
# Keycloak config
KEYCLOAK_REALM = "master"
KEYCLOAK_URL = "http://keycloak:8080"
CLIENT_ID = "soa"
ISSUER = f"{KEYCLOAK_URL}/realms/{KEYCLOAK_REALM}"
JWKS_URL = f"{ISSUER}/protocol/openid-connect/certs"
for _ in range(30):
try:
r = requests.get("http://keycloak:8080/realms/master/.well-known/openid-configuration")
if r.status_code == 200:
break
except Exception:
pass
time.sleep(2)
else:
raise Exception("Keycloak is not available after waiting")
jwks = requests.get(JWKS_URL).json()["keys"]
def get_signing_key(token):
unverified_header = jwt.get_unverified_header(token)
kid = unverified_header.get("kid")
for key in jwks:
if key["kid"] == kid:
return key
raise Exception("Public key not found.")
# Decorator for OIDC protection
def oidc_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
# Get user info from Apache headers
user_email = request.headers.get("OIDC_email")
username = request.headers.get("OIDC_user") or user_email
if not user_email or not username:
return jsonify({"error": "Not authenticated"}), 401
# Find or create user in DB
user = User.query.filter_by(email=user_email).first()
if not user:
user = User(
username=username,
email=user_email,
alias=username,
)
db.session.add(user)
db.session.commit()
event = {
"type": "user_created",
"data": {"id": user.id, "alias": user.alias}
}
redis_client.publish('events', json.dumps(event))
g.db_user = user
return f(*args, **kwargs)
return wrapper
@app.route("/api/private/debug-headers")
def debug_headers():
return jsonify(dict(request.headers))
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
galerie_id = db.Column(db.Integer, nullable=False)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(255), unique=True, nullable=False)
alias = db.Column(db.String(255), nullable=False)
first_name = db.Column(db.String(100))
last_name = db.Column(db.String(100))
bio = db.Column(db.Text)
profile_picture_url = db.Column(db.String(255))
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
class Critique(db.Model):
class Gallery(db.Model):
__tablename__ = "galleries"
id = db.Column(db.Integer, primary_key=True)
oeuvre_id = db.Column(db.Integer, nullable=False)
texte = db.Column(db.Text, nullable=False)
username = db.Column(db.String(100), nullable=False)
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
title = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
is_public = db.Column(db.Boolean, default=False)
publication_date = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
class Artwork(db.Model):
__tablename__ = "artworks"
id = db.Column(db.Integer, primary_key=True)
gallery_id = db.Column(db.Integer, db.ForeignKey('galleries.id'), nullable=False)
creator_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
title = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
image_url = db.Column(db.String(255), nullable=False)
medium = db.Column(db.String(100))
dimensions = db.Column(db.String(50))
creation_year = db.Column(db.Integer)
price = db.Column(db.Numeric(10, 2))
is_visible = db.Column(db.Boolean, default=True)
is_for_sale = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
@app.route("/", methods=["GET"])
def index():
return f"User API - Authenticated as {request.user}", 200
class GalleryMember(db.Model):
__tablename__ = "gallery_members"
gallery_id = db.Column(db.Integer, db.ForeignKey('galleries.id'), primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
role = db.Column(db.String(50), nullable=False, default='viewer')
status = db.Column(db.String(50), nullable=False, default='pending')
invited_at = db.Column(db.DateTime, server_default=db.func.now())
entered_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
@app.route("/galerie/<int:galerie_id>/entrer", methods=["POST"])
def entrer_galerie(galerie_id):
visite = Visite(galerie_id=galerie_id)
db.session.add(visite)
class ArtworkReview(db.Model):
__tablename__ = "artwork_reviews"
id = db.Column(db.Integer, primary_key=True)
artwork_id = db.Column(db.Integer, db.ForeignKey('artworks.id'), nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
grade = db.Column(db.Integer)
description = db.Column(db.Text)
parent_ar_id = db.Column(db.Integer, db.ForeignKey('artwork_reviews.id'))
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
__table_args__ = (db.CheckConstraint('grade >= 0 AND grade <= 5', name='check_grade_range_artwork'),)
class GalleryReview(db.Model):
__tablename__ = "gallery_reviews"
id = db.Column(db.Integer, primary_key=True)
gallery_id = db.Column(db.Integer, db.ForeignKey('galleries.id'), nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
grade = db.Column(db.Integer)
description = db.Column(db.Text)
parent_gr_id = db.Column(db.Integer, db.ForeignKey('gallery_reviews.id'))
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
__table_args__ = (db.CheckConstraint('grade >= 0 AND grade <= 5', name='check_grade_range_gallery'),)
with app.app_context():
db.create_all() # Ensure all tables are created if they do not exist
@app.route("/api/private/redirect")
def oidc_redirect():
code = request.args.get("code")
if not code:
return "Missing code", 400
# Exchange code for tokens
token_url = "https://auth.local/realms/master/protocol/openid-connect/token"
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "https://api.local/api/private/redirect",
"client_id": "soa",
"client_secret": "mysecret"
}
resp = requests.post(token_url, data=data)
if resp.status_code != 200:
return "Token exchange failed", 400
tokens = resp.json()
# Store tokens in session, or set as cookie, or return to frontend
# Example: set as cookie (not for production, just for demo)
response = redirect("/") # or wherever you want
response.set_cookie("access_token", tokens["access_token"], httponly=True, secure=True)
return response
# User profile
# Retrieve the authenticated user's profile information.
@app.route("/api/private/me", methods=["GET"])
@oidc_required
def get_me():
user = g.db_user
return jsonify({
"id": user.id,
"username": user.username,
"email": user.email,
"alias": user.alias,
"first_name": user.first_name,
"last_name": user.last_name,
"bio": user.bio,
"profile_picture_url": user.profile_picture_url,
"created_at": user.created_at,
"updated_at": user.updated_at
})
# Update the authenticated user's editable profile fields (alias, first name, last name, bio, profile picture).
@app.route("/api/private/me", methods=["PUT"])
@oidc_required
def update_me():
data = request.json
user = g.db_user
user.alias = data.get("alias", user.alias)
user.first_name = data.get("first_name", user.first_name)
user.last_name = data.get("last_name", user.last_name)
user.bio = data.get("bio", user.bio)
user.profile_picture_url = data.get("profile_picture_url", user.profile_picture_url)
db.session.commit()
return jsonify({"message": "Entré dans la galerie"}), 201
@app.route("/galerie/<int:galerie_id>/sortir", methods=["POST"])
def sortir_galerie(galerie_id):
Visite.query.filter_by(galerie_id=galerie_id).delete()
db.session.commit()
return jsonify({"message": "Sorti de la galerie"}), 200
@app.route("/oeuvres", methods=["POST"])
def create_oeuvre():
data = flask.request.get_json()
titre = data.get("titre")
if not titre:
return {"error": "Titre requis"}, 400
oeuvre = Oeuvre(titre=titre, exposee=True)
db.session.add(oeuvre)
db.session.commit()
# Publier l'événement
event = {
"type": "oeuvre_created",
"data": {"id": oeuvre.id, "titre": oeuvre.titre}
"type": "user_updated",
"data": {"id": user.id, "alias": user.alias}
}
redis_client.publish('events', json.dumps(event))
return {"id": oeuvre.id, "titre": oeuvre.titre}, 201
return jsonify({"message": "Profile updated"})
@app.route("/oeuvre/<int:oeuvre_id>/critiquer", methods=["POST"])
def critiquer_oeuvre(oeuvre_id):
data = request.get_json()
if not data or not data.get("texte"):
# Invitations
# Send an invitation to another user to join the specified gallery.
@app.route("/api/private/gallery/<int:gallery_id>/invite", methods=["POST"])
@oidc_required
def invite_user(gallery_id):
data = request.json
invited_user_id = data.get("user_id")
role = data.get("role", "viewer")
gallery = Gallery.query.get_or_404(gallery_id)
if gallery.owner_id != g.db_user.id:
abort(403)
user = User.query.get(invited_user_id)
if not user:
abort(404)
invitation = GalleryMember(
gallery_id=gallery_id,
user_id=invited_user_id,
role=role,
status="pending"
)
try:
db.session.add(invitation)
db.session.commit()
event = {
"type": "invitation_sent",
"data": {"user_id": invitation.user_id, "gallery_id": invitation.gallery_id}
}
redis_client.publish('events', json.dumps(event))
except IntegrityError:
db.session.rollback()
return jsonify({"error": "Invitation already exists"}), 409
return jsonify({"message": "Invitation sent"}), 201
# Allow an invited user to accept or reject a gallery invitation.
@app.route("/api/private/invitations/<int:gallery_id>/respond", methods=["PUT"])
@oidc_required
def respond_invitation(gallery_id):
data = request.json
status = data.get("status")
if status not in ["accepted", "rejected"]:
abort(400)
critique = Critique(oeuvre_id=oeuvre_id, texte=data["texte"], username=request.user)
db.session.add(critique)
invitation = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id).first_or_404()
if invitation.status != "pending":
abort(403)
invitation.status = status
if status == "accepted":
invitation.entered_at = db.func.now()
db.session.commit()
return jsonify({"message": "Critique ajoutée"}), 201
# ROUTE CREATION GALERIE
@app.route("/galeries", methods=["POST"])
def create_galerie():
data = request.get_json()
nom = data.get("nom")
if not nom:
return {"error": "Nom requis"}, 400
galerie = Galerie(nom=nom, auteur=request.user)
db.session.add(galerie)
db.session.commit()
# Publier l'événement
event = {
"type": "galerie_created",
"data": {"id": galerie.id, "nom": galerie.nom, "auteur": galerie.auteur}
"type": "invitation_answered",
"data": {"user_id": invitation.user_id, "gallery_id": invitation.gallery_id, "answer": invitation.status}
}
redis_client.publish('events', json.dumps(event))
return {"id": galerie.id, "nom": galerie.nom, "auteur": galerie.auteur}, 201
return jsonify({"message": f"Invitation {status}"})
# List all invitations received by the authenticated user (with status).
@app.route("/api/private/invitations/received", methods=["GET"])
@oidc_required
def get_received_invitations():
invitations = GalleryMember.query.filter_by(user_id=g.db_user.id).all()
result = []
for inv in invitations:
gal = Gallery.query.get(inv.gallery_id)
own = User.query.get(gal.owner_id)
result.append({
"gallery_id": inv.gallery_id,
"gallery_title": gal.title,
"gallery_description": gal.description,
"owner": own.alias,
"role": inv.role,
"status": inv.status,
"invited_at": inv.invited_at,
"entered_at": inv.entered_at,
"updated_at": inv.updated_at
})
return jsonify(result)
# Galleries
# List all galleries accessible to the user (public, owned, or where they are a member).
@app.route("/api/private/galleries", methods=["GET"])
@oidc_required
def get_galleries():
user_id = g.db_user.id
public = Gallery.query.filter_by(is_public=True)
owned = Gallery.query.filter_by(owner_id=user_id)
member = Gallery.query.join(GalleryMember, Gallery.id==GalleryMember.gallery_id).filter(GalleryMember.user_id==user_id, GalleryMember.status=="accepted")
galleries = public.union(owned).union(member).all()
result = []
for gal in galleries:
own = User.query.get(gal.owner_id)
result.append({
"id": gal.id,
"title": gal.title,
"description": gal.description,
"owner": own.alias,
"is_public": gal.is_public,
"publication_date": gal.publication_date,
})
return jsonify(result)
# Show details of a single gallery (enforcing public or member access).
@app.route("/api/private/gallery/<int:gallery_id>", methods=["GET"])
@oidc_required
def get_gallery(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
own = User.query.get(gal.owner_id)
return jsonify({
"id": gal.id,
"title": gal.title,
"description": gal.description,
"owner": own.alias,
"is_public": gal.is_public,
"publication_date": gal.publication_date,
"created_at": gal.created_at,
"updated_at": gal.updated_at
})
# Create a new gallery for the authenticated user.
@app.route("/api/private/gallery", methods=["POST"])
@oidc_required
def create_gallery():
data = request.json
gallery = Gallery(
owner_id=g.db_user.id,
title=data.get("title"),
description=data.get("description"),
is_public=data.get("is_public", False),
publication_date=data.get("publication_date")
)
db.session.add(gallery)
db.session.commit()
event = {
"type": "gallery_created",
"data": {"user_id": gallery.owner_id, "gallery_id": gallery.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"id": gallery.id, "message": "Gallery created"}), 201
# Update a gallery's title, description, public flag, and publication date (owner only).
@app.route("/api/private/gallery/<int:gallery_id>", methods=["PUT"])
@oidc_required
def update_gallery(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if gal.owner_id != g.db_user.id:
abort(403)
data = request.json
gal.title = data.get("title", gal.title)
gal.description = data.get("description", gal.description)
gal.is_public = data.get("is_public", gal.is_public)
gal.publication_date = data.get("publication_date", gal.publication_date)
db.session.commit()
event = {
"type": "gallery_updated",
"data": {"user_id": gal.owner_id, "gallery_id": gal.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"message": "Gallery updated"})
# Retrieve the list of galleries owned by the authenticated user.
@app.route("/api/private/galleries/mine", methods=["GET"])
@oidc_required
def get_my_galleries():
user_id = g.db_user.id
galleries = Gallery.query.filter_by(owner_id=user_id).all()
result = []
for gal in galleries:
result.append({
"id": gal.id,
"title": gal.title,
"description": gal.description,
"is_public": gal.is_public,
"publication_date": gal.publication_date,
"created_at": gal.created_at,
"updated_at": gal.updated_at
})
return jsonify(result)
# List all members of a gallery (including the owner), with roles and join dates.
@app.route("/api/private/gallery/<int:gallery_id>/members", methods=["GET"])
@oidc_required
def get_gallery_members(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
members = GalleryMember.query.filter_by(gallery_id=gallery_id, status="accepted").all()
result = []
owner = User.query.get(gal.owner_id)
result.append({
"user_id": owner.id,
"alias": owner.alias,
"bio": owner.bio,
"profile_picture_url": owner.profile_picture_url,
"role": "owner",
"entered_at": gal.created_at
})
for mem in members:
user = User.query.get(mem.user_id)
result.append({
"user_id": user.id,
"alias": user.alias,
"bio": user.bio,
"profile_picture_url": user.profile_picture_url,
"role": mem.role,
"entered_at": mem.entered_at
})
return jsonify(result)
# Artworks
# List artworks in a gallery, filtering by visibility and access.
@app.route("/api/private/gallery/<int:gallery_id>/artworks", methods=["GET"])
@oidc_required
def get_gallery_artworks(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
if gal.owner_id != g.db_user.id:
artworks = Artwork.query.filter_by(gallery_id=gallery_id, is_visible=True).all()
else:
artworks = Artwork.query.filter_by(gallery_id=gallery_id).all()
result = []
for art in artworks:
cre = User.query.get(art.creator_id)
result.append({
"id": art.id,
"title": art.title,
"description": art.description,
"creator": cre.alias,
"image_url": art.image_url,
"medium": art.medium,
"dimensions": art.dimensions,
"creation_year": art.creation_year,
"is_visible": art.is_visible,
"price": art.price,
"is_for_sale": art.is_for_sale
})
return jsonify(result)
# Retrieve detailed information about a single artwork (visibility & access checks).
@app.route("/api/private/artwork/<int:artwork_id>", methods=["GET"])
@oidc_required
def get_artwork(artwork_id):
art = Artwork.query.get_or_404(artwork_id)
gal = Gallery.query.get(art.gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=art.gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
if art.creator_id != g.db_user.id and not art.is_visible:
abort(404)
cre = User.query.get(art.creator_id)
return jsonify({
"id": art.id,
"gallery_id": art.gallery_id,
"creator": cre.alias,
"title": art.title,
"description": art.description,
"image_url": art.image_url,
"medium": art.medium,
"dimensions": art.dimensions,
"creation_year": art.creation_year,
"is_visible": art.is_visible,
"price": art.price,
"is_for_sale": art.is_for_sale,
"created_at": art.created_at,
"updated_at": art.updated_at
})
# Add a new artwork to the specified gallery (owner only).
@app.route("/api/private/gallery/<int:gallery_id>/artwork", methods=["POST"])
@oidc_required
def create_artwork(gallery_id):
gallery = Gallery.query.get_or_404(gallery_id)
if gallery.owner_id != g.db_user.id:
abort(403)
data = request.json
artwork = Artwork(
gallery_id=gallery_id,
creator_id=g.db_user.id,
title=data.get("title"),
description=data.get("description"),
image_url=data.get("image_url"),
medium=data.get("medium"),
dimensions=data.get("dimensions"),
creation_year=data.get("creation_year"),
price=data.get("price"),
is_visible=data.get("is_visible", True),
is_for_sale=data.get("is_for_sale", False)
)
db.session.add(artwork)
db.session.commit()
event = {
"type": "artwork_created",
"data": {"user_id": artwork.creator_id, "artwork_id": artwork.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"id": artwork.id, "message": "Artwork created"}), 201
# Update an existing artwork's details (creator only).
@app.route("/api/private/artwork/<int:artwork_id>", methods=["PUT"])
@oidc_required
def update_artwork(artwork_id):
art = Artwork.query.get_or_404(artwork_id)
if art.creator_id != g.db_user.id:
abort(403)
data = request.json
art.title = data.get("title", art.title)
art.description = data.get("description", art.description)
art.image_url = data.get("image_url", art.image_url)
art.medium = data.get("medium", art.medium)
art.dimensions = data.get("dimensions", art.dimensions)
art.creation_year = data.get("creation_year", art.creation_year)
art.price = data.get("price", art.price)
art.is_visible = data.get("is_visible", art.is_visible)
art.is_for_sale = data.get("is_for_sale", art.is_for_sale)
db.session.commit()
event = {
"type": "artwork_updated",
"data": {"user_id": art.creator_id, "artwork_id": art.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"message": "Artwork updated"})
# List all artworks created by the authenticated user.
@app.route("/api/private/artworks/mine", methods=["GET"])
@oidc_required
def get_my_artworks():
artworks = Artwork.query.filter_by(creator_id=g.db_user.id).all()
result = []
for art in artworks:
result.append({
"id": art.id,
"gallery_id": art.gallery_id,
"title": art.title,
"description": art.description,
"image_url": art.image_url,
"medium": art.medium,
"dimensions": art.dimensions,
"creation_year": art.creation_year,
"is_visible": art.is_visible,
"price": art.price,
"is_for_sale": art.is_for_sale,
"created_at": art.created_at,
"updated_at": art.updated_at
})
return jsonify(result)
# Gallery reviews
# List all reviews for a given gallery (with access checks).
@app.route("/api/private/gallery/<int:gallery_id>/reviews", methods=["GET"])
@oidc_required
def get_gallery_reviews(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
reviews = GalleryReview.query.filter_by(gallery_id=gal.id).all()
result = []
for rev in reviews:
aut = User.query.get(rev.author_id)
result.append({
"id": rev.id,
"author": aut.alias,
"grade": rev.grade,
"description": rev.description,
"parent_gr_id": rev.parent_gr_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
# Submit a new review for the specified gallery (access enforced).
@app.route("/api/private/gallery/<int:gallery_id>/review", methods=["POST"])
@oidc_required
def create_gallery_review(gallery_id):
gal = Gallery.query.get_or_404(gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
data = request.json
review = GalleryReview(
gallery_id=gal.id,
author_id=g.db_user.id,
grade=data.get("grade"),
description=data.get("description"),
parent_gr_id=data.get("parent_gr_id")
)
db.session.add(review)
db.session.commit()
event = {
"type": "gallery_review_created",
"data": {"user_id": review.author_id, "gallery_id": review.gallery_id, "gallery_review_id": review.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"id": review.id, "message": "Review created"}), 201
# Edit an existing gallery review (author only).
@app.route("/api/private/galleries/review/<int:review_id>", methods=["PUT"])
@oidc_required
def update_gallery_review(review_id):
rev = GalleryReview.query.get_or_404(review_id)
if rev.author_id != g.db_user.id:
abort(403)
gal = Gallery.query.get_or_404(rev.gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=rev.gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
data = request.json
rev.grade = data.get("grade", rev.grade)
rev.description = data.get("description", rev.description)
db.session.commit()
event = {
"type": "gallery_review_updated",
"data": {"user_id": rev.author_id, "gallery_id": rev.gallery_id, "gallery_review_id": rev.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"message": "Review updated"})
# Retrieve all gallery reviews written by the authenticated user.
@app.route("/api/private/galleries/reviews/given", methods=["GET"])
@oidc_required
def get_given_gallery_reviews():
reviews = GalleryReview.query.filter_by(author_id=g.db_user.id).all()
result = []
for rev in reviews:
gal = Gallery.query.get(rev.gallery_id)
result.append({
"review_id": rev.id,
"gallery_id": gal.id,
"gallery_title": gal.title,
"grade": rev.grade,
"description": rev.description,
"parent_gr_id": rev.parent_gr_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
# List all reviews received on galleries owned by the authenticated user.
@app.route("/api/private/galleries/reviews/received", methods=["GET"])
@oidc_required
def get_received_gallery_reviews():
galleries = Gallery.query.filter_by(owner_id=g.db_user.id).all()
result = []
for gal in galleries:
reviews = GalleryReview.query.filter_by(gallery_id=gal.id).all()
for rev in reviews:
author = User.query.get(rev.author_id)
result.append({
"review_id": rev.id,
"gallery_id": gal.id,
"gallery_title": gal.title,
"author": author.alias,
"grade": rev.grade,
"description": rev.description,
"parent_gr_id": rev.parent_gr_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
# Artwork reviews
# List all reviews for a given artwork (with access checks).
@app.route("/api/private/artwork/<int:artwork_id>/reviews", methods=["GET"])
@oidc_required
def get_artwork_reviews(artwork_id):
art = Artwork.query.get_or_404(artwork_id)
gal = Gallery.query.get(art.gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=art.gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
if art.creator_id != g.db_user.id and not art.is_visible:
abort(404)
reviews = ArtworkReview.query.filter_by(artwork_id=art.id).all()
result = []
for rev in reviews:
aut = User.query.get(rev.author_id)
result.append({
"id": rev.id,
"author": aut.alias,
"grade": rev.grade,
"description": rev.description,
"parent_ar_id": rev.parent_ar_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
# Submit a new review for the specified artwork (access to gallery enforced).
@app.route("/api/private/artwork/<int:artwork_id>/review", methods=["POST"])
@oidc_required
def create_artwork_review(artwork_id):
art = Artwork.query.get_or_404(artwork_id)
gal = Gallery.query.get(art.gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=art.gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
if art.creator_id != g.db_user.id and not art.is_visible:
abort(404)
data = request.json
review = ArtworkReview(
artwork_id=art.id,
author_id=g.db_user.id,
grade=data.get("grade"),
description=data.get("description"),
parent_ar_id=data.get("parent_ar_id")
)
db.session.add(review)
db.session.commit()
event = {
"type": "artwork_review_created",
"data": {"user_id": review.author_id, "artwork_id": review.artwork_id_id, "artwork_review_id": review.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"id": review.id, "message": "Review created"}), 201
# Edit an existing artwork review (author only).
@app.route("/api/private/artworks/review/<int:review_id>", methods=["PUT"])
@oidc_required
def update_artwork_review(review_id):
rev = ArtworkReview.query.get_or_404(review_id)
if rev.author_id != g.db_user.id:
abort(403)
art = Artwork.query.get_or_404(rev.artwork_id)
gal = Gallery.query.get(art.gallery_id)
if not gal.is_public:
member = GalleryMember.query.filter_by(gallery_id=art.gallery_id, user_id=g.db_user.id, status="accepted").first()
if gal.owner_id != g.db_user.id and not member:
abort(403)
if art.creator_id != g.db_user.id and not art.is_visible:
abort(404)
data = request.json
rev.grade = data.get("grade", rev.grade)
rev.description = data.get("description", rev.description)
db.session.commit()
event = {
"type": "artwork_review_updated",
"data": {"user_id": rev.author_id, "artwork_id": rev.artwork_id_id, "artwork_review_id": rev.id}
}
redis_client.publish('events', json.dumps(event))
return jsonify({"message": "Review updated"})
# Retrieve all artwork reviews written by the authenticated user.
@app.route("/api/private/artworks/reviews/given", methods=["GET"])
@oidc_required
def get_given_artwork_reviews():
reviews = ArtworkReview.query.filter_by(author_id=g.db_user.id).all()
result = []
for rev in reviews:
art = Artwork.query.get(rev.artwork_id)
result.append({
"review_id": rev.id,
"artwork_id": art.id,
"artwork_title": art.title,
"grade": rev.grade,
"description": rev.description,
"parent_ar_id": rev.parent_ar_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
# List all reviews received on artworks owned by the authenticated user.
@app.route("/api/private/artworks/reviews/received", methods=["GET"])
@oidc_required
def get_received_artwork_reviews():
artworks = Artwork.query.filter_by(creator_id=g.db_user.id).all()
result = []
for art in artworks:
reviews = ArtworkReview.query.filter_by(artwork_id=art.id).all()
for rev in reviews:
author = User.query.get(rev.author_id)
result.append({
"review_id": rev.id,
"artwork_id": art.id,
"artwork_title": art.title,
"author": author.alias,
"grade": rev.grade,
"description": rev.description,
"parent_ar_id": rev.parent_ar_id,
"created_at": rev.created_at,
"updated_at": rev.updated_at
})
return jsonify(result)
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(host='0.0.0.0',port=5002, debug=True)

View File

@ -1,76 +0,0 @@
import time
import pymysql
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
import redis
import json
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://myuser:mypassword@mysql:3306/mydb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
MYSQL_HOST = "mysql"
MYSQL_PORT = 3306
MYSQL_USER = "myuser"
MYSQL_PASSWORD = "mypassword"
MYSQL_DB = "mydb"
# Connexion Redis
redis_client = redis.Redis(host='redis', port=6379, decode_responses=True)
while True:
try:
conn = pymysql.connect(
host=MYSQL_HOST,
port=MYSQL_PORT,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
database=MYSQL_DB
)
conn.close()
print("MySQL is up - continuing.")
break
except pymysql.err.OperationalError as e:
print("Waiting for MySQL...", e)
time.sleep(2)
class Artiste(db.Model):
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String(100), nullable=False)
class Galerie(db.Model):
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String(100), nullable=False)
class Oeuvre(db.Model):
id = db.Column(db.Integer, primary_key=True)
titre = db.Column(db.String(200), nullable=False)
exposee = db.Column(db.Boolean, default=False)
@app.route("/", methods=["GET"])
def index():
return "Public API", 200
@app.route("/artistes", methods=["GET"])
def get_artistes():
artistes = Artiste.query.all()
return jsonify([{"id": a.id, "nom": a.nom} for a in artistes]), 200
@app.route("/galeries", methods=["GET"])
def get_galeries():
galeries = Galerie.query.all()
return jsonify([{"id": g.id, "nom": g.nom} for g in galeries]), 200
@app.route("/oeuvres", methods=["GET"])
def get_oeuvres():
oeuvres = Oeuvre.query.filter_by(exposee=True).all()
return jsonify([{"id": o.id, "titre": o.titre} for o in oeuvres]), 200
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(host='0.0.0.0',port=5001, debug=True)