Skip to content

heiji-events/ms-user-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MS User

Overview

MS User is a Backend for Frontend (BFF) microservice designed for comprehensive user management and authentication within the Heiji Events ecosystem. As a BFF pattern implementation, this service serves as the single entry point for frontend applications, providing unified authentication, authorization, and data aggregation while proxying requests to downstream microservices (MS Event Manager and MS Ticket Manager). This service provides complete user lifecycle management including registration, authentication with JWT tokens, authorization controls, and role-based access control, serving as the central authentication hub and API gateway for all client applications.

Features

  • Backend for Frontend (BFF): Single entry point for all client applications with unified API
  • User Management: Full CRUD operations for user accounts
  • JWT Authentication: Secure token-based authentication system
  • Role-Based Access Control: ADMIN and USER role management with method-level security
  • API Gateway: Proxies and aggregates requests to MS Event Manager and MS Ticket Manager
  • Password Encryption: BCrypt password hashing for security
  • Event & Ticket Integration: Seamless integration with MS Event Manager and MS Ticket Manager
  • Soft Delete: Users are soft-deleted to maintain data integrity
  • Authorization Services: Fine-grained access control for resources
  • Request Orchestration: Coordinates multiple service calls and data aggregation
  • API Documentation: Swagger/OpenAPI 3.0 documentation
  • Test Coverage: Comprehensive unit tests for services and authentication
  • Security Filter: Custom JWT validation and authentication filter

Technology Stack

  • Java 17
  • Spring Boot 3.5.4
  • Spring Security 6 - Authentication and authorization
  • Spring Data MongoDB - Data persistence
  • Spring Cloud OpenFeign - External service communication
  • MongoDB - Primary database
  • JWT (Auth0) - Token generation and validation
  • MapStruct - Object mapping
  • Lombok - Boilerplate code reduction
  • SpringDoc OpenAPI - API documentation
  • Maven - Dependency management and build tool

API Endpoints

Authentication API (/v1/auth)

Method Endpoint Description
POST /v1/auth/login User login with JWT token generation

Users API (/v1/users)

Method Endpoint Description
POST /v1/users Create a new user account
GET /v1/users/{id} Get user by ID
GET /v1/users/cpf/{cpf} Get user by CPF (internal)
PUT /v1/users/{id} Update user information
DELETE /v1/users/{id} Soft delete user account

Events API (/v1/events) - BFF Proxy to MS Event Manager

Method Endpoint Description
POST /v1/events Create a new event (Admin)
GET /v1/events/{id} Get event by ID
GET /v1/events Get all events (paginated)
PUT /v1/events/{id} Update an existing event
DELETE /v1/events/{id} Soft delete an event

Tickets API (/v1/tickets) - BFF Proxy to MS Ticket Manager

Method Endpoint Description
POST /v1/tickets Create a new ticket
GET /v1/tickets/{id} Get ticket by ID
GET /v1/tickets Get all tickets (paginated)
DELETE /v1/tickets/{id} Soft delete a ticket

Request/Response Examples

User Registration

POST /v1/users
{
  "email": "user@example.com",
  "cpf": "12345678901",
  "password": "securepassword123"
}

User Login

POST /v1/auth/login
{
  "email": "user@example.com",
  "password": "securepassword123"
}

Authentication Response

{
  "id": "64f5a1b2e4b0d1a2b3c4d5e9",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "email": "user@example.com",
  "cpf": "12345678901"
}

User Response

{
  "id": "64f5a1b2e4b0d1a2b3c4d5e9",
  "email": "user@example.com",
  "cpf": "12345678901"
}

Project Structure

src/
├── main/
│   ├── java/br/com/shiroshima/msuser/
│   │   ├── MsUserApplication.java             # Main application class
│   │   ├── auth/                              # Authentication components
│   │   │   ├── SecurityFilter.java            # JWT validation filter
│   │   │   └── TokenService.java              # JWT token operations
│   │   ├── clients/                           # External service clients
│   │   │   ├── MsEventManagerClient.java      # Event service integration
│   │   │   └── MsTicketManagerClient.java     # Ticket service integration
│   │   ├── configs/                           # Configuration classes
│   │   │   ├── OpenAPIConfig.java             # Swagger configuration
│   │   │   └── SecurityConfiguration.java     # Security configuration
│   │   ├── controllers/                       # REST controllers
│   │   │   ├── AuthenticationController.java  # Authentication endpoints
│   │   │   ├── EventController.java           # Event proxy endpoints
│   │   │   ├── TicketController.java          # Ticket proxy endpoints
│   │   │   └── UserController.java            # User management endpoints
│   │   ├── dtos/                              # Data Transfer Objects
│   │   │   ├── AuthDTO.java
│   │   │   ├── UserAuthenticatedDTO.java
│   │   │   ├── UserCreateDTO.java
│   │   │   ├── UserResponseDTO.java
│   │   │   ├── UserUpdateDTO.java
│   │   │   ├── events/                        # Event DTOs
│   │   │   │   ├── EventCreateDTO.java
│   │   │   │   ├── EventEditDTO.java
│   │   │   │   ├── EventPageableDTO.java
│   │   │   │   └── EventResponseDTO.java
│   │   │   └── tickets/                       # Ticket DTOs
│   │   │       ├── TicketCreateDTO.java
│   │   │       ├── TicketEditDTO.java
│   │   │       ├── TicketPageableDTO.java
│   │   │       └── TicketResponseDTO.java
│   │   ├── entities/                          # Domain entities
│   │   │   ├── Role.java                      # User role enumeration
│   │   │   └── User.java                      # User entity
│   │   ├── exceptions/                        # Custom exceptions
│   │   │   ├── ApiExceptionManager.java
│   │   │   ├── ErrorMessage.java
│   │   │   ├── EventNotFoundException.java
│   │   │   ├── EventWithPendingTicketsException.java
│   │   │   ├── TokenGenerationErrorException.java
│   │   │   ├── UniqueUserViolationException.java
│   │   │   └── UserNotFoundException.java
│   │   ├── mappers/                           # MapStruct mappers
│   │   │   └── UserMapper.java
│   │   ├── openapi/                           # OpenAPI specifications
│   │   │   ├── AuthenticationControllerOpenAPI.java
│   │   │   ├── EventControllerOpenAPI.java
│   │   │   ├── TicketControllerOpenAPI.java
│   │   │   └── UserControllerOpenAPI.java
│   │   ├── repositories/                      # Data repositories
│   │   │   └── UserRepository.java
│   │   └── services/                          # Business logic
│   │       ├── AuthorizationService.java      # Authentication & authorization
│   │       └── UserService.java               # User business logic
│   └── resources/
│       ├── application.yml                    # Application configuration
│       ├── static/                            # Static resources
│       └── templates/                         # Template files
└── test/                                      # Test classes
    └── java/br/com/shiroshima/msuser/
        ├── MsUserApplicationTests.java
        ├── auth/                              # Authentication tests
        │   └── TokenServiceTest.java
        └── services/                          # Service tests
            ├── AuthorizationServiceTest.java
            └── UserServiceTest.java

Configuration

Environment Variables

Variable Default Description
MONGO_URI mongodb+srv://admin:admin@cluster0.bzpkqgg.mongodb.net/db_user?retryWrites=true&w=majority&appName=Cluster0?ssl=true&sslInvalidHostNameAllowed=true MongoDB connection string
PORT 8080 Application server port
MS_TICKET_URL http://localhost:8082/v1 MS Ticket Manager service URL
MS_EVENT_URL http://localhost:8081/v1 MS Event Manager service URL
JWT_SECRET dev-environment JWT signing secret key
JWT_ISSUER auth-api JWT token issuer
JWT_EXPIRATION_HOURS 2 JWT token expiration in hours
JWT_TIMEZONE_OFFSET -03:00 JWT timezone offset

Application Configuration

The application uses application.yml for configuration:

spring:
  application:
    name: ms-user
  data:
    mongodb:
      uri: ${MONGO_URI}
      authentication-database: admin

server:
  port: ${PORT:8080}

springdoc:
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true
    path: /swagger-ui.html

clients:
  ms-ticket-manager:
    url: ${MS_TICKET_URL:http://localhost:8082/v1}
  ms-event-manager:
    url: ${MS_EVENT_URL:http://localhost:8081/v1}

api:
  security:
    token:
      secret: ${JWT_SECRET:dev-environment}
      issuer: ${JWT_ISSUER:auth-api}
      expiration:
        hours: ${JWT_EXPIRATION_HOURS:2}
      timezone:
        offset: ${JWT_TIMEZONE_OFFSET:-03:00}

Getting Started

Prerequisites

  • Java 17 or higher
  • Maven 3.6+
  • MongoDB instance (local or remote)

Installation

  1. Clone the repository

    git clone https://github.com/heiji-events/ms-user.git
    cd ms-user
  2. Set environment variables (optional)

    export MONGO_URI="your-mongodb-connection-string"
    export PORT="8080"
    export MS_TICKET_URL="http://localhost:8082/v1"
    export MS_EVENT_URL="http://localhost:8081/v1"
    export JWT_SECRET="your-jwt-secret-key"
    export JWT_ISSUER="your-jwt-issuer"
    export JWT_EXPIRATION_HOURS="2"
    export JWT_TIMEZONE_OFFSET="-03:00"
  3. Build the project

    ./mvnw clean compile
  4. Run tests

    ./mvnw test
  5. Start the application

    ./mvnw spring-boot:run

API Documentation

Once the application is running, you can access the API documentation at:

Authentication & Authorization

JWT Token Authentication

The service uses JWT tokens for stateless authentication:

  • Tokens are generated upon successful login
  • Tokens include user email as subject
  • Configurable expiration time (default: 2 hours)
  • Tokens must be included in Authorization header as Bearer {token}

Role-Based Access Control

The system supports two user roles:

  • ADMIN: Full access to all endpoints including event management
  • USER: Limited access to user-specific resources and public endpoints

Security Endpoints

  • Public Access: User registration, login, some event/ticket viewing
  • Authenticated Access: User profile management, ticket creation
  • Admin Access: Event management, user administration
  • Owner Access: Users can only access their own resources

Validation Rules

User Registration/Update

  • Email: Valid email format, unique in system
  • CPF: Valid Brazilian CPF format (11 digits without formatting), unique in system
  • Password: 5-50 characters for creation/update

Authentication

  • Email: Must not be blank, valid format
  • Password: Must not be blank

External Dependencies

MS Event Manager

  • Purpose: Event management operations
  • Default URL: http://localhost:8081/v1
  • Integration: Create, read, update, delete events

MS Ticket Manager

  • Purpose: Ticket management operations
  • Default URL: http://localhost:8082/v1
  • Integration: Create, read, delete tickets, owner validation

Development

Code Quality Tools

  • MapStruct: Compile-time object mapping
  • Lombok: Reduces boilerplate code
  • Spring Boot DevTools: Hot reloading during development
  • Spring Security Test: Security testing utilities

Building and Testing

# Compile the project
./mvnw compile

# Run all tests
./mvnw test

# Package the application
./mvnw package

# Run with specific profile
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev

Security Configuration

The service implements comprehensive security measures:

  • CSRF protection disabled (stateless API)
  • Stateless session management
  • Custom JWT security filter
  • Method-level security annotations
  • BCrypt password encoding

Business Logic

User Registration Flow

  1. Input Validation: Validate email format, CPF format, password strength
  2. Uniqueness Check: Verify email and CPF are not already registered
  3. Password Encryption: Hash password using BCrypt
  4. User Creation: Save user with default USER role
  5. Response: Return user data without sensitive information

Authentication Flow

  1. Credential Validation: Verify email and password
  2. User Authentication: Use Spring Security authentication manager
  3. Token Generation: Create JWT token with user email as subject
  4. Response: Return user data and JWT token

Authorization Flow

  1. Token Extraction: Extract JWT from Authorization header
  2. Token Validation: Verify token signature and expiration
  3. User Loading: Load user details from database
  4. Context Setting: Set authentication context for request
  5. Access Control: Apply method-level security rules

Soft Delete Implementation

  • Users are never physically deleted from the database
  • A deleted flag is used to mark users as inactive
  • Deleted users are excluded from regular queries
  • This approach maintains referential integrity and audit trails

Error Handling

The service provides comprehensive error handling for:

  • Invalid email or CPF format
  • Duplicate email or CPF during registration
  • Authentication failures
  • Authorization denial
  • User not found scenarios
  • Token generation and validation errors
  • External service communication errors

Changelog

Version 0.0.1-SNAPSHOT

  • Initial release
  • User registration and authentication
  • JWT token-based authentication
  • Role-based access control
  • Integration with Event and Ticket services
  • Soft delete functionality
  • Comprehensive validation
  • API documentation with Swagger
  • Method-level security
  • Test coverage for core functionality

About

Um serviço para gerenciamento de usuarios, utilizando Java 17, Spring Boot, MongoDB, OpenFeign e autenticação por JWT

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages