Skip to content

A professional, secure authentication system built with Go, designed for fintech applications with enterprise-grade security features.

Notifications You must be signed in to change notification settings

shariaralphabyte/Auth_Backend_Using_Go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Fintech Authentication System

A professional, secure authentication system built with Go, designed for fintech applications with enterprise-grade security features.

πŸš€ Features

Security Features

  • JWT Access & Refresh Tokens with short expiry times
  • Password Hashing using bcrypt
  • Rate Limiting (100 requests/minute per IP)
  • Account Lockout after 5 failed login attempts
  • Token Revocation system for compromised accounts
  • Audit Logging for all security events
  • Input Validation and sanitization
  • CORS Protection with configurable origins
  • Security Headers (XSS, CSRF, etc.)

Role-Based Access Control

  • Admin Role (01): Full system access
  • User Role (02): Limited access to personal data
  • Granular Permissions for different endpoints

Advanced Features

  • Account Status Management (active/inactive/suspended)
  • Password Strength Validation
  • Email Format Validation
  • Comprehensive Error Handling
  • Professional Logging System

πŸ“ Project Structure

fintech-auth/
β”œβ”€β”€ main.go                 # Application entry point
β”œβ”€β”€ config/
β”‚   └── config.go          # Configuration management
β”œβ”€β”€ database/
β”‚   └── database.go        # Database initialization
β”œβ”€β”€ models/
β”‚   └── user.go           # User model and repository
β”œβ”€β”€ handlers/
β”‚   β”œβ”€β”€ auth.go           # Authentication handlers
β”‚   └── admin.go          # Admin-only handlers
β”œβ”€β”€ middleware/
β”‚   └── auth.go           # Authentication & security middleware
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ validator.go      # Input validation utilities
β”‚   └── token.go          # JWT token utilities
β”œβ”€β”€ go.mod                # Go dependencies
β”œβ”€β”€ Postman_Collection.json # API testing collection
└── README.md             # This file

πŸ› οΈ Setup Instructions

Prerequisites

  • Go 1.21 or higher
  • SQLite3 (included with go-sqlite3 driver)

Installation

  1. Clone/Create Project
mkdir fintech-auth
cd fintech-auth
  1. Initialize Go Module
go mod init fintech-auth
  1. Install Dependencies
go get github.com/golang-jwt/jwt/v5
go get github.com/gorilla/mux
go get github.com/mattn/go-sqlite3
go get golang.org/x/crypto
  1. Create Directory Structure
mkdir -p config database models handlers middleware utils
  1. Copy Source Files Copy all the provided source files to their respective directories.

  2. Run the Application

go run main.go

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

Environment Variables (Optional)

export PORT=8080
export DATABASE_URL=./fintech_auth.db
export JWT_SECRET=your-super-secret-jwt-key-change-in-production
export REFRESH_SECRET=your-super-secret-refresh-key-change-in-production
export ENVIRONMENT=development

πŸ” Default Admin Account

⚠️ IMPORTANT: Change these credentials immediately after first login!

  • Email: admin@fintech.com
  • Password: admin123
  • Role: 01 (Admin)

πŸ“‘ API Endpoints

Authentication Endpoints

Register User

POST /api/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "role": "02"
}

Login

POST /api/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "SecurePass123!"
}

Refresh Token

POST /api/refresh
Content-Type: application/json

{
  "refresh_token": "your_refresh_token_here"
}

Protected Endpoints (Require Authentication)

Get Profile

GET /api/protected/profile
Authorization: Bearer <access_token>

Change Password

POST /api/protected/change-password
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "current_password": "CurrentPass123!",
  "new_password": "NewSecurePass123!"
}

Admin Endpoints (Admin Role Required)

Get All Users

GET /api/admin/users
Authorization: Bearer <admin_access_token>

Revoke User Token

POST /api/admin/revoke-token
Authorization: Bearer <admin_access_token>
Content-Type: application/json

{
  "user_email": "user@example.com",
  "reason": "Account compromised"
}

Update User Status

PUT /api/admin/user/{user_id}/status
Authorization: Bearer <admin_access_token>
Content-Type: application/json

{
  "status": "suspended",
  "reason": "Suspicious activity"
}

Get Audit Logs

GET /api/admin/audit-logs?limit=100
Authorization: Bearer <admin_access_token>

πŸ§ͺ Testing with Postman

  1. Import Collection: Import the provided Postman_Collection.json
  2. Set Base URL: Update {{baseUrl}} to http://localhost:8080/api
  3. Test Sequence:
    • Register a new user
    • Login to get tokens
    • Test protected endpoints
    • Login as admin
    • Test admin endpoints

Test Cases Included

  • βœ… Valid registration and login
  • βœ… Invalid email format validation
  • βœ… Weak password validation
  • βœ… Invalid JSON handling
  • βœ… Unauthorized access attempts
  • βœ… Role-based access control
  • βœ… Token refresh functionality
  • βœ… Admin token revocation
  • βœ… User status management

πŸ”’ Security Best Practices Implemented

Password Security

  • Minimum 8 characters
  • Must contain uppercase, lowercase, numbers, and special characters
  • Protection against common passwords
  • Bcrypt hashing with default cost

Token Security

  • Short-lived access tokens (15 minutes)
  • Longer-lived refresh tokens (7 days)
  • Unique token IDs for tracking
  • Token revocation capability
  • Proper token validation

Account Security

  • Account lockout after failed attempts
  • Audit logging for all actions
  • Rate limiting per IP address
  • Secure password change process

API Security

  • Input validation and sanitization
  • Proper error handling
  • CORS protection
  • Security headers
  • Role-based authorization

πŸ“Š Database Schema

Users Table

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT '02',
    status TEXT NOT NULL DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_login DATETIME,
    failed_login_attempts INTEGER DEFAULT 0,
    locked_until DATETIME
);

Revoked Tokens Table

CREATE TABLE revoked_tokens (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    token_id TEXT UNIQUE NOT NULL,
    user_email TEXT NOT NULL,
    revoked_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    reason TEXT
);

Audit Logs Table

CREATE TABLE audit_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_email TEXT,
    action TEXT NOT NULL,
    details TEXT,
    ip_address TEXT,
    user_agent TEXT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

πŸš€ Production Deployment

Security Checklist

  • Change default admin credentials
  • Set strong JWT secrets
  • Configure HTTPS
  • Set up proper CORS origins
  • Configure rate limiting
  • Set up log monitoring
  • Regular security audits
  • Database backups

Environment Configuration

# Production environment
export ENVIRONMENT=production
export JWT_SECRET=your-256-bit-secret-key
export REFRESH_SECRET=your-256-bit-refresh-secret
export DATABASE_URL=/secure/path/to/database.db

πŸ“ˆ Monitoring and Maintenance

Audit Log Actions

  • USER_REGISTERED - New user registration
  • LOGIN_SUCCESS - Successful login
  • LOGIN_FAILED - Failed login attempt
  • TOKEN_REFRESHED - Access token refreshed
  • PASSWORD_CHANGED - Password change
  • TOKEN_REVOKED - Token revoked by admin
  • STATUS_CHANGED - User status changed
  • ADMIN_* - Admin actions

Regular Maintenance

  • Monitor failed login attempts
  • Review audit logs regularly
  • Clean up old revoked tokens
  • Monitor rate limiting effectiveness
  • Update dependencies regularly

🀝 Contributing

  1. Follow Go best practices
  2. Add comprehensive tests
  3. Update documentation
  4. Security-first approach
  5. Performance considerations

πŸ“„ License

This project is designed for educational and professional use. Ensure compliance with your organization's security policies and local regulations when deploying in production.

About

A professional, secure authentication system built with Go, designed for fintech applications with enterprise-grade security features.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages