Skip to content

Tanathorn-Rin/go-authentication-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Authentication System with Go

A robust REST API authentication system built with Go, Gin framework, MongoDB, and JWT tokens. This project provides user registration, login, and role-based access control (RBAC) features.

πŸš€ Features

  • βœ… User Registration & Login
  • βœ… JWT Authentication (Access & Refresh Tokens)
  • βœ… Password Hashing with bcrypt
  • βœ… Role-Based Access Control (ADMIN/USER)
  • βœ… MongoDB Integration
  • βœ… Input Validation
  • βœ… Protected Routes with Middleware

πŸ“‹ Prerequisites

Before running this project, make sure you have the following installed:

πŸ› οΈ Installation

1. Clone the Repository

git clone https://github.com/Tanathorn-Rin/go-authentication-system.git
cd go-authentication-system

2. Install Dependencies

go mod download

3. Set Up MongoDB

Option A: Using Docker (Recommended for Quick Start)

docker run -d -p 27017:27017 --name mongodb-auth mongo:latest

Option B: Install MongoDB Locally (macOS)

brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

Option C: Using MongoDB Atlas (Cloud)

  1. Create a free account at MongoDB Atlas
  2. Create a cluster and get your connection string
  3. Update the connection string in config/database.go

4. Run the Application

go run main.go

The server will start on http://localhost:8080

πŸ“š API Endpoints

Public Routes

1. User Signup

POST /signup
Content-Type: application/json

{
  "first_name": "John",
  "last_name": "Doe",
  "email": "[email protected]",
  "password": "securepassword123",
  "phone": "1234567890",
  "role": "USER"
}

Response:

{
  "message": "User created successfully"
}

2. User Login

POST /login
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "securepassword123"
}

Response:

{
  "user": { ... },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Protected Routes (Requires Authentication)

3. Get All Users (ADMIN only)

GET /users
Authorization: Bearer <your_jwt_token>

Response:

[
  {
    "user_id": "...",
    "first_name": "John",
    "last_name": "Doe",
    "email": "[email protected]",
    "role": "USER",
    ...
  }
]

4. Get User by ID

GET /users/:id
Authorization: Bearer <your_jwt_token>

Note: Regular users can only access their own profile. ADMIN can access any user profile.

Response:

{
  "user_id": "...",
  "first_name": "John",
  "last_name": "Doe",
  "email": "[email protected]",
  "role": "USER",
  ...
}

πŸ” Authentication

This API uses JWT (JSON Web Tokens) for authentication. After logging in, include the token in the Authorization header:

Authorization: Bearer <your_jwt_token>

Token Expiration

  • Access Token: 24 hours
  • Refresh Token: 7 days

πŸ—οΈ Project Structure

Authentication-system/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ auth-key.go        # JWT key generation
β”‚   └── database.go        # MongoDB connection
β”œβ”€β”€ controllers/
β”‚   └── userControllers.go # User-related handlers
β”œβ”€β”€ helpers/
β”‚   └── token.go           # JWT & password utilities
β”œβ”€β”€ middleware/
β”‚   └── auth.go            # JWT authentication middleware
β”œβ”€β”€ models/
β”‚   └── user.go            # User model/schema
β”œβ”€β”€ routes/
β”‚   └── routes.go          # Route definitions
β”œβ”€β”€ main.go                # Application entry point
β”œβ”€β”€ go.mod                 # Go module dependencies
└── go.sum                 # Dependency checksums

πŸ”§ Configuration

Database

Update MongoDB connection string in config/database.go:

clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

Database Name

The default database name is usersdb. Change it in config/database.go if needed:

return Client.Database("usersdb").Collection(collectionName)

Server Port

The server runs on port 8080 by default. Change it in main.go:

port := "8080"

πŸ“¦ Dependencies

πŸ§ͺ Testing the API

Using cURL

Signup:

curl -X POST http://localhost:8080/signup \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Jane",
    "last_name": "Smith",
    "email": "[email protected]",
    "password": "password123",
    "phone": "9876543210",
    "role": "USER"
  }'

Login:

curl -X POST http://localhost:8080/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "[email protected]",
    "password": "password123"
  }'

Get Users (with token):

curl -X GET http://localhost:8080/users \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Using Postman

  1. Import the endpoints listed above
  2. For protected routes, add the token in the Authorization tab:
    • Type: Bearer Token
    • Token: Paste your JWT token

πŸ›‘οΈ Security Features

  • Password Hashing: Passwords are hashed using bcrypt before storage
  • JWT Tokens: Secure token-based authentication
  • Role-Based Access Control: Different permissions for ADMIN and USER roles
  • Input Validation: All inputs are validated before processing
  • Secure Headers: Authorization headers for protected routes

πŸ› Troubleshooting

MongoDB Connection Error

server selection error: server selection timeout

Solution: Make sure MongoDB is running:

# If using Docker
docker start mongodb-auth

# If using Homebrew
brew services start mongodb-community

Port Already in Use

bind: address already in use

Solution: Change the port in main.go or kill the process using port 8080:

lsof -ti:8080 | xargs kill -9

Module Errors

no required module provides package

Solution: Run:

go mod tidy
go mod download

πŸ“ License

This project is open source and available under the MIT License.

πŸ‘€ Author

Tanathorn Rin

🀝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page.

⭐ Show your support

Give a ⭐️ if this project helped you!


Note: This is a learning project. For production use, consider adding:

  • Environment variables for sensitive data
  • HTTPS/TLS support
  • Rate limiting
  • Email verification
  • Password reset functionality
  • Refresh token rotation
  • Better error handling
  • Unit tests
  • API documentation (Swagger/OpenAPI)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages