Skip to content
/ be0.go Public template

πŸš€ A robust Go-based backend service with advanced authentication and permission systems.

Notifications You must be signed in to change notification settings

theboringhumane/be0.go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🐦 be0 Backend

πŸš€ A robust Go-based backend service with advanced authentication and permission systems.

✨ Features

πŸ” Authentication System

  • 🎯 JWT-based authentication with refresh tokens
  • πŸ‘₯ Role-based access control (RBAC)
  • πŸ”‘ Password reset functionality with time-limited codes
  • πŸ‘‘ Super admin creation on first run

πŸ›‘οΈ Permission System

  • πŸ“Š Granular resource-based permissions
  • πŸ—οΈ Module-based organization
  • πŸ‘€ Role-based default permissions
  • 🌟 Support for wildcard permissions (e.g., "teams:*")

🎯 Supported Modules

1. 🏒 Team Management

  • 🌐 Multi-team support
  • βœ‰οΈ Team invitations
  • βš™οΈ Team settings

2. πŸ‘€ User Management

  • πŸ‘‘ User roles (Super Admin, Admin, Member)
  • πŸ”‘ Permission management
  • πŸ‘€ Profile management

🚌 Event Bus System

  • 🎯 Decoupled service communication
  • ⚑ Asynchronous event handling
  • πŸ”Œ Service hooks integration
  • πŸ›‘οΈ Panic recovery in event handlers

Event Flow Architecture

sequenceDiagram
    participant M as Models
    participant E as Event Bus
    participant S as Services
    participant H as Hooks
    
    M->>E: Emit Event
    activate E
    E->>S: Notify Service
    E->>H: Trigger Hooks
    S-->>E: Process Event
    H-->>E: Execute Hook
    deactivate E
Loading

Available Events

Event Name Description Payload
user.registered Triggered on new registration UserData
team.created Triggered when a new team is created TeamData

Example Usage

// Register event handler
events.On("user.created", func(data interface{}) {
    // Handle email sent event
})

// Emit event
events.Emit("user.created", emailData)

πŸš€ Getting Started

πŸ“‹ Prerequisites

  • πŸ”§ Go 1.21 or higher
  • πŸ—„οΈ PostgreSQL 17 or higher
  • ⚑ Redis (for rate limiting and caching)

πŸ”§ Environment Variables

# πŸ–₯️ Server Configuration
SERVER_HOST=localhost
SERVER_PORT=8080

# πŸ—„οΈ Database Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=kori_user
POSTGRES_PASSWORD=kori_password
POSTGRES_DB=kori
POSTGRES_SSLMODE=disable

# πŸ”’ JWT Configuration
JWT_SECRET=your_secure_jwt_secret

# πŸ“ Storage Configuration
STORAGE_PROVIDER=local
STORAGE_BASE_PATH=./storage

# βš™οΈ Worker Configuration
WORKER_CONCURRENCY=5
WORKER_QUEUE_SIZE=100

# πŸ”„ Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=kori_password
REDIS_DB=0

# πŸ‘‘ Super Admin Configuration (First Run)
SUPERADMIN_EMAIL=[email protected]
SUPERADMIN_PASSWORD=secure_password
SUPERADMIN_NAME=Admin

πŸ“₯ Installation

  1. Clone the repository:
git clone https://github.com/theboringhumane/be0.go.git
cd be0.go
  1. Install dependencies:
go mod download
  1. Set up the environment:
cp .env.example .env
# Edit .env with your configuration
  1. Run migrations:
go run cmd/migrate/main.go
  1. Start the server:
go run cmd/server/main.go

πŸ“š API Documentation

The API is documented using Swagger/OpenAPI. Access the documentation at:

http://localhost:8080/swagger/index.html

πŸ” Authentication

πŸ“ Registration

POST /api/v1/auth/register
{
    "email": "[email protected]",
    "password": "secure_password",
    "first_name": "John",
    "last_name": "Doe"
}

πŸ”‘ Login

POST /api/v1/auth/login
{
    "email": "[email protected]",
    "password": "secure_password"
}

πŸ”„ Password Reset

POST /api/v1/auth/password-reset
{
    "email": "[email protected]"
}

πŸ”’ Authentication System Architecture

The authentication system supports both traditional email/password authentication and Google OAuth, integrated with JWT-based session management.

graph TD
    subgraph "Traditional Email/Password Authentication"
        A[User Registration/Login] -->|Email & Password| B{Exists?}
        B -->|No - Register| C[Create Team & User]
        C --> D[Assign Default Permissions]
        B -->|Yes - Login| E[Validate Password]
        D --> F[Generate Tokens]
        E -->|Valid| F
        E -->|Invalid| G[Return Error]
        F --> H[Create Auth Transaction]
        H --> I[Return JWT & Refresh Token]
    end

    subgraph "Google OAuth Authentication"
        J[Google Sign-In] -->|ID Token| K[Verify with Firebase]
        K -->|Valid| L{User Exists?}
        L -->|No| M[Create Team & User]
        M --> N[Assign Default Permissions]
        L -->|Yes| O[Update Provider Data]
        N --> P[Generate Tokens]
        O --> P
        P --> Q[Create Auth Transaction]
        Q --> R[Return JWT & Refresh Token]
    end

    subgraph "JWT Token Flow"
        S[Protected API Request] -->|JWT Token| T[Auth Middleware]
        T -->|Validate| U{Token Valid?}
        U -->|Yes| V[Extract Claims]
        V --> W[Set Context]
        W --> X[Continue to Handler]
        U -->|No| Y[Return 401]
    end

    subgraph "Token Refresh Flow"
        Z[Refresh Token Request] -->|Refresh Token| AA{Valid?}
        AA -->|Yes| AB[Get User]
        AB --> AC[Generate New Access Token]
        AC --> AD[Update Auth Transaction]
        AD --> AE[Return New Access Token]
        AA -->|No| AF[Return 401]
    end

    subgraph "Password Reset Flow"
        AG[Reset Request] -->|Email| AH[Generate Reset Code]
        AH --> AI[Store Reset Code]
        AI --> AJ[Send Reset Email]
        AK[Reset Verification] -->|Code & New Password| AL{Valid Code?}
        AL -->|Yes| AM[Update Password]
        AM --> AN[Mark Code Used]
        AL -->|No| AO[Return Error]
    end

    subgraph "Team Invite Flow"
        AP[Team Invite] -->|Email & Role| AQ[Generate Invite Code]
        AQ --> AR[Store Invite]
        AR --> AS[Send Invite Email]
        AT[Accept Invite] -->|Code & Password| AU{Valid Invite?}
        AU -->|Yes| AV[Create User]
        AV --> AW[Assign Team & Role]
        AU -->|No| AX[Return Error]
    end
Loading

Key Components:

  1. πŸ” Authentication Methods

    • πŸ“§ Traditional Email/Password
    • πŸ”‘ Google OAuth via Firebase
    • πŸ“¨ Team Invitations
  2. 🎟️ Token Management

    • πŸ”’ JWT Access Tokens (24h validity)
    • πŸ”„ Refresh Tokens (7 days validity)
    • πŸ“ Auth Transaction Tracking
  3. πŸ‘₯ User Management

    • 🏒 Automatic Team Creation
    • πŸ‘‘ Role Assignment
    • πŸ”‘ Permission Management
  4. πŸ”’ Security Features

    • πŸ” Bcrypt Password Hashing
    • ⏰ Time-Limited Reset Codes
    • πŸ” Firebase Token Verification
    • πŸ“Š Transaction-based Operations
  5. 🀝 Integration Points

    • πŸ”Œ Firebase Authentication
    • πŸ“¨ Email Service for Notifications
    • πŸ“ Event System for Tracking

Authentication Endpoints:

# Traditional Authentication
POST /api/v1/auth/register     # User Registration
POST /api/v1/auth/login        # User Login
POST /api/v1/auth/refresh      # Token Refresh

# Google OAuth
POST /api/v1/auth/google       # Google Sign-In

# Password Management
POST /api/v1/auth/password-reset         # Request Reset
POST /api/v1/auth/password-reset/verify  # Verify Reset

# Team Management
POST /api/v1/auth/invite       # Send Team Invite
POST /api/v1/auth/accept/:code # Accept Invite

πŸ›‘οΈ Security Features

  1. ⚑ Rate Limiting

    • πŸ”’ Request rate limiting per IP
    • πŸ”‘ API key rate limiting
    • βš™οΈ Configurable limits
  2. πŸ”’ JWT Security

    • ⏱️ Short-lived access tokens (24 hours)
    • πŸ”„ Refresh token support (7 days)
    • 🎯 Permission claims in tokens
  3. πŸ” Password Security

    • πŸ”’ Bcrypt password hashing
    • βœ… Minimum password requirements
    • πŸ›‘οΈ Secure password reset flow
  4. πŸ”’ API Security

    • 🌐 CORS protection
    • πŸ“¦ Request size limiting
    • πŸ›‘οΈ Secure headers
    • πŸ—œοΈ GZIP compression

πŸ‘¨β€πŸ’» Development

πŸ“ Project Structure

πŸ“¦ be0.go
 ┣ πŸ“‚ cmd                     # Application entry points
 ┣ πŸ“‚ internal               
 ┃ ┣ πŸ“‚ api                  # API layer
 ┃ ┃ ┣ πŸ“‚ middleware         # Custom middlewares
 ┃ ┃ ┣ πŸ“‚ validator          # Request validators
 ┃ ┃ β”— πŸ“œ server.go          # Server setup
 ┃ ┣ πŸ“‚ config               # Configuration
 ┃ ┣ πŸ“‚ events               # Event bus system
 ┃ ┣ πŸ“‚ handlers             # Request handlers
 ┃ ┣ πŸ“‚ models               # Database models
 ┃ ┣ πŸ“‚ routes               # Route definitions
 ┃ ┣ πŸ“‚ services             # Business logic
 ┃ β”— πŸ“‚ utils                # Utility functions
 ┣ πŸ“‚ migrations             # Database migrations
 β”— πŸ“‚ storage                # Local storage

✨ Adding New Features

  1. πŸ“¦ New Resource

    • πŸ“ Add model in internal/models/
    • πŸ”‘ Add permissions in internal/models/seed.go
    • 🎯 Create handler in internal/handlers/
    • πŸ”Œ Add routes in internal/routes/
  2. πŸ”‘ New Permission

    • πŸ“ Add resource in defaultResources
    • πŸ‘₯ Add permissions in rolePermissions
    • πŸ”„ Run server to auto-seed

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

πŸš€ A robust Go-based backend service with advanced authentication and permission systems.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages