SurfBuddy Backend API 🏄♂️⚡ "L'API REST qui propulse votre compagnon de surf !" "The REST API that powers your surf buddy!"
🇫🇷 Version Française SurfBuddy Backend est une API REST développée avec PHP Symfony qui alimente l'application mobile SurfBuddy. Cette API permet de gérer les spots de surf du monde entier, l'authentification des utilisateurs et toutes les opérations CRUD nécessaires au bon fonctionnement de l'application mobile. Ce projet a été développé dans le cadre du cursus de développement mobile à Ada Tech School, en se concentrant sur la création d'APIs robustes et sécurisées.
Fonctionnalités 🌊 API REST complète : Endpoints pour la gestion des spots de surf 🔐 Authentification JWT : Système d'authentification sécurisé avec tokens JWT 👥 Gestion utilisateurs : Inscription, connexion et gestion des profils 📸 Upload d'images : Gestion des photos de spots et profils utilisateurs 🗺️ Géolocalisation : Support des coordonnées GPS pour les spots 🔍 Filtrage et pagination : Optimisation des requêtes avec filtres et pagination 📊 Base de données MySQL : Stockage persistant avec Doctrine ORM 🛡️ Sécurité CORS : Configuration CORS pour l'intégration mobile ⚡ Performance optimisée : Queries optimisées et mise en cache Pile technologique PHP 8.1+ Symfony 6.4+ Framework Doctrine ORM pour la gestion de base de données MySQL 8.0+ Base de données JWT Authentication pour la sécurité Nelmio CORS Bundle pour la configuration CORS API Platform (optionnel) pour l'auto-documentation Twig pour les templates (si nécessaire) Composer pour la gestion des dépendances Architecture API Endpoints principaux Authentification :
POST /api/auth/register - Inscription utilisateur POST /api/auth/login - Connexion utilisateur POST /api/auth/refresh - Rafraîchissement du token Spots de surf :
GET /api/spots - Liste des spots (avec pagination et filtres) GET /api/spots/{id} - Détails d'un spot spécifique POST /api/spots - Création d'un nouveau spot (authentifié) PUT /api/spots/{id} - Modification d'un spot (authentifié) DELETE /api/spots/{id} - Suppression d'un spot (authentifié) Utilisateurs :
GET /api/users/profile - Profil utilisateur (authentifié) PUT /api/users/profile - Modification du profil (authentifié) POST /api/users/avatar - Upload photo de profil (authentifié) Modèle de données Entité Spots php class Spots { private int $id; private string $spotName; private DifficultyEnum $difficulty; private string $country; private string $city; private float $latitude; private float $longitude; private \DateTime $seasonBegin; private \DateTime $seasonEnd; private ?string $spotPicture; private SpotTypeEnum $type; private Users $user; // Créateur du spot } Entité Users php class Users { private int $id; private string $alias; private string $email; private string $password; // Hashé private ?string $picture; private Collection $spots; // Spots créés par l'utilisateur } Enums DifficultyEnum : BEGINNER, INTERMEDIATE, ADVANCED, EXPERT SpotTypeEnum : BEACH_BREAK, REEF_BREAK, POINT_BREAK, RIVER_MOUTH Prérequis Avant d'installer ce projet, assurez-vous d'avoir :
PHP 8.1 ou supérieur Composer (gestionnaire de dépendances PHP) MySQL 8.0 ou supérieur Git Serveur web (Apache, Nginx, ou serveur de développement Symfony) Installation Cloner le dépôt bash git clone https://github.com/adatechschool/SurfBuddy_Back.git cd SurfBuddy_Back Installer les dépendances bash composer install Configuration de l'environnement Copiez le fichier .env et configurez vos variables d'environnement : bash cp .env .env.local Éditez .env.local avec vos paramètres : env
DATABASE_URL="mysql://username:[email protected]:3306/surfbuddy_db?charset=utf8mb4"
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem JWT_PASSPHRASE=your_jwt_passphrase
CORS_ALLOW_ORIGIN=^https?://(localhost|127.0.0.1)(:[0-9]+)?$
APP_ENV=dev APP_SECRET=your_app_secret_key Configuration de la base de données bash
php bin/console doctrine:database:create
php bin/console doctrine:migrations:migrate
php bin/console doctrine:fixtures:load Génération des clés JWT bash php bin/console lexik:jwt:generate-keypair Démarrer le serveur de développement bash
symfony server:start
php -S localhost:8000 -t public/ Configuration CORS Pour permettre l'accès depuis l'application mobile, configurez CORS dans config/packages/nelmio_cors.yaml :
yaml nelmio_cors: defaults: origin_regex: true allow_origin: ['%env(CORS_ALLOW_ORIGIN)%'] allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE'] allow_headers: ['Content-Type', 'Authorization'] expose_headers: ['Link'] max_age: 3600 paths: '^/api/': allow_origin: [''] allow_headers: [''] allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] max_age: 3600 Structure du projet SurfBuddy_Back/ ├── bin/ # Scripts exécutables │ └── console # Console Symfony ├── config/ # Configuration Symfony │ ├── packages/ # Configuration des bundles │ │ ├── api_platform.yaml │ │ ├── cache.yaml │ │ ├── doctrine.yaml │ │ ├── framework.yaml │ │ ├── nelmio_cors.yaml │ │ ├── routing.yaml │ │ ├── security.yaml │ │ ├── twig.yaml │ │ └── validator.yaml │ └── routes/ # Configuration des routes │ ├── api_platform.yaml │ ├── framework.yaml │ ├── security.yaml │ └── routes.yaml ├── migrations/ # Migrations de base de données ├── public/ # Dossier public accessible │ ├── bundles/ │ ├── images/ # Images uploadées │ │ ├── default-avatar.png │ │ ├── Empty_wave_at_Banzai_Pipeline.jpeg │ │ ├── image1.jpg │ │ ├── image2.jpg │ │ ├── image3.jpg │ │ ├── La-grande-plage-Biarritz.jpg │ │ └── Vague_Hossegor_PEP9556.jpg │ └── index.php # Point d'entrée de l'application ├── src/ # Code source de l'application │ ├── Controller/ # Contrôleurs API │ │ ├── AuthController.php # Authentification │ │ ├── SpotsController.php # Gestion des spots │ │ └── UsersController.php # Gestion des utilisateurs │ ├── Entity/ # Entités Doctrine │ │ ├── Spots.php # Entité Spots │ │ └── Users.php # Entité Users │ ├── Enum/ # Énumérations │ │ ├── DifficultyEnum.php # Niveaux de difficulté │ │ └── SpotTypeEnum.php # Types de spots │ ├── Repository/ # Repositories Doctrine │ │ ├── SpotsRepository.php # Repository des spots │ │ └── UsersRepository.php # Repository des utilisateurs │ └── Kernel.php # Kernel Symfony ├── templates/ # Templates Twig (si utilisés) │ ├── spots/ │ │ └── index.html.twig │ └── users/ │ ├── index.html.twig │ └── base.html.twig ├── var/ # Fichiers temporaires ├── vendor/ # Dépendances Composer ├── .env # Variables d'environnement (template) ├── .gitignore # Fichiers à ignorer par Git ├── compose.override.yaml # Configuration Docker Compose (optionnel) ├── compose.yaml # Configuration Docker Compose (optionnel) ├── composer.json # Configuration Composer ├── composer.lock # Fichier de verrouillage Composer └── symfony.lock # Fichier de verrouillage Symfony Documentation API Exemples de requêtes Inscription d'un utilisateur :
bash
curl -X POST http://localhost:8000/api/auth/register
-H "Content-Type: application/json"
-d '{
"alias": "surfeur123",
"email": "[email protected]",
"password": "motdepasse123"
}'
Connexion :
bash
curl -X POST http://localhost:8000/api/auth/login
-H "Content-Type: application/json"
-d '{
"email": "[email protected]",
"password": "motdepasse123"
}'
Récupération des spots avec pagination :
bash
curl -X GET "http://localhost:8000/api/spots?page=1&limit=10&country=France"
-H "Authorization: Bearer YOUR_JWT_TOKEN"
Création d'un nouveau spot :
bash
curl -X POST http://localhost:8000/api/spots
-H "Content-Type: application/json"
-H "Authorization: Bearer YOUR_JWT_TOKEN"
-d '{
"spotName": "La Gravière",
"difficulty": "EXPERT",
"country": "France",
"city": "Hossegor",
"latitude": 43.6617,
"longitude": -1.4072,
"seasonBegin": "2024-09-01",
"seasonEnd": "2024-04-30",
"type": "BEACH_BREAK"
}'
Tests et développement
Commandes utiles
bash
php bin/console cache:clear
php bin/console doctrine:schema:validate
php bin/console make:migration
php bin/console make:controller
php bin/phpunit
php bin/console debug:router Variables d'environnement de développement env
APP_ENV=dev APP_DEBUG=true
DATABASE_URL="mysql://root:@127.0.0.1:3306/surfbuddy_test?charset=utf8mb4"
CORS_ALLOW_ORIGIN=* Intégration avec le frontend Cette API est conçue pour fonctionner avec l'application React Native SurfBuddy. Points d'intégration importants :
Configuration CORS : Autorise les requêtes depuis l'application mobile Format JSON : Toutes les réponses sont au format JSON Authentification JWT : Tokens à inclure dans les headers des requêtes Gestion des erreurs : Codes HTTP standards et messages d'erreur explicites Upload d'images : Support des images en base64 ou multipart/form-data Sécurité Authentification JWT : Tokens sécurisés avec expiration Validation des données : Validation stricte des inputs Hachage des mots de passe : Utilisation de bcrypt Protection CSRF : Configuration Symfony Security Sanitisation : Protection contre les injections SQL et XSS Améliorations futures Basé sur la feuille de route du projet et les besoins identifiés :
Tests automatisés : Suite de tests unitaires et d'intégration Documentation OpenAPI : Documentation auto-générée avec API Platform Cache Redis : Mise en cache pour améliorer les performances Monitoring : Logs et métriques de performance Docker : Containerisation pour le déploiement CI/CD : Pipeline d'intégration et déploiement continu Notifications push : Système de notifications pour l'app mobile API versioning : Gestion des versions de l'API Rate limiting : Protection contre les abus Backup automatique : Stratégie de sauvegarde de la base de données 🇬🇧 English Version SurfBuddy Backend is a REST API developed with PHP Symfony that powers the SurfBuddy mobile application. This API manages surf spots worldwide, user authentication, and all CRUD operations necessary for the mobile application to function properly. This project was developed as part of the mobile development curriculum at Ada Tech School, focusing on creating robust and secure APIs.
Features 🌊 Complete REST API: Endpoints for surf spots management 🔐 JWT Authentication: Secure authentication system with JWT tokens 👥 User Management: Registration, login, and profile management 📸 Image Upload: Management of spot photos and user profiles 🗺️ Geolocation: GPS coordinates support for spots 🔍 Filtering and Pagination: Query optimization with filters and pagination 📊 MySQL Database: Persistent storage with Doctrine ORM 🛡️ CORS Security: CORS configuration for mobile integration ⚡ Optimized Performance: Optimized queries and caching Tech Stack PHP 8.1+ Symfony 6.4+ Framework Doctrine ORM for database management MySQL 8.0+ Database JWT Authentication for security Nelmio CORS Bundle for CORS configuration API Platform (optional) for auto-documentation Twig for templates (if needed) Composer for dependency management API Architecture Main Endpoints Authentication:
POST /api/auth/register - User registration POST /api/auth/login - User login POST /api/auth/refresh - Token refresh Surf Spots:
GET /api/spots - List spots (with pagination and filters) GET /api/spots/{id} - Get specific spot details POST /api/spots - Create new spot (authenticated) PUT /api/spots/{id} - Update spot (authenticated) DELETE /api/spots/{id} - Delete spot (authenticated) Users:
GET /api/users/profile - Get user profile (authenticated) PUT /api/users/profile - Update profile (authenticated) POST /api/users/avatar - Upload profile picture (authenticated) Data Model Spots Entity php class Spots { private int $id; private string $spotName; private DifficultyEnum $difficulty; private string $country; private string $city; private float $latitude; private float $longitude; private \DateTime $seasonBegin; private \DateTime $seasonEnd; private ?string $spotPicture; private SpotTypeEnum $type; private Users $user; // Spot creator } Users Entity php class Users { private int $id; private string $alias; private string $email; private string $password; // Hashed private ?string $picture; private Collection $spots; // Spots created by user } Enums DifficultyEnum: BEGINNER, INTERMEDIATE, ADVANCED, EXPERT SpotTypeEnum: BEACH_BREAK, REEF_BREAK, POINT_BREAK, RIVER_MOUTH Prerequisites Before installing this project, make sure you have:
PHP 8.1 or higher Composer (PHP dependency manager) MySQL 8.0 or higher Git Web server (Apache, Nginx, or Symfony development server) Installation Clone the repository bash git clone https://github.com/adatechschool/SurfBuddy_Back.git cd SurfBuddy_Back Install dependencies bash composer install Environment configuration Copy the .env file and configure your environment variables: bash cp .env .env.local Edit .env.local with your parameters: env
DATABASE_URL="mysql://username:[email protected]:3306/surfbuddy_db?charset=utf8mb4"
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem JWT_PASSPHRASE=your_jwt_passphrase
CORS_ALLOW_ORIGIN=^https?://(localhost|127.0.0.1)(:[0-9]+)?$
APP_ENV=dev APP_SECRET=your_app_secret_key Database setup bash
php bin/console doctrine:database:create
php bin/console doctrine:migrations:migrate
php bin/console doctrine:fixtures:load Generate JWT keys bash php bin/console lexik:jwt:generate-keypair Start development server bash
symfony server:start
php -S localhost:8000 -t public/ Development Context This project was developed as part of the Mobile Development curriculum at Ada Tech School. The project follows a step-by-step approach as outlined in the course materials:
Step 1-2: Basic JSON API with static data and iOS integration Step 3-4: Dynamic database with list and detail endpoints Step 5-7: iOS integration with detailed views Step 8-9: POST endpoints and form integration Step 10: MySQL database integration Step 11: Filtering and pagination Sky is the limit: User sessions, authentication, and advanced features Frontend Integration This API is designed to work with the SurfBuddy React Native application. Key integration points:
CORS Configuration: Allows requests from mobile application JSON Format: All responses in JSON format JWT Authentication: Tokens to include in request headers Error Handling: Standard HTTP codes and explicit error messages Image Upload: Support for base64 or multipart/form-data images Security JWT Authentication: Secure tokens with expiration Data Validation: Strict input validation Password Hashing: Using bcrypt CSRF Protection: Symfony Security configuration Sanitization: Protection against SQL injection and XSS Testing and Development Useful Commands bash
php bin/console cache:clear
php bin/console doctrine:schema:validate
php bin/console make:migration
php bin/console make:controller
php bin/phpunit
php bin/console debug:router Future Enhancements Based on the project roadmap and identified needs:
Automated Testing: Unit and integration test suite OpenAPI Documentation: Auto-generated documentation with API Platform Redis Cache: Caching for performance improvement Monitoring: Logs and performance metrics Docker: Containerization for deployment CI/CD: Continuous integration and deployment pipeline Push Notifications: Notification system for mobile app API Versioning: API version management Rate Limiting: Protection against abuse Automatic Backup: Database backup strategy Contributing This project was developed as part of Ada Tech School's curriculum. If you'd like to contribute:
Fork the repository Create a feature branch (git checkout -b feature/AmazingFeature) Commit your changes (git commit -m 'Add some AmazingFeature') Push to the branch (git push origin feature/AmazingFeature) Open a Pull Request Troubleshooting Common Issues Database connection issues:
bash
php bin/console doctrine:database:create --if-not-exists JWT key issues:
bash
php bin/console lexik:jwt:generate-keypair --overwrite CORS issues:
Check your CORS configuration in config/packages/nelmio_cors.yaml Ensure your frontend origin is allowed Permission issues:
bash
chmod -R 777 var/ About Ada Tech School This project was developed as part of the mobile development curriculum at Ada Tech School, a coding school focused on inclusive and collaborative learning.
License This project is open source.
Acknowledgments Ada Tech School for the project framework and guidance The Symfony community for the excellent framework and documentation The surfing community for inspiration and domain knowledge Built with ❤️ by students passionate about both technology and surfing Happy Coding and Surfing! 🏄♂️🚀
"L'API qui propulse votre passion du surf !" "The API that powers your surfing passion!"