Commit Graph

8 Commits

Author SHA1 Message Date
Rezon Philip 060cf8c78b feat(auth): Implement comprehensive JWT authentication system with token rotation
This commit introduces a complete authentication system using JWT-based access and refresh
tokens, secure session management, and refresh token rotation to enhance overall security.

Core Authentication Features:
- Dual-token system: Short-lived access tokens (15 min) + long-lived refresh tokens (7 days)
- Hybrid security model: JWT signatures + SHA-256 hashed refresh tokens in database
- Session tracking: Device info, IP address, and user agent for security auditing
- Token rotation: Automatically rotates refresh tokens on each use to reduce theft exposure
- Multi-tenant support: TenantID embedded in access tokens for data isolation

Security Implementations:
- bcrypt password hashing for user credentials
- SHA-256 hashing for refresh token persistence and fast lookup
- HttpOnly + Secure + SameSite cookies for XSS/CSRF protection
- Token type validation to prevent misuse of refresh tokens as access tokens
- Robust input validation (email structure, password strength, uniqueness)
- Generic authentication errors to prevent email enumeration attacks

Authentication Middleware:
- Required authentication: Rejects unauthorized requests with 401
- Optional authentication: Allows public/private hybrid endpoints
- Dual token source support: Cookies (web) + Authorization header (mobile/API)
- Injects user claims into request context for downstream handlers

Rate Limiting:
- Sliding window algorithm to prevent brute force and DoS attacks
- Configurable per-IP limits with automatic counter cleanup
- Thread-safe design using mutex locks
- Returns 429 Too Many Requests on rate limit violations

Password & Email Validation:
- Password rules: Minimum length, mixed character types, no personal info
- Email validation: RFC-compliant parsing + normalization (lowercase/trim)
- Case-insensitive uniqueness checks during registration

Session Management:
- Database-backed sessions for immediate revocation and device tracking
- View active sessions per user (with metadata)
- Revoke single or all sessions
- Automatic cleanup of expired/revoked sessions

API Endpoints Added:
- POST /api/v1/auth/login   – Authenticate user and issue tokens
- POST /api/v1/auth/refresh – Rotate refresh token and issue new access token
- POST /api/v1/auth/logout  – Revoke session and clear cookies
- GET  /api/v1/health       – Protected health check route

Service Layer Enhancements:
- AuthService: Token generation/validation, session lifecycle management
- UserService: Registration, authentication, and password updates

CORS Configuration:
- Localhost origins for development (5173, 3000)
- Configurable allowed methods/headers/credentials
- 1-hour preflight caching
- Production-ready whitelist via environment config

Files Added:
- pkg/auth/claims.go
- internal/services/auth_service.go
- internal/services/user_service.go
- internal/repositories/session_repository.go
- internal/repositories/user_repository.go
- internal/handlers/auth_handler.go
- internal/middleware/auth_middleware.go
- internal/middleware/cors.go
- internal/middleware/rate_limiter.go
- internal/models/session.go
- internal/models/user.go
- internal/config/config.go
- internal/routes/routes.go

Technical Stack:
- Echo v4, golang-jwt/jwt v5, sqlx, bcrypt, PostgreSQL

Testing Considerations:
- Dependency injection for easy mocking
- Service-layer testing independent of HTTP stack
- Repository abstraction supporting mock DBs
- Time-based logic testable via injected clock

Future Enhancements:
- Redis-powered rate limiting for scaling
- Password history enforcement
- Have I Been Pwned integration
- Email verification workflow
- Two-factor authentication (2FA)
- OAuth/social login support
- Monitoring/metrics (Prometheus)
- Structured logging with request IDs

Story: E2-001-2 – JWT Authentication System Implementation
2025-12-08 02:10:21 +05:30
Rezon Philip a0dba4261f
Merge pull request #6 from creativenoz/feature/postgres-config
chore(postgres_db): Relocated database files to outside backend, init DockerFile, expand docker-compose
2025-12-03 23:01:45 +05:30
Rezon Philip 05b056c804 chore(postgres_db): Relocated database files to outside backend, init DockerFile, expand docker-compose
This commit relocates the database files to outside the backend folder, to the root aurganize folder.
- we initialise the backend Dockerfile.dev
- we expand the docker-compose to migrate our backend to docker

This improves developer experience and standardizes database operations for the entire backend team.

Story: E1-004 - PostgreSQL Database Setup
2025-12-03 22:57:47 +05:30
Rezon Philip b2ce4672cf
Merge pull request #5 from creativenoz/feature/api-server-main
chore(makefile): Define backend project makefile
2025-12-03 22:50:39 +05:30
Rezon Philip 0182a1ae9e chore(postgres_db): Add full PostgreSQL tooling (migrations, seeds, backup, restore, health-check)
This commit introduces a complete PostgreSQL developer workflow for the Aurganize backend,
fully integrated with the Dockerized database environment.

Included changes:
  • Added initial migration
  • Added development seed script with temporary RLS disable/enable logic
  • Added test operation script to validate if the entries are working as expected
  • Added docker-aware backup script:
        - Dumps DB from inside postgres container
        - Stores compressed .sql.gz backups outside repo
        - Auto-cleans old backups
  • Added docker-aware restore script:
        - Drops and recreates DB
        - Restores from compressed backups
  • Added Docker-based database health check:
        - Moved health_check.sql to database/tests/
        - Added health_check.sh wrapper to run through docker exec
  • Updated directory structure for database scripts and tests
  • Ensured all scripts auto-detect container, user, and file locations

This improves developer experience and standardizes database operations for the entire backend team.

Story: E1-004 - PostgreSQL Database Setup
2025-12-03 00:39:34 +05:30
Rezon Philip 09249032e7 chore(makefile): Define backend project makefile
Available targets:\033[0m
  help            Show this help message
  dev             Run development server with hot reload (requires Air)
  run             Run server without hot reload
  build           Build production binary
  build-local     Build binary for local OS
  test            Run all tests
  test-coverage   Run tests and show coverage report
  test-unit       Run unit tests only
  test-integration Run integration tests only
  bench           Run benchmarks
  clean           Clean build artifacts and caches
  deps            Download dependencies
  deps-update     Update all dependencies
  lint            Run linter
  fmt             Format code
  vet             Run go vet
  check           Run all checks (fmt, vet, lint, test)
  migrate-up      Run database migrations
  migrate-down    Rollback last migration
  migrate-create  Create new migration (usage: make migrate-create NAME=add_users_table)
  docker-build    Build Docker image
  docker-run      Run Docker container
  install-air     Install Air for hot reload
  install-linter  Install golangci-lint
  install-migrate Install golang-migrate
  install-tools   Install all development tools
  db-psql         Connect to database with psql
  seed            Run database seed script
  mod-graph       Show dependency graph
  mod-why         Show why a package is needed (usage: make mod-why PKG=github.com/pkg/errors)
  version         Show version information
  info            Show project information

This commit establishes the foundation for all future development.

Story: E1-002 - Backend Project Initialization (makefile)
2025-11-30 03:18:41 +05:30
Rezon Philip b99866db54 feat(echo server): Define backend api server using echo framework
API server (backend/cmd/api):
- we load configuration
- init logger
- create echo server instance
- we define the middleware pipeline
--- recover
--- request_id
--- logger_format
--- cors (ross-Origin Resource Sharing)
--- security_headers
--- gzip_compresssion
- route_mapping
- star_server
- graceful_shutdown

add-ons:
- healthCheckHandler()
- customHTTPErrorHandler()

This commit establishes the foundation for all future development.

Story: E1-002 - Backend Project Initialization (main echo server)
2025-11-29 20:52:17 +05:30
Rezon Philip 96651fceea feat(config,loggin): Defining global config loading and multi-level logging mechanism
Config (backend/internal/confi)
- Defined the global config loading in internal/config/config.go
- - Defined DatabaseSN() and RedisDSN() to expose their respective connection strings
- Defined the env example to refer to while creating the .env file in your local
Logging (backend/pkg/logger)
- Defined the global loggin mechanism ( logger.go )
- Created and validated the logging through tests ( logger_test.go )written and validated
- Added a reference ( example_test.go ) to refer to understand about usage of logging mechanims

This commit establishes the foundation for all future development.

Story: E1-002 - Backend Project Initialization (Partial)
2025-11-29 16:40:25 +05:30