K12 Authentication Microservice
A comprehensive authentication and authorization microservice built with Node.js, TypeScript, Express, and gRPC.
Features
- Dual API Support: Both REST HTTP and gRPC APIs
- JWT Authentication: Secure token-based authentication with HTTP-only cookies
- User Management: Admin-only user creation, updates, and deletion
- Role-Based Access: Admin and SME roles
- Password Management: Secure password hashing with bcrypt
- Avatar Upload: Google Cloud Storage integration
- Secrets Management: HashiCorp Vault integration
- Rate Limiting: Built-in request rate limiting
- Comprehensive Logging: Winston-based logging system
- API Documentation: Interactive Swagger/OpenAPI documentation
Architecture
REST API Endpoints
Public Routes
POST /api/auth/login- User loginPOST /api/auth/refresh-token- Refresh access token
Protected Routes
GET /api/auth/me- Get current userPOST /api/auth/change-password- Change passwordPOST /api/auth/change-avatar- Change avatar
Admin Routes
POST /api/admin/create-user- Create new userGET /api/admin/users- Get all usersGET /api/admin/users/:userId- Get user by IDPUT /api/admin/users/:userId- Update userDELETE /api/admin/users/:userId- Delete userPOST /api/admin/reset-password- Reset user passwordGET /api/admin/stats- Get user statistics
gRPC Services
The service exposes the following gRPC methods:
Authentication Methods
login(email, password)- User loginrefreshToken(refreshToken)- Refresh access tokengetCurrentUser(userId)- Get current user infochangePassword(userId, currentPassword, newPassword)- Change passwordchangeAvatar(userId, avatar)- Change avatar
Admin Methods
createUser(email, name, password, role)- Create new usergetAllUsers()- Get all usersgetUserById(userId)- Get user by IDupdateUser(userId, name, avatar)- Update userdeleteUser(userId)- Delete userresetPassword(userId, newPassword)- Reset passwordgetUserStats()- Get user statistics
Getting Started
Prerequisites
- Node.js 18+
- MongoDB
- HashiCorp Vault (optional for development)
- Google Cloud Storage (for avatar uploads)
Installation
-
Clone the repository
-
Install dependencies:
pnpm install -
Set up environment variables:
cp .env.example .env # Edit .env with your actual values -
Generate gRPC code:
pnpm proto:gen -
Start the service:
# Development npm run dev # Production npm run build npm start
Docker Setup
- Build and run with Docker Compose:
docker-compose up -d
This will start:
- K12 Auth Service (HTTP: 3001, gRPC: 50051)
- MongoDB (27017)
- HashiCorp Vault (8200)
Environment Variables
See .env.example for a complete list of all environment variables.
Quick Setup:
# Copy example file
cp .env.example .env
# Edit with your actual values
nano .env
Required Variables:
MONGODB_URI- MongoDB connection stringJWT_SECRET- Secret key for access tokensJWT_REFRESH_SECRET- Secret key for refresh tokens
Key Configuration Examples:
# GCS Configuration
GCS_BUCKET_NAME=k12-auth-avatars
GCS_PROJECT_ID=your-gcp-project-id
# Avatar Processing (all optional with defaults)
AVATAR_SIZE=512 # Pixels (128-2048, default: 512)
AVATAR_QUALITY=80 # Quality (1-100, default: 80)
AVATAR_MAX_SIZE_MB=10 # Max upload size (1-50, default: 10)
AVATAR_FORMAT=webp # Format: webp|jpeg|png (default: webp)
AVATAR_COMPRESSION_EFFORT=6 # Effort (0-6, default: 6)
API Documentation
Swagger UI
Once the server is running, access the interactive API documentation at:
http://localhost:3001/api-docs
The Swagger UI provides:
- Complete endpoint documentation
- Interactive API testing
- Authentication support (Bearer tokens and cookies)
- Request/response schemas with examples
- Validation rules
API Usage
REST API
Login
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "admin@example.com", "password": "password123"}'
Response:
{
"success": true,
"message": "Login successful",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
Note: The refresh token is automatically set as an HTTP-only cookie.
Refresh Access Token
curl -X POST http://localhost:3001/api/auth/refresh-token \
-H "Content-Type: application/json" \
--cookie "refreshToken=YOUR_REFRESH_TOKEN"
Change Password
curl -X POST http://localhost:3001/api/auth/change-password \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"currentPassword": "old123", "newPassword": "New123Pass"}'
gRPC Client
import { GrpcClient } from "./src/grpc/client.service.js";
const client = new GrpcClient("localhost:50051");
// Login
const loginResult = await client.login("admin@example.com", "password123");
// Get all users
const users = await client.getAllUsers();
// Close connection
client.close();
Testing
Test gRPC Client
npm run test-grpc
Create Admin User
npm run create-admin
Development
Project Structure
src/
├── config/ # Configuration files
├── controllers/ # REST API controllers
├── grpc/ # gRPC service implementation
├── middleware/ # Express middleware
├── models/ # Database models
├── routes/ # REST API routes
├── schemas/ # Validation schemas
├── services/ # Business logic
├── types/ # TypeScript types
└── vault/ # Vault integration
Code Generation
The gRPC code is generated from the auth.proto file:
npm run generate-grpc
This creates:
src/generated/auth.js- JavaScript gRPC definitionssrc/generated/auth.d.ts- TypeScript definitions
Admin User Seeding
Create a root admin user for initial setup:
npm run seed-admin
This creates an admin user with:
- Name: "root admin"
- Email: From
ADMIN_EMAILenv var (default:root-admin@gmail.com) - Password: From
ADMIN_PASSWORDenv var (default:admin123456) - Role:
admin
Environment Variables:
ADMIN_EMAIL=your-admin@example.com
ADMIN_PASSWORD=your-secure-password
Important: Change the default password after first login!
Security Features
- Password Hashing: bcrypt with 12 salt rounds
- JWT Tokens: Secure access and refresh tokens
- Rate Limiting: Prevents brute force attacks
- Input Validation: Comprehensive request validation
- CORS Protection: Configurable origin restrictions
- Helmet: Security headers
- Secrets Management: Vault integration for sensitive data
Monitoring
- Health Check:
GET /api/health - Structured Logging: Winston with configurable levels
- Error Handling: Comprehensive error handling and logging
License
MIT