Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ashtishad/user-auth-template

A robust and secure user authentication API template built with Go. This project provides essential authentication functionalities including user registration, login, and token refresh. It features JWT-based authentication, secure password hashing, and HttpOnly cookie management. Ideal for quickly bootstrapping authentication systems in Go.
https://github.com/ashtishad/user-auth-template

docker gin go golang postgresql

Last synced: 4 days ago
JSON representation

A robust and secure user authentication API template built with Go. This project provides essential authentication functionalities including user registration, login, and token refresh. It features JWT-based authentication, secure password hashing, and HttpOnly cookie management. Ideal for quickly bootstrapping authentication systems in Go.

Awesome Lists containing this project

README

        

# User-Auth-Template

A robust and secure user authentication API template built with Go. This project provides essential authentication functionalities including user registration, login, and token refresh. It features JWT-based authentication, secure password hashing, and HttpOnly cookie management. Ideal for quickly bootstrapping authentication systems in Go-based web applications or microservices.

Key Features:
- User registration with email validation
- Secure login with JWT token generation
- Token refresh mechanism
- Error handling and appropriate HTTP status codes
- Customizable and easily extendable

Perfect for developers looking to implement a solid authentication foundation in their Go projects.

## Quick Start

1. Clone your new repository locally with ssh `git clone [email protected]:ashtishad/user-auth-template.git`
2. Copy `.env.example` from the `/local-dev` directory to `.env` in the project root.
3. Run `make up` to start the Docker services.
4. Run `make run` to start the application.
5. Run `make watch` for live reload.

## Development Commands

- `make up`: Start Docker services
- `make down`: Stop Docker services
- `make down-data`: Stop Docker services and remove data
- `make build`: Build the application
- `make run`: Run the application
- `make test`: Run tests with race detector
- `make lint`: Run linter (staticcheck)
- `make watch`: Start live reload with Air
- `swag init` : For generating swagger specs after creating new routes.

## Tools/Libraries Used

- [Gin Web Framework](https://github.com/gin-gonic/gin) for HTTP routing and middleware
- [PostgreSQL](https://www.postgresql.org/) database with [pgx](https://github.com/jackc/pgx) for reusable connection pooling
- [golang-jwt](https://github.com/golang-jwt/jwt) for JSON Web Token handling
- [golang-migrate](https://github.com/golang-migrate/migrate) for database migrations
- [swaggo/swag](https://github.com/swaggo/swag) for Swagger API documentation
- [Air](https://github.com/cosmtrek/air) for live reloading during development
- [golangci-lint](https://golangci-lint.run/) for linting, config file is .golangci.yaml
- [slog](https://pkg.go.dev/log/slog) for structured logging
- [godotenv](https://github.com/joho/godotenv) for managing environment variables
- Docker and Docker Compose for containerization
- GitHub Actions for CI/CD (Build, Test, Lint)

## Directory Structure

command
`tree -a -I '.git|.DS_Store|.gitignore|.idea|docs|api-collections'`

```
├── .github
│   └── workflows
│   └── ci.yaml
├── infra
│   ├── docker
│   │   └── init-db.sql
│   ├── postgres
│   │   ├── migrations
│   │   │   ├── 000001_create-users-table.down.sql
│   │   │   └── 000001_create-users-table.up.sql
│   │   ├── postgres_conn.go
│   │   ├── postgres_conn_test.go
│   │   └── postgres_migrations.go
│   └── redis
│   └── sample.md
├── internal
│   ├── auth
│   │   └── jwt.go
│   ├── common
│   │   ├── app_errs.go
│   │   ├── constants.go
│   │   ├── custom_err_messages.go
│   │   ├── slog_config.go
│   │   └── timeouts.go
│   ├── config
│   │   └── config.go
│   ├── domain
│   │   ├── auth.go
│   │   ├── auth_repository.go
│   │   ├── user.go
│   │   └── user_repository.go
│   └── server
│   ├── auth_handlers.go
│   ├── dto.go
│   ├── helpers.go
│   ├── middlewares.go
│   ├── routes.go
│   └── server.go
├── local-dev
│   └── .env_example
├── main.go
├── .golangci.yaml
├── Makefile
├── README.md
├── compose.yaml
├── go.mod
├── go.sum
├── .air.toml
├── .env (place it here)
```

# User Authentication API

This API provides user authentication services including registration, login, and token refresh.

## Base URL

```
{{api_url}} example: 127.0.0.1:8080/api/
```

## Endpoints

### 1. Register

Register a new user.

- **URL**: `/register`
- **Method**: `POST`
- **Body**:
```json
{
"name": "John Doe",
"email": "[email protected]",
"password": "samplepass"
}
```

#### Responses

- **201 Created**: User successfully registered
- Sets `accessToken` cookie (HttpOnly, Secure)
- Returns user details
- **400 Bad Request**: Invalid input
- **409 Conflict**: User already exists
- **500 Internal Server Error**: For internal server errors.

### 2. Login

Authenticate a user.

- **URL**: `/login`
- **Method**: `POST`
- **Body**:
```json
{
"email": "[email protected]",
"password": "samplepass"
}
```

#### Responses

- **200 OK**: Login successful
- Sets `accessToken` cookie (HttpOnly, Secure)
- Returns user details
- **400 Bad Request**: Invalid input
- **401 Unauthorized**: Invalid credentials
- **500 Internal Server Error**: For internal server errors.

### 3. Refresh Token

Refresh the access token.

- **URL**: `/refresh`
- **Method**: `POST`
- **Body**:
```json
{
"userId": "9df78c1a-0ae1-4a1e-981f-e88455da45af"
}
```

#### Responses

- **200 OK**: Token refreshed successfully
- Sets new `accessToken` cookie (HttpOnly, Secure)
- Returns userId
- **404 Not Found**: Refresh token not found
- **500 Internal Server Error**: Unexpected error

## Error Handling

The API returns appropriate HTTP status codes and error messages in the response body:

```json
{
"error": "Error message"
}
```

## Authentication

The API uses JWT tokens for authentication. After successful login or registration, an `accessToken` is set as an HTTP-only, secure cookie.

## Notes

- All successful responses include a `Set-Cookie` header with the `accessToken`.
- The `accessToken` has a max age of 900 seconds (15 minutes).
- Always use HTTPS in production to ensure secure transmission of tokens and credentials.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.