Veranstaltungen-APP/API_AUTHENTICATION_GUIDE.md

361 lines
7.4 KiB
Markdown

# API Authentication Guide - Mobile App Integration
## Overview
Your Laravel application is now fully configured with **Laravel Sanctum** token-based authentication, perfect for mobile app development.
## System Status ✅
### Completed Features
- ✅ User authentication with email/password
- ✅ Role-based access control (user, organizer, admin)
- ✅ Token generation and validation
- ✅ Protected API endpoints
- ✅ User favorites system
- ✅ Event management with permissions
### Test Users Available
All passwords are `password123`
| Email | Role | Purpose |
|-------|------|---------|
| user@example.com | user | Regular user - can view events & favorites |
| organizer@example.com | organizer | Can create/update/delete own events |
| admin@example.com | admin | Full system access |
---
## API Endpoints
### 1. Authentication Endpoints (PUBLIC)
#### Login
```
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "password123"
}
Response (200):
{
"success": true,
"message": "Login erfolgreich",
"user": {
"id": 1,
"name": "Test User",
"email": "user@example.com",
"role": "user",
"created_at": "2025-04-14T08:42:12.000000Z",
"updated_at": "2025-04-14T08:42:12.000000Z"
},
"token": "1|PZHueLvJEr6d9mU1d4J7FUVJiPh0LD1Uy6S2Qc"
}
```
#### Register
```
POST /api/auth/register
Content-Type: application/json
{
"name": "New User",
"email": "newuser@example.com",
"password": "password123",
"password_confirmation": "password123",
"role": "user" // Optional: "user" (default), "organizer", or "admin"
}
Response (201): Similar to login response with new user token
```
### 2. Protected Endpoints (REQUIRE auth:sanctum)
All protected endpoints require the token in the Authorization header:
```
Authorization: Bearer YOUR_TOKEN_HERE
```
#### Get Current User
```
GET /api/auth/me
Authorization: Bearer 1|PZHueLvJEr6d9mU1d4J7FUVJiPh0LD1Uy6S2Qc
```
#### Update Profile
```
PUT /api/auth/profile
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"name": "Updated Name",
"email": "newemail@example.com"
}
```
#### Change Password
```
POST /api/auth/change-password
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"current_password": "password123",
"password": "newpassword123",
"password_confirmation": "newpassword123"
}
```
#### Logout
```
POST /api/auth/logout
Authorization: Bearer YOUR_TOKEN
```
### 3. Public Event Endpoints
#### List All Events
```
GET /api/events
```
#### Get Event Details
```
GET /api/events/{id}
```
#### Get Available Locations
```
GET /api/events/locations/list
```
#### Get Available Categories
```
GET /api/events/categories/list
```
### 4. Protected Event Management (Organizers Only)
#### Get My Events
```
GET /api/events/my-events
Authorization: Bearer YOUR_TOKEN
```
#### Create Event (Organizer/Admin Only)
```
POST /api/events
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"title": "New Event",
"description": "Event description",
"category": "Music",
"location_id": 1,
"website_url": "https://...",
"contact_email": "contact@...",
"contact_phone": "+49..."
}
```
#### Update Event (Creator Only)
```
PUT /api/events/{id}
Authorization: Bearer YOUR_TOKEN
Content-Type: application/json
{
"title": "Updated Title",
"description": "Updated description",
...
}
```
#### Delete Event (Creator Only)
```
DELETE /api/events/{id}
Authorization: Bearer YOUR_TOKEN
```
### 5. Favorites System
#### Toggle Favorite
```
POST /api/events/{id}/toggle-favorite
Authorization: Bearer YOUR_TOKEN
```
#### Get My Favorites
```
GET /api/events/favorites
Authorization: Bearer YOUR_TOKEN
```
---
## Mobile App Integration
### Authentication Flow
```
1. User enters email and password
2. POST /api/auth/login
3. Receive token from response
4. Store token securely (e.g., keychain on iOS, Keystore on Android)
5. Include token in all subsequent API calls:
Authorization: Bearer {token}
6. If token expires/401 error, prompt re-login
```
### Token Storage Best Practices
**iOS (Swift):**
```swift
// Store in Keychain
try keychain.store(token, key: "api_token")
let token = try keychain.retrieveString("api_token")
```
**Android (Kotlin):**
```kotlin
// Store in Encrypted SharedPreferences
val token = encryptedSharedPreferences.getString("api_token", null)
encryptedSharedPreferences.edit().putString("api_token", token).apply()
```
**Flutter:**
```dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage();
await storage.write(key: "api_token", value: token);
String? token = await storage.read(key: "api_token");
```
### Request Headers
```
GET /api/auth/me HTTP/1.1
Host: localhost:8000
Authorization: Bearer 1|PZHueLvJEr6d9mU1d4J7FUVJiPh0LD1Uy6S2Qc
Content-Type: application/json
Accept: application/json
```
---
## Error Handling
### Typical HTTP Responses
| Status | Meaning | Action |
|--------|---------|--------|
| 200 | Success | Process response data |
| 201 | Created | Resource successfully created |
| 400 | Bad Request | Check request format/validation |
| 401 | Unauthorized | Token invalid/expired - re-login |
| 403 | Forbidden | User lacks permission for this action |
| 404 | Not Found | Resource doesn't exist |
| 500 | Server Error | Report to developer |
### Error Response Format
```json
{
"success": false,
"message": "Error description",
"errors": {
"field_name": ["Validation error message"]
}
}
```
---
## Role-Based Permissions
| Feature | user | organizer | admin |
|---------|------|-----------|-------|
| View events | ✅ | ✅ | ✅ |
| Create event | ❌ | ✅ | ✅ |
| Edit own event | ❌ | ✅ | ✅ |
| Delete own event | ❌ | ✅ | ✅ |
| Manage favorites | ✅ | ✅ | ✅ |
| Admin panel | ❌ | ❌ | ✅ |
---
## Environment Details
- **Server**: http://localhost:8000
- **API Base**: http://localhost:8000/api
- **Database**: MySQL 5.7
- **Auth Method**: Laravel Sanctum (Personal Access Tokens)
- **Token Format**: UUID|plaintext_token
---
## Troubleshooting
### 401 Unauthorized
- Token might be expired
- Token format incorrect
- Token not included in header
- Solution: Re-login to get new token
### 403 Forbidden
- Your user role doesn't have permission
- Solution: Use appropriate user role for action
### 422 Unprocessable Entity
- Validation error in request data
- Check response `errors` field for details
- Ensure all required fields are provided
---
## Next Steps for Mobile Development
1. **Authentication Flow**
- Create login screen with email/password fields
- Implement token storage using platform-specific secure storage
- Create auto-login using stored token
2. **Event Listing**
- Fetch events from `/api/events`
- Implement pagination if needed
- Add search/filter functionality
3. **Event Details**
- Show event location, description, contact info
- Allow authenticated users to favorite events
4. **User Profile**
- Display user info from `/api/auth/me`
- Allow profile updates and password changes
5. **Event Management (for Organizers)**
- Create events form
- Edit/delete own events
- View analytics
---
## Support & Documentation
- Laravel Sanctum Docs: https://laravel.com/docs/11.x/sanctum
- API Response Examples: See docs/API_RESPONSES.md
- Example Queries: See docs/EXAMPLE_QUERIES.php
---
**Last Updated**: April 2025
**Status**: ✅ Production Ready for Mobile App Development