Authentication microservice for the Zyotra VPS deployment platform.
A high-performance authentication service built with Bun, Elysia.js, Drizzle ORM, and PostgreSQL. This microservice handles user registration, login, JWT-based authentication, and refresh token management for the Zyotra ecosystem.
- User Registration & Login - Secure user authentication with bcrypt password hashing
- JWT Authentication - Access tokens (15 min) and refresh tokens (15 days)
- Session Management - Persistent refresh token storage with automatic cleanup
- Protected Routes - Middleware-based route protection
- Database Migrations - Drizzle ORM for type-safe database operations
- High Performance - Built on Bun runtime for maximum speed
├── src/
│ ├── index.ts # Application entry point
│ ├── routes.ts # Route definitions
│ │
│ ├── controllers/
│ │ └── auth/
│ │ ├── loginController.ts # Handles user login
│ │ └── registerController.ts # Handles user registration
│ │
│ ├── db/
│ │ ├── client.ts # Database connection
│ │ └── schema.ts # Database schema (users, login_sessions)
│ │
│ ├── jwt/
│ │ ├── generateTokens.ts # Access & refresh token generation
│ │ └── verifyTokens.ts # Token verification logic
│ │
│ ├── middlewares/
│ │ └── checkAuth.ts # Authentication middleware
│ │
│ ├── types/
│ │ └── types.ts # TypeScript type definitions
│ │
│ └── utils/
│ └── hashPassword.ts # Password hashing utility
│
├── drizzle.config.ts # Drizzle ORM configuration
├── tsconfig.json # TypeScript configuration
├── package.json # Dependencies and scripts
└── README.md # This file
Application entry point that:
- Initializes Elysia server
- Loads environment variables
- Registers routes with middleware support
- Applies
checkAuthmiddleware to protected routes - Starts the server on configured PORT
Centralized route configuration defining:
- HTTP method (GET, POST, PUT, DELETE, PATCH)
- Path
- Handler function
- Middleware stack
- Protection status (
isProtected: boolean)
Handles user login:
- Validates email and password
- Compares hashed passwords using bcrypt
- Generates access and refresh tokens
- Returns user ID and tokens on success
Handles user registration:
- Accepts email and password
- Hashes password with bcrypt
- Inserts user into database
- Returns success message
Database connection setup:
- Uses
postgres-jsdriver - Drizzle ORM client initialization
- Connection string from
DATABASE_URLenv variable
Database schema definitions:
users table:
id- Serial primary keyemail- Unique email (varchar 255)password- Hashed password (text)createdAt- Timestamp (default now)updatedAt- Timestamp (default now)
login_sessions table:
id- Serial primary keyuserId- Foreign key to users (cascade delete)refreshToken- Unique token stringcreatedAt- Timestamp (default now)expiresAt- Expiration timestamp
Token generation:
generateAccessToken()- Creates 15-minute JWT access tokensgenerateRefreshToken()- Creates 15-day JWT refresh tokens and stores in DB- Cleans up old refresh tokens for the user
Token verification:
verifyAccessToken()- Validates access token signature and expiryverifyRefreshToken()- Validates refresh token against database and checks expiry
Authentication middleware:
- Extracts token from request body
- Verifies access token
- Attaches user data to request context
- Returns 401 for invalid/missing tokens
- Uses Elysia's
derive()andguard()pattern
Password hashing utility:
- Uses bcryptjs with salt rounds of 10
- Returns hashed password string
TypeScript definitions:
HTTPMethod- HTTP verb typesapiRoute- Route configuration interfaceStatusCode- HTTP status code enum
- Bun v1.0+
- PostgreSQL database
- Clone the repository
git clone <repository-url>
cd zyotra-auth-service- Install dependencies
bun install- Configure environment variables
Create a
.envfile in the root directory:
# Server
PORT=3000
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/zyotra_auth
# JWT Secrets
ACCESS_TOKEN_SECRET=your-access-token-secret-here
REFRESH_TOKEN_SECRET=your-refresh-token-secret-here- Run database migrations
bun run db:generate # Generate migration files
bun run db:migrate # Apply migrations- Start the development server
bun run devThe server will start at http://localhost:3000 (or your configured PORT).
Register a new user
Request Body:
{
"email": "user@example.com",
"password": "securePassword123"
}Response (201):
{
"message": "User registered successfully"
}Authenticate user and receive tokens
Request Body:
{
"email": "user@example.com",
"password": "securePassword123"
}Response (200):
{
"message": "Login successful",
"userId": 1,
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}-
Registration:
- User submits email and password
- Password is hashed with bcrypt
- User record created in database
-
Login:
- User submits credentials
- Password verified against hash
- Access token (15 min) and refresh token (15 days) generated
- Refresh token stored in
login_sessionstable
-
Protected Routes:
- Client sends access token in request body
checkAuthmiddleware verifies token- If valid, request proceeds with user context
- If invalid, returns 401 Unauthorized
-
Token Refresh:
- When access token expires, use refresh token
- Verify refresh token against database
- Issue new access token
bun run dev # Start development server with hot reload
bun run start # Start production server
bun run db:generate # Generate Drizzle migration files
bun run db:migrate # Run database migrations
bun run db:push # Push schema changes to database
bun run db:studio # Open Drizzle Studio (database GUI)- Runtime: Bun - Fast JavaScript runtime
- Framework: Elysia.js - High-performance web framework
- ORM: Drizzle ORM - TypeScript ORM
- Database: PostgreSQL
- Authentication: JWT (jsonwebtoken)
- Password Hashing: bcryptjs
- Language: TypeScript
- Passwords hashed with bcrypt (10 salt rounds)
- JWT tokens with configurable secrets
- Refresh token rotation on new login
- Cascade deletion of sessions on user deletion
- Environment-based configuration
- SQL injection protection via Drizzle ORM
| Variable | Description | Example |
|---|---|---|
PORT |
Server port | 3000 |
DATABASE_URL |
PostgreSQL connection string | postgresql://user:pass@localhost:5432/db |
ACCESS_TOKEN_SECRET |
Secret for access token signing | your-secret-key |
REFRESH_TOKEN_SECRET |
Secret for refresh token signing | your-refresh-secret |
- Add email verification
- Implement password reset flow
- Add OAuth providers (Google, GitHub)
- Rate limiting for auth endpoints
- Redis integration for token blacklisting
- Two-factor authentication (2FA)
- API key authentication for service-to-service communication
This is a microservice for the Zyotra platform. For contribution guidelines, please refer to the main Zyotra repository.
MIT License - see LICENSE file for details
- Zyotra Main Platform - VPS deployment orchestration
- Zyotra API Gateway - Service mesh and routing
- Zyotra Deployment Service - Git-based deployments
Built with ❤️ for the Zyotra ecosystem