Systems Hub
Production System — subrohub Backend

Authentication &
Authorization System

Phone OTP থেকে শুরু করে Course Access পর্যন্ত — ১০-২০ লাখ User কিভাবে Serve হয়

১০–২০ লাখ
Active Users
OTP + JWT
Auth Method
Redis
Cache Layer
Role-Based
Authorization

← → Arrow Keys • Space • বাটন দিয়ে নেভিগেট করুন

System Overview

পুরো সিস্টেম এক নজরে

📱
User / Client
Phone দিয়ে Request
HTTPS
🛡️
Rate Limiter
Spam Block
Pass
⚙️
Express Server
Route + Middleware
Check
Redis Cache
Fast Lookup
Cache Miss
🗄️
PostgreSQL
Permanent Data
🔐

Authentication

Phone OTP দিয়ে পরিচয় যাচাই → JWT Token তৈরি

🎫

Authorization

Token দেখে Role ও Course Access চেক করা হয়

🚀

Scale করা

Redis Cache দিয়ে DB-তে চাপ না দিয়ে লাখো Request সামলানো

Authentication — Phase 1

নতুন User Sign Up করলে কী হয়?

1
📱 Phone Number পাঠায়

User তার 01XXXXXXXXX নম্বর POST করে /signup route-এ

2
🔍 DB Check — আছে নাকি নেই?

Prisma দিয়ে grandCelebrationAuth table-এ খোঁজা হয়

3
📤 OTP পাঠানো হয়

OtpService SMS Gateway দিয়ে 4-digit code পাঠায়

4
🔑 Temp Token দেওয়া হয়

authToken: null, refreshToken: temp JWT

5
✅ OTP Verify → Real Token

সঠিক OTP → isVerifyPhone: true → আসল authToken

subrohub App — Sign Up
01XXXXXXXXX
OTP পাঠান →
🚫 Rate Limit সুরক্ষা

সর্বোচ্চ ৪ বার OTP চাওয়া যাবে
প্রতিটির মাঝে ২ মিনিট অপেক্ষা

// Temp Refresh Token
eyJhbGciOiJIUzI1NiJ9.
{phone, role, isVerifyPhone: false}
.TEMP_SECRET ← verify পর্যন্ত
Authentication — Phase 2

Existing User Login করলে কী হয়?

📱
User
POST /request/login/otp
🛡️
Rate Check
max 4 tries
🗄️
DB Lookup
Prisma findFirst
📨
SMS OTP
OtpService
🔐
JWT তৈরি
HS256 Sign
🎟 Access Token (authToken)
{ id: "user_id", phone: "01XXX", role: "student", isVerifyPhone: true } // Algorithm: HS256 | Short expiry // Header: x-access-token
🔄 Refresh Token
{ id: "user_id", phone: "01XXX", role: "student" } // Different secret key // Long expiry | HttpOnly Cookie-তে থাকে
Authorization Middleware

Protected Route-এ Request আসলে কী হয়?

📨 Request আসে
x-access-token: eyJhbGciOiJIUzI1NiJ9...
🔍 JWT Verify
verifyUserTokenWithSignature() HS256
Invalid→401
⚡ Redis Cache Check
getCachedAuthUser() — DB-তে না গিয়ে
Hit → fast
📱 Single Device Check
validateCachedStudentSession()
2 device→300
✅ req.user সেট → next()
Controller-এ পৌঁছায় — Resource Access মিলে
Response Codes
401 Unauthorized
"Invalid or expired token."
403 Forbidden
"You are not authorized to access this resource."
300 Multiple Choices
"একটি অ্যাকাউন্ট থেকে এক সময়ে একটি Device"
200 OK ✓
সব চেক পাস → Content পাঠানো হয়
406 Not Acceptable
"Session expired. Please login again."
Performance Layer

Redis Cache — লাখো Request সামলানো হয় কিভাবে?

Cache HIT
Redis-এ পাওয়া গেল
~1 ms
🐌
Cache MISS
DB-তে যেতে হলো
~100 ms
Redis Cache Keys
auth:user:{role}:{id}→ {user}TTL 2min
auth:session:{id}:{host}→ {session}TTL 5min
course:ctx:{entityId}→ {course}TTL 2min
course:access:{cId}:{uId}→ boolTTL 2min
💡 কেন লাখো User সামলানো যায়?

১০ লাখ User একসাথে request করলে, প্রথমটি DB-তে যায়, বাকি সব Redis থেকে instant! DB চাপ ৯৯% কমে।

getOrLoadStrictCache Pattern
// authorization.cache.js async function getCachedAuthUser({ role, userId }) { const key = CacheKeys.user(role, userId); return getOrLoadStrictCache({ key, loader: async () => { // Miss হলে DB থেকে নাও return await prisma.user .findUnique({ where: { id: userId } }); }, ttl: 2 * 60_000 }); }
Cache Invalidation
invalidateCourseStudentAccess(userId, courseId); invalidateCourseStudentAccessMany(userId, courseIds);
Course Authorization

কোর্স Access কিভাবে Check হয়?

📱
Student
Video দেখতে চায়
GET /course/video/{id}
🛡️
Middleware
Token → User
canUserAccessCourse()
Redis → DB
Access Check
Content
Video / PDF
// authorization.cache.js async function canUserAccessCourse(userId, courseId) { // ১. Course কি Free? const ctx = await getCachedCourseContext(courseId); if (ctx.course.isCourseFree) return true; // ২. Student কি Enrolled? return await hasCourseStudentAccess(userId, courseId); }
✅ Access পাবে যখন
✓ Course Free হলে
✓ Paid Course কিনে Enrolled হলে
✓ Admin / SuperAdmin
✓ Membership Active
❌ Access পাবে না যখন
✗ Paid Course কেনা হয়নি
✗ Course Archived
✗ Token নেই বা Expired
✗ অন্য Device-এ Login
Role-Based Access Control

কে কী করতে পারবে?

Role কারা কী করতে পারে Token-এ
superAdmin সর্বোচ্চ কর্তৃপক্ষ সব কিছু — User, Course, Settings, Analytics ♾️ Full
admin Content Team Course তৈরি, Video upload, Live Class manage 🔑 High
solver প্রশ্ন সমাধানকারী Student প্রশ্নের উত্তর দেওয়া 📝 Limited
student শিক্ষার্থী কেনা Course দেখা, Quiz দেওয়া 📚 Course Only
🔍 Role Check Middleware
authorize(["student", "admin"]); const tokenRole = decoded?.role; if (!allowedRoles.includes(tokenRole)) { throw 401; }
🔎 User Lookup Order
1️⃣ Admin table চেক
2️⃣ Student table চেক
3️⃣ Solver table চেক
4️⃣ SuperAdmin table চেক
findUserWithRole(emailOrPhone)
Scalability & Security

১০–২০ লাখ User কিভাবে Handle হয়?

Performance Numbers
Redis Cache Hit Rate0%
DB Load Reduction0%
Security Score0%
Uptime Target0%
~1ms
Cache Response
4x max
OTP Attempts
2 min
OTP Cooldown
1 device
Per Account
Security Layers
🛡️
IP-based Rate Limiting
Brute force ও bot attack রোধ করে
⏱️
OTP Expiry + Count Limit
Expired বা extra OTP কাজ করে না
🔏
HS256 JWT Signature
Secret key ছাড়া Token tamper অসম্ভব
📱
Single Device Session
Account sharing রোধ করে
🔄
Access + Refresh Token Pair
Short-lived access → secure rotation
সারসংক্ষেপ

এক কথায় পুরো System

Phone OTP → JWT Token → Redis Cache → Role Check → Course Access — এই ৫ ধাপে ১০-২০ লাখ User Serve হয়

🔐

Authentication

Phone OTP → Temp Token → Verify → Real JWT
Rate limit + OTP expiry দিয়ে সুরক্ষিত

🎫

Authorization

JWT → Role → Redis Cache → User Check
Course Access verify (Free বা Enrolled)

🚀

Scale করা যায়

Redis cache → DB load কমানো
Single device + cache invalidation

Complete Request Lifecycle
📱 User 🛡️ Rate Limit ✅ Validation 🔑 JWT Verify ⚡ Redis Cache 👤 Role Check 📚 Course Access ✅ 200 OK
Node.js · Express · Prisma ORM · PostgreSQL · Redis · JWT HS256 · bcryptjs