Skip to content

Repository files navigation

Ticketing System API

A production-ready REST API for a Ticketing System built with Laravel 12, PostgreSQL, and modern authentication. This system provides comprehensive ticket management with role-based access control, real-time notifications, and export capabilities.

Features

  • Authentication: Token-based authentication using Laravel Sanctum
  • Role-Based Access Control: Admin, Staff, and User roles with Spatie Laravel Permission
  • Ticket Management: Full CRUD operations with status tracking
  • Comment System: Add and view comments on tickets
  • Admin Dashboard: Statistics and data export functionality
  • API Documentation: Interactive Swagger UI documentation
  • Email Notifications: Automated notifications for ticket events
  • Export Capabilities: CSV and PDF export for reporting
  • Queue System: Background job processing for emails
  • Testing: Comprehensive feature tests with PHPUnit
  • Security: Rate limiting, CORS protection, input sanitization, strong password requirements

Tech Stack

  • Framework: Laravel 12
  • Database: PostgreSQL 15+
  • Authentication: Laravel Sanctum
  • Authorization: Spatie Laravel Permission
  • API Documentation: L5-Swagger (OpenAPI 3.0)
  • Export: Laravel Excel (CSV) and DomPDF (PDF)
  • Mail: Laravel Mail with queue support
  • Testing: PHPUnit with Laravel testing framework

Security Features

  • Rate Limiting: 60 requests/minute for API, 10/minute for login, 30/minute for registration
  • CORS Protection: Configurable allowed origins
  • Input Sanitization: XSS prevention for user-generated content
  • Strong Passwords: Minimum 10 characters with uppercase, numbers, and symbols
  • Authorization Checks: Role-based access control on all endpoints
  • Token Expiration: 60-minute token validity
  • Production-Safe Seeders: Default users only created in development

Prerequisites

  • PHP 8.3 or higher
  • Composer
  • PostgreSQL 15 or higher
  • Node.js and npm (for API documentation assets)

Installation

1. Clone the Repository

git clone <repository-url>
cd ticketing-system

2. Install Dependencies

composer install

3. Environment Configuration

cp .env.example .env

Edit the .env file and configure your database settings:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=ticketing_system
DB_USERNAME=your_username
DB_PASSWORD=your_password

MAIL_MAILER=log
MAIL_FROM_ADDRESS=your-email@example.com
MAIL_FROM_NAME="Ticketing System"

4. Generate Application Key

php artisan key:generate

5. Database Setup

# Create PostgreSQL database
createdb ticketing_system

# Run migrations and seeders
php artisan migrate --seed

This will create:

  • Admin user: admin@example.com / admin123
  • Staff users: staff1@example.com, staff2@example.com / staff123
  • Regular users: john@example.com, jane@example.com, bob@example.com / user123
  • Sample tickets and comments

6. Generate API Documentation

php artisan l5-swagger:generate

7. Start the Application

php artisan serve

8. Start Queue Worker (for email notifications)

php artisan queue:work

API Documentation

Access the interactive API documentation at:

http://localhost:8000/api/docs

Authentication

The API uses token-based authentication with Laravel Sanctum. Include the token in the Authorization header:

Authorization: Bearer YOUR_TOKEN_HERE

Register

curl -X POST http://localhost:8000/api/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123"
  }'

Login

curl -X POST http://localhost:8000/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "password123"
  }'

API Endpoints

Authentication

  • POST /api/register - Register new user
  • POST /api/login - Login user
  • POST /api/logout - Logout user

Tickets

  • GET /api/tickets - List tickets (filtered by user role)
  • POST /api/tickets - Create new ticket
  • GET /api/tickets/{id} - Get ticket details
  • PUT /api/tickets/{id} - Update ticket
  • DELETE /api/tickets/{id} - Delete ticket

Comments

  • POST /api/tickets/{id}/comments - Add comment to ticket
  • GET /api/tickets/{id}/comments - Get ticket comments

Admin Endpoints

  • GET /api/admin/tickets/stats - Get ticket statistics
  • GET /api/admin/tickets/export?format=csv&status=open - Export tickets

User Roles

Admin

  • Full access to all tickets
  • Can assign tickets to staff
  • Access to admin endpoints
  • Can export data

Staff

  • Can view all tickets
  • Can update ticket status and assignments
  • Can add comments to any ticket

User

  • Can only view and manage their own tickets
  • Can add comments to their tickets
  • Cannot access admin endpoints

Testing

Run the test suite:

php artisan test

Run tests with coverage:

php artisan test --coverage

Run specific test file:

php artisan test tests/Feature/AuthTest.php

Queue Management

Start Queue Worker

php artisan queue:work

Check Failed Jobs

php artisan queue:failed

Retry Failed Jobs

php artisan queue:retry all

Troubleshooting

Database Connection Issues

  1. Ensure PostgreSQL is running
  2. Verify database credentials in .env
  3. Check if the database exists: psql -l
  4. Run migrations: php artisan migrate

Queue Not Processing

  1. Ensure queue worker is running: php artisan queue:work
  2. Check queue configuration: QUEUE_CONNECTION=database
  3. Verify failed jobs table exists: php artisan queue:failed-table

Email Notifications Not Working

  1. Check mail configuration in .env
  2. For development, use: MAIL_MAILER=log
  3. For production, configure SMTP settings
  4. Ensure queue worker is running for email processing

API Documentation Not Loading

  1. Install npm dependencies: npm install
  2. Generate documentation: php artisan l5-swagger:generate
  3. Check if assets are published: php artisan vendor:publish --provider="L5Swagger\L5SwaggerServiceProvider"

Permission Issues

  1. Clear application cache: php artisan cache:clear
  2. Clear config cache: php artisan config:clear
  3. Clear route cache: php artisan route:clear
  4. Re-run migrations if needed: php artisan migrate:fresh --seed

Development

Adding New Features

  1. Create migration: php artisan make:migration add_field_to_table
  2. Create model: php artisan make:model NewModel
  3. Create controller: php artisan make:controller Api/NewController
  4. Add routes in routes/api.php
  5. Update API documentation annotations
  6. Write tests in tests/Feature/

Code Style

This project follows Laravel's coding standards. Run the following to check and fix code style:

php artisan pint

Deployment

Production Environment Checklist

  1. Environment Configuration

    APP_ENV=production
    APP_DEBUG=false
    APP_KEY=<generate-with-php-artisan-key-generate>
  2. Database Configuration

    • Use strong database credentials
    • Enable SSL for database connections
    • Run migrations: php artisan migrate --force
    • Do NOT run seeders in production
  3. Security Settings

    BCRYPT_ROUNDS=14
    SESSION_SECURE_COOKIE=true
    SESSION_HTTP_ONLY=true
    SESSION_SAME_SITE=strict
    SANCTUM_EXPIRES_AT=60
  4. Cache Optimization

    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    php artisan event:cache
  5. Queue Configuration

    • Set QUEUE_CONNECTION=database or redis
    • Run queue worker: php artisan queue:work --tries=3 --timeout=60
    • Use supervisor to manage queue workers
  6. Web Server Configuration

    • Configure Nginx/Apache for Laravel
    • Enable SSL/TLS certificates
    • Set up proper headers (HSTS, CSP, etc.)
    • Configure rate limiting at server level
  7. Monitoring & Logging

    • Set LOG_CHANNEL=errorlog or configure external logging
    • Set up application monitoring (Sentry, Bugsnag, etc.)
    • Monitor queue failed jobs

Production Installation Steps

# 1. Install dependencies
composer install --optimize-autoloader --no-dev

# 2. Copy and configure environment
cp .env.example .env
# Edit .env with production values

# 3. Generate app key
php artisan key:generate

# 4. Run migrations
php artisan migrate --force

# 5. Optimize application
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 6. Generate API documentation
php artisan l5-swagger:generate

# 7. Set proper file permissions
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

Docker Deployment

Create a docker-compose.yml file for containerized deployment:

version: '3.8'
services:
  app:
    image: php:8.3-fpm
    volumes:
      - ./:/var/www/html
    environment:
      - APP_ENV=production
      - APP_DEBUG=false
    depends_on:
      - db
      - redis
  
  webserver:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./:/var/www/html
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
    depends_on:
      - app
  
  db:
    image: postgres:15
    environment:
      POSTGRES_DB=ticketing_system
      POSTGRES_USER=postgres
      POSTGRES_PASSWORD=<strong-password>
    volumes:
      - postgres_data:/var/lib/postgresql/data
  
  redis:
    image: redis:alpine
  
  queue:
    image: php:8.3-cli
    command: php artisan queue:work --tries=3
    volumes:
      - ./:/var/www/html
    depends_on:
      - db
      - redis

volumes:
  postgres_data:

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

This project is licensed under the MIT License.

Support

For support and questions:

  • Create an issue in the repository
  • Check the troubleshooting section above
  • Review the API documentation at /api/docs

Changelog

Version 1.1.0 - Production Ready

Security Improvements:

  • Added API rate limiting (60 req/min general, 10 req/min login, 30 req/min registration)
  • Implemented CORS configuration for cross-origin requests
  • Added input sanitization for comments (XSS prevention)
  • Strengthened password requirements (min 10 chars, uppercase, numbers, symbols)
  • Fixed authorization checks in TicketController and CommentController
  • Reduced token expiration from 24 hours to 60 minutes
  • Added production-safe seeders (default users only in development)

Code Quality:

  • Added comprehensive error handling with try-catch blocks in all controllers
  • Improved validation rules (description min/max length, category length)
  • Optimized admin stats query (single query instead of 5 separate queries)
  • Added null-safe access in CSV export
  • Removed empty boot() methods from models
  • Cleaned up duplicate casts in User model
  • Hidden role field from API responses

Database:

  • Added performance indexes on frequently queried columns
  • Added composite indexes for common query patterns
  • Improved migration for production safety

Documentation:

  • Updated README with production deployment checklist
  • Added Docker deployment configuration
  • Updated .env.example with new configuration options

Version 1.0.0

  • Initial release with full ticketing system functionality
  • Laravel 12 compatibility
  • PostgreSQL support
  • Role-based access control
  • API documentation with Swagger
  • Email notifications with queue processing
  • Export functionality (CSV/PDF)
  • Comprehensive test suite

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages