{"id":29480941,"url":"https://github.com/hermantrym/go-firebase-api","last_synced_at":"2026-05-03T21:34:51.247Z","repository":{"id":304535176,"uuid":"1019022149","full_name":"hermantrym/go-firebase-api","owner":"hermantrym","description":"A production-ready, modular RESTful API built with Go (Golang) and Firebase. This project demonstrates clean architecture principles, secure JWT authentication, type-safe Role-Based Access Control (RBAC), input validation, and structured error handling using the Gin framework.","archived":false,"fork":false,"pushed_at":"2025-07-13T17:22:10.000Z","size":33,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-13T19:22:38.658Z","etag":null,"topics":["backend","backend-api","clean-architecture","firebase","firestore","gin-framework","gin-gonic","go","golang","jwt","jwt-authentication","modular-architecture","production","rbac","rbac-authorization","rbac-roles","rest-api","restful-api"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hermantrym.png","metadata":{"files":{"readme":"README.MD","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-13T15:11:23.000Z","updated_at":"2025-07-13T17:26:09.000Z","dependencies_parsed_at":"2025-07-13T19:24:35.592Z","dependency_job_id":"480ae036-3326-4296-891c-7575cfe80414","html_url":"https://github.com/hermantrym/go-firebase-api","commit_stats":null,"previous_names":["hermantrym/go-firebase-api"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/hermantrym/go-firebase-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermantrym%2Fgo-firebase-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermantrym%2Fgo-firebase-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermantrym%2Fgo-firebase-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermantrym%2Fgo-firebase-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hermantrym","download_url":"https://codeload.github.com/hermantrym/go-firebase-api/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hermantrym%2Fgo-firebase-api/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32586187,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-03T06:36:36.687Z","status":"ssl_error","status_checked_at":"2026-05-03T06:36:09.306Z","response_time":103,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","backend-api","clean-architecture","firebase","firestore","gin-framework","gin-gonic","go","golang","jwt","jwt-authentication","modular-architecture","production","rbac","rbac-authorization","rbac-roles","rest-api","restful-api"],"created_at":"2025-07-14T23:55:10.186Z","updated_at":"2026-05-03T21:34:51.225Z","avatar_url":"https://github.com/hermantrym.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Modular REST API with Go \u0026 Firebase\n\n[![Go Version](https://img.shields.io/badge/go-1.18+-blue.svg)](https://golang.org)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA robust and modular RESTful API built with Golang, using Firebase (Firestore) for data persistence. This project demonstrates professional backend development practices including a clean, layered architecture, JWT authentication, role-based authorization, input validation, and structured error handling.\n\n---\n\n## Features\n\n-   **Modular Architecture**: Clean separation of concerns using a layered structure (Handler, Service, Repository).\n-   **JWT Authentication**: Secure endpoints using a JWT-based authentication middleware.\n-   **Role-Based Authorization (RBAC)**: Securely restricts access based on user roles. Features separate endpoints for public registration and admin-level user management.\n-   **Configuration Management**: Securely manages configuration and secrets using environment variables (`.env` file).\n-   **Input Validation**: Strong server-side validation of request data using `go-playground/validator`.\n-   **Structured Error Handling**: A custom error handling system to provide clear, consistent error responses for different scenarios.\n-   **Firebase Integration**: Uses the Firebase Admin SDK for Go to interact with Cloud Firestore.\n\n---\n\n## Project Structure\n\nThe project follows a standard layered architecture to ensure maintainability and scalability.\n\n```\n.\n├── cmd/\n│   └── api/\n│       └── main.go           # Application entry point\n├── internal/\n│   ├── apierror/\n│   │   └── apierror.go       # Custom error types\n│   ├── auth/\n│   │   └── auth.go           # JWT generation and middleware\n│   ├── config/\n│   │   └── firebase.go       # Firebase initialization\n│   ├── handler/\n│   │   ├── auth_handler.go   # HTTP handler for authentication\n│   │   └── user_handler.go   # HTTP handler for user resources\n│   ├── model/\n│   │   └── user.go           # User data structure\n│   ├── repository/\n│   │   └── user_repository.go# Data access layer (Firestore)\n│   ├── role/\n│   │   └── role.go           # Role constants and logic\n│   └── service/\n│       └── user_service.go   # Business logic layer\n├── .env                        # Local environment variables (gitignored)\n├── .gitignore\n├── go.mod\n├── go.sum\n└── serviceAccountKey.json      # Firebase credentials (gitignored)\n```\n\n---\n\n## Prerequisites\n\n-   [Go](https://golang.org/dl/) version 1.18 or higher.\n-   A [Google Firebase](https://console.firebase.google.com/) project with Firestore enabled.\n\n---\n\n## Installation \u0026 Setup\n\nFollow these steps to get the project running on your local machine.\n\n1.  **Clone the repository:**\n    ```bash\n    git clone https://github.com/hermantrym/go-firebase-api.git\n    cd go-firebase-api\n    ```\n\n2.  **Set up Firebase Credentials:**\n    -   Go to your Firebase project settings \u003e Service Accounts.\n    -   Click **\"Generate new private key\"** to download a JSON file.\n    -   Rename the downloaded file to `serviceAccountKey.json` and place it in the root directory of the project.\n\n3.  **Configure Environment Variables:**\n    -   Create a new file named `.env` in the root directory. You can copy the `.env.example` file if it exists.\n    -   Open the `.env` file and set the required variables. See the [Environment Variables](#environment-variables) section below for details.\n\n4.  **Install Dependencies:**\n    ```bash\n    go mod tidy\n    ```\n\n5.  **Run the Application:**\n    ```bash\n    go run ./cmd/api/main.go\n    ```\n    The server will start on `http://localhost:8080`.\n\n---\n\n## API Endpoints\n\n### Authentication\n\n#### 1. Login to Get a Token\n\n-   **Method**: `POST`\n-   **Path**: `/login`\n-   **Description**: Authenticates a user based on their email and returns a JWT if successful.\n-   **Access**: Public\n\n**Request Body:**\n```json\n{\n    \"email\": \"user@example.com\"\n}\n```\n\n**Success Response (200 OK):**\n```json\n{\n    \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n}\n```\n\n### User Management\n\n#### 1. Register a New User\n\n-   **Method**: `POST`\n-   **Path**: `/users`\n-   **Description**: Creates a new user with a default \"user\" role. Any `role` field provided in the request body will be ignored for security reasons.\n-   **Access**: Public\n\n**Request Body:**\n```json\n{\n  \"name\": \"Budi Santoso\",\n  \"email\": \"budi.santoso@example.com\"\n}\n```\n\n**Success Response (201 Created):**\n```json\n{\n  \"id\": \"some-generated-id\",\n  \"name\": \"Budi Santoso\",\n  \"email\": \"budi.santoso@example.com\",\n  \"role\": \"user\"\n}\n```\n\n#### 2. Get User Details by ID\n\n-   **Method**: `GET`\n-   **Path**: `/users/:id`\n-   **Description**: Retrieves the details of a specific user.\n-   **Access**: **Protected** (Requires a valid JWT for any authenticated user)\n\n**Example Request:**\n```bash\nTOKEN=\"\u003cyour-jwt\u003e\"\nUSER_ID=\"\u003cuser-id-to-fetch\u003e\"\n\ncurl -H \"Authorization: Bearer $TOKEN\" http://localhost:8080/users/$USER_ID\n```\n\n**Success Response (200 OK):**\n```json\n{\n    \"id\": \"some-user-id\",\n    \"name\": \"Budi Santoso\",\n    \"email\": \"budi.santoso@example.com\",\n    \"role\": \"user\"\n}\n```\n\n### Admin Endpoints\n\n#### 1. Get All Users\n\n-   **Method**: `GET`\n-   **Path**: `/admin/users`\n-   **Description**: Retrieves a list of all users in the system.\n-   **Access**: **Protected (Admin Only)**\n\n**Example Request:**\n```bash\n# Ensure this token belongs to a user with the 'admin' role\nADMIN_TOKEN=\"\u003cyour-admin-jwt\u003e\"\n\ncurl -H \"Authorization: Bearer $ADMIN_TOKEN\" http://localhost:8080/admin/users\n```\n\n**Success Response (200 OK):**\n```json\n[\n    {\n        \"id\": \"user-id-1\",\n        \"name\": \"Admin User\",\n        \"email\": \"admin@example.com\",\n        \"role\": \"admin\"\n    },\n    {\n        \"id\": \"user-id-2\",\n        \"name\": \"Budi Santoso\",\n        \"email\": \"budi.santoso@example.com\",\n        \"role\": \"user\"\n    }\n]\n```\n\n#### 2. Create a New User (Admin)\n\n-   **Method**: `POST`\n-   **Path**: `/admin/users`\n-   **Description**: Allows an admin to create a new user with a specific role. If the `role` is omitted, it defaults to \"user\".\n-   **Access**: **Protected (Admin Only)**\n\n**Request Body:**\n```json\n{\n    \"name\": \"Admin Baru\",\n    \"email\": \"admin.baru@example.com\",\n    \"role\": \"admin\"\n}\n```\n\n**Example Request:**\n```bash\nADMIN_TOKEN=\"\u003cyour-admin-jwt\u003e\"\n\ncurl -X POST -H \"Authorization: Bearer $ADMIN_TOKEN\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\"name\": \"Admin Baru\", \"email\": \"admin.baru@example.com\", \"role\": \"admin\"}' \\\nhttp://localhost:8080/admin/users\n```\n\n**Success Response (200 OK):**\n```json\n{\n    \"id\": \"another-generated-id\",\n    \"name\": \"Admin Baru\",\n    \"email\": \"admin.baru@example.com\",\n    \"role\": \"admin\"\n}\n```\n\n---\n\n## Environment Variables\n\nThese variables must be defined in a `.env` file in the project root.\n\n| Variable                            | Description                                                      | Example                               |\n|-------------------------------------|------------------------------------------------------------------|---------------------------------------|\n| `FIREBASE_SERVICE_ACCOUNT_KEY_PATH` | The file path to your Firebase service account JSON credentials. | `./serviceAccountKey.json`            |\n| `JWT_SECRET_KEY`                    | A long, random, and secret string used to sign and verify JWTs.  | `a-very-strong-and-random-secret-key` |\n\n---\n\n## Key Technologies Used\n\n-   **Go**: The core programming language.\n-   **Gin**: A high-performance HTTP web framework.\n-   **Firebase Admin SDK**: For connecting to Cloud Firestore.\n-   **JWT-Go**: For generating and validating JSON Web Tokens.\n-   **Go-Playground Validator**: For request data validation.\n\n---\n\n## Future Improvements\n\n-   [x] **Role-Based Access Control (RBAC)**: Restricts access to specific endpoints based on user roles.\n-   [ ] **Password Hashing**: Implement `bcrypt` for secure password storage and authentication.\n-   [ ] **Unit \u0026 Integration Tests**: Write comprehensive tests for all layers of the application.\n-   [ ] **Structured Logging**: Integrate a logging library like `Logrus` or `Zap` for better log management.\n-   [ ] **Dockerize the Application**: Create a `Dockerfile` to containerize the application for easier deployment.\n\n---\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE.md) file for details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhermantrym%2Fgo-firebase-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhermantrym%2Fgo-firebase-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhermantrym%2Fgo-firebase-api/lists"}