الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقت
الـ session: id عشوائي في cookie، والبيانات في Redis بـ TTL. ليه Redis (كل الـ instances بتشوف نفس الـ sessions، والـ logout فوري). sliding expiration بـ EXPIRE مع كل request، وتخزين hash الـ id مش الـ id نفسه. وإدارة الأجهزة: sorted set لكل مستخدم، وحد أقصى للأجهزة، و logout من كل الأجهزة التانية.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. بعد ما المستخدم يسجّل دخول، إزاي الـ server يفتكره في كل request؟ الطريقة الكلاسيكية: session. الـ server بيعمل id عشوائي طويل، ويحطه في cookie. والبيانات نفسها، مين المستخدم، بتتخزن عند الـ server. ومع كل request، المتصفح بيبعت الـ cookie، والـ server يدوّر بالـ id. وليه Redis؟ لأن عندك instances كتير، ولازم كلهم يشوفوا نفس الـ sessions. ولأن الـ logout لازم يبقى فوري: تمسح الـ key، خلاص. sessions dot js: الـ id اتنين وتلاتين byte عشوائي. والـ key في Redis هو sha two fifty six للـ id، مش الـ id نفسه، فلو حد قدر يقرا Redis، ما يقدرش يستخدم اللي شافه. و readSession بيمدّ العمر مع كل استخدام، ودي اسمها sliding expiration. server dot js: middleware بيقرا الـ session من الـ cookie. login بيعمل session ويحط الـ cookie بالـ flags اللي اتعلمناها. me بيرجّع البيانات والـ TTL. logout بيمسح. و debug بيورّينا الـ keys في Redis.
نشغّل: login، وبعدين نبص على الـ keys في Redis.
import express from "express";
import cookieParser from "cookie-parser";
import { redis, createSession, readSession, destroySession, ttlOf } from "./sessions.js";
await redis.flushall();
const app = express();
app.use(express.json());
app.use(cookieParser());
const COOKIE = { httpOnly: true, secure: true, sameSite: "lax", path: "/" };
app.use(async (req, res, next) => {
req.session = await readSession(req.cookies.sid);
next();
});
app.post("/login", async (req, res) => {
// (التحقق من الـ password ليه درس)
const sid = await createSession({ userId: 7, name: req.body.name });
res.cookie("sid", sid, COOKIE);
res.json({ ok: true, sidLength: sid.length });
});
app.get("/me", async (req, res) => {
if (!req.session) return res.status(401).json({ error: "سجّل دخول" });
res.json({ ...req.session, ttl: await ttlOf(req.cookies.sid) });
});
app.post("/logout", async (req, res) => {
await destroySession(req.cookies.sid);
res.clearCookie("sid", COOKIE);
res.json({ ok: true });
});
app.get("/debug/keys", async (req, res) => res.json((await redis.scan("0", "MATCH", "sess:*"))[1]));
app.listen(3000, () => console.log("http://localhost:3000"));المخرجات
$ node server.js
http://localhost:3000
→ POST /login
{"name":"mona"}
← 200 OK
connection: keep-alive
content-length: 26
content-type: application/json; charset=utf-8
etag: W/"1a-tvlo22zO3b2+XXqmkOuad20FyYM"
keep-alive: timeout=5
set-cookie: sid=ogBgmC3o0AEryJtcwGEwHATTwPsydLrxtzIJX2OhmEQ; Path=/; HttpOnly; Secure; SameSite=Lax
x-powered-by: Express
{
"ok": true,
"sidLength": 43
}
→ GET /debug/keys
← 200 OK
[
"sess:14b1f5d9002f89ee7763157306b10065f961ae393fa62afd04ba7cd17de26290"
]الـ cookie فيها sid طوله تلاتة وأربعين حرف، وده الـ base64url بتاع اتنين وتلاتين byte، ومعاها HttpOnly و Secure و SameSite. وفي Redis: key بيبدأ بـ sess، وبعده hash مالوش علاقة بالـ sid اللي في الـ cookie. والـ requests اللي جاية محتاجة الـ cookie، فخلينا نجرّب بـ script بيمسكها ويبعتها زي المتصفح. نفس الـ server، والـ client بيبعت الـ cookie.
import { spawn } from "node:child_process";
const server = spawn("node", ["server.js"], { stdio: "ignore", env: process.env });
await new Promise((r) => setTimeout(r, 800));
const base = "http://localhost:3000";
const login = await fetch(`${base}/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "mona" }) });
const cookie = login.headers.get("set-cookie").split(";")[0];
const me = async () => {
const r = await fetch(`${base}/me`, { headers: { cookie } });
return `${r.status} ${JSON.stringify(await r.json())}`;
};
console.log("me:", await me());
await fetch(`${base}/logout`, { method: "POST", headers: { cookie } });
console.log("بعد logout:", await me());
server.kill();المخرجات
$ node client.js
me: 200 {"userId":7,"name":"mona","createdAt":1792245373648,"ttl":1800}
بعد logout: 401 {"error":"سجّل دخول"}me بالـ cookie: البيانات، و createdAt، والـ ttl ألف وتمنمية تانية، يعني تلاتين دقيقة. وبعد الـ logout: four oh one، حتى بنفس الـ cookie، لأن الـ session اتمسحت من Redis. وده الفرق الكبير عن الـ JWT اللي هنشوفه في قسم الـ auth: الـ JWT صعب تلغيه قبل ما يخلص، والـ session بتتلغي فورًا. التحدي: الأجهزة المتسجلة. زي صفحة الأجهزة في Google أو Netflix. كل مستخدم ليه sorted set بالـ sessions بتاعته، والـ score هو وقت الدخول. أقصى تلات أجهزة: الرابع يخرّج الأقدم. ودالة بترجّع أسماء الأجهزة. و logout من كل الأجهزة التانية. التفاصيل في الكومنت.
login(userId, device): session + ZADD user:<id>:sessions، ولو أكتر من 3 ← ZPOPMIN وامسح. devices() بـ ZRANGE و MGET، و logoutOthers() يمسح الكل ما عدا الحالي.
الحل. login: MULTI بيكتب الـ session والـ sorted set مع بعض، ولو عدّينا التلاتة: ZPOPMIN بيطلّع الأقدم ونمسح الـ session بتاعه. devices: ZRANGE و MGET مرة واحدة، واللي مات نشيله من الـ set. logoutOthers: كل الـ hashes ما عدا الحالي، و MULTI بيمسح الـ sessions ويشيلهم من الـ set. نشغّل.
import crypto from "node:crypto";
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.flushall();
const keyOf = (sid) => "sess:" + crypto.createHash("sha256").update(sid).digest("hex");
const MAX_DEVICES = 3;
async function login(userId, device) {
const sid = crypto.randomBytes(32).toString("base64url");
const h = keyOf(sid);
const set = `user:${userId}:sessions`;
await redis
.multi()
.set(h, JSON.stringify({ userId, device }), "EX", 1800)
.zadd(set, Date.now(), h)
.exec();
if ((await redis.zcard(set)) > MAX_DEVICES) {
const [oldest] = await redis.zpopmin(set);
await redis.del(oldest);
}
await new Promise((r) => setTimeout(r, 5)); // كل login بوقت مختلف
return sid;
}
async function devices(userId) {
const set = `user:${userId}:sessions`;
const hashes = await redis.zrange(set, 0, -1);
if (!hashes.length) return [];
const raws = await redis.mget(hashes);
const dead = hashes.filter((_, i) => raws[i] === null);
if (dead.length) await redis.zrem(set, ...dead);
return raws.filter(Boolean).map((r) => JSON.parse(r).device);
}
async function logoutOthers(userId, currentSid) {
const set = `user:${userId}:sessions`;
const keep = keyOf(currentSid);
const others = (await redis.zrange(set, 0, -1)).filter((h) => h !== keep);
if (others.length) await redis.multi().del(...others).zrem(set, ...others).exec();
}
const sids = {};
for (const d of ["phone", "laptop", "tablet", "tv"]) sids[d] = await login(7, d);
console.log(await devices(7));
await logoutOthers(7, sids.laptop);
console.log(await devices(7));
redis.disconnect();المخرجات
$ node main.js [ 'laptop', 'tablet', 'tv' ] [ 'laptop' ]
بعد أربع أجهزة: laptop و tablet و tv، والـ phone خرج لأنه الأقدم. وبعد logoutOthers من الـ laptop: laptop بس. الدرس الجاي: Redis Streams والـ consumer groups.
03 / دروس المسار (122)
- 01أهلًا بيك: يعني إيه backend، والكورس ده ماشي إزاي
- 02الملفات والفولدرات والـ terminal: تتحرك على جهازك زي المبرمجين
- 03Node وأول برنامج: تشغّل وتقرا رسالة الخطأ
- 04القيم والمتغيرات والأنواع: const و let و typeof
- 05القرارات والتكرار: if و === والـ truthy والـ loops
- 06الـ functions: parameters و return والـ arrow functions والـ scope
- 07الـ objects والـ arrays: destructuring و spread و map و filter و reduce
- 08JSON والنصوص والتواريخ: اللغة اللي الـ backend بيتكلم بيها
- 09الـ callbacks والـ closures وأول لمسة async: setTimeout
- 10الـ classes والـ errors: throw و try/catch و stack trace
- 11git: تحفَظ كل خطوة وترجعلها، وما تسرّبش أسرارك
- 12ESM و CommonJS و package exports: Node بيلاقي الـ modules إزاي
- 13الـ Promises و async/await: sequential و parallel والأخطاء والإلغاء
- 14الـ event loop والـ microtasks: Node بيعمل كل حاجة بـ thread واحد إزاي
- 15الـ Streams والـ Backpressure: ملفات أكبر من الـ memory
- 16الـ File System والـ paths: قراية وكتابة صح، ومن غير path traversal
- 17الـ Buffers والبيانات الـ binary: الـ bytes من جُوّه
- 18Crypto APIs والأسرار: random و hash و HMAC و AES-GCM
- 19الـ Worker Threads: شغل CPU تقيل من غير ما توقف الـ server
- 20الـ Errors على مستوى الـ process: operational و programmer و crash-only
- 21الـ Node test runner والـ debugging: tests من غير مكتبات
- 22HTTP من جُوّه: الـ methods والـ status codes والـ headers
- 23Express والـ Routing: الـ params والـ query والترتيب والـ Router
- 24Express 5: إيه اللي اتغيّر، وإزاي تنقل مشروع قديم
- 25الـ Middleware ودورة حياة الـ request جُوّه Express
- 26Validation للمدخلات بـ Zod: ما تصدّقش أي حاجة جاية من برة
- 27تصنيف الأخطاء و Problem Details: شكل واحد لكل الـ errors
- 28الـ CORS والـ Cookies: المتصفح بيحمي المستخدم إزاي
- 29رفع الملفات وحدود الحجم: multer من غير ثغرات
- 30الـ Realtime: Server-Sent Events و WebSockets
- 31OpenAPI والـ API Versioning: عقد مكتوب، وتغيير من غير ما تكسر حد
- 32PostgreSQL: الـ DDL وأنواع البيانات الصح لكل عمود
- 33الـ Constraints: PK و FK و UNIQUE و CHECK — الـ database بتحمي نفسها
- 34الـ Normalization والـ ERD: تقسّم البيانات صح من أول يوم
- 35الـ JOINs والتجميع: INNER و LEFT و GROUP BY و HAVING و window functions
- 36JSONB في PostgreSQL: إمتى تستخدمه، وإزاي تسأله وتعمله index
- 37الـ Indexes من جُوّه: B-tree و GIN و BRIN
- 38Partial و Covering indexes: indexes أصغر وأسرع
- 39الـ Pagination بالـ Keyset: ليه OFFSET بيبطّأ وبيكرر
- 40Full Text Search في Postgres: بحث بالكلمات، بالعربي والإنجليزي
- 41EXPLAIN ANALYZE والـ Planner: اقرا الـ plan وصلّح الـ query
- 42الـ Transactions بـ node-postgres: كله أو ولا حاجة
- 43الـ MVCC ومستويات الـ Isolation: transactions كتير في نفس الوقت
- 44الـ Locks والـ Deadlocks: مين مستني مين
- 45SKIP LOCKED و Job Leasing: Postgres كـ job queue
- 46Row Level Security والـ Multi-tenancy: كل عميل يشوف بياناته بس
- 47Migrations من غير downtime: expand و backfill و contract
- 48الـ Replication والـ Read Replicas: نسخ حية من الـ database
- 49الـ Connection Pooling و PgBouncer: connections أقل، requests أكتر
- 50الـ Partitioning والـ VACUUM والمراقبة: Postgres على المدى الطويل
- 51Redis وأنواع البيانات: strings و hashes و lists و sets و sorted sets
- 52Cache-aside والـ TTL: Redis قدام الـ database
- 53الـ Cache invalidation والـ Stampede: لما الـ key الشهير يموت
- 54Lua والـ Atomicity في Redis: كام أمر كأنهم أمر واحد
- 55الـ Rate Limiting في Redis: fixed window و sliding window و token bucket
- 56الـ Sessions في Redis: تسجيل دخول تقدر تلغيه في أي وقتانت هنا
- 57Redis Streams والـ Consumer Groups: log بيتوزع على workers
- 58Pub/Sub و BullMQ: إشارات بين الـ instances، وطوابير شغل محترمة
- 59Redis لما يقع: الـ persistence (RDB و AOF) والـ replication
- 60Redis في الإنتاج: الـ ACLs والـ Cluster والمراقبة
- 61تخزين الـ Passwords بـ Argon2id: صح من أول مرة
- 62Session Fixation والـ Rotation: id جديد مع كل صلاحية جديدة
- 63الـ Cookie Flags والـ CSRF: المتصفح بيبعت الـ cookie، فلازم تتأكد مين اللي طلب
- 64الـ XSS والـ Content Security Policy: ما تخليش النص يتحوّل لـ code
- 65الـ OAuth و OpenID Connect و PKCE: login بـ Google من غير ما تشوف الـ password
- 66التأكد من الـ JWT صح: التوقيع والـ claims والـ scopes
- 67الـ BOLA و BFLA: الـ token السليم مش معناه إن الطلب مسموح
- 68الـ RBAC و ABAC والملكية: policy واحدة بدل ifs متفرقة
- 69الـ MFA والـ recovery: التاني factor اللي بجد
- 70الـ Passkeys و WebAuthn: login من غير password وضد الـ phishing
- 71الـ Threat Modeling بـ STRIDE: فكّر زي المهاجم قبل ما تكتب code
- 72الـ SQL Injection والـ Parameterization: الـ data ما تبقاش code
- 73الـ SSRF والـ Egress: ما تخليش الـ server بتاعك يزور الشبكة الداخلية
- 74الـ Security Headers والـ TLS: كل response يقول للـ browser يحمي المستخدم إزاي
- 75توقيع الـ Webhooks والـ Replay: الـ webhook ده جاي فعلًا من Stripe؟
- 76تغيير الأسرار والـ HMAC: إزاي تغيّر مفتاح من غير ما كل حاجة تقع
- 77سلسلة التوريد والـ SBOM: إنت واثق في ألف package ما تعرفهمش؟
- 78الـ Audit والـ Privacy Logs: سجّل مين عمل إيه، من غير ما تسجّل الأسرار
- 79اختبار الأمان و OWASP ASVS: الأمن جُوّه الـ CI، مش audit آخر السنة
- 80الـ Prototype Pollution والـ Resource DoS: request واحد يخلّي الكل admin أو يوقّع الـ server
- 81الـ SLI والـ SLO والـ Error Budget: إمتى تصحّي الـ on-call وإمتى تسيبه نايم
- 82الـ Event Loop Delay والـ ELU: لما Node نفسه يتخنق
- 83الـ Worker Threads والـ CPU Profiling: الشغل التقيل بره الـ event loop، والوقت راح فين
- 84الـ Memory والـ GC والـ Leaks: الـ process اللي بيكبر لحد ما يقع
- 85الـ N+1 Queries والـ DataLoader: صفحة واحدة بمِيّتين query
- 86الـ HTTP Caching والـ Compression: أسرع request هو اللي ما بيوصلش
- 87الـ Load Testing والـ Soak Testing: الـ server بيستحمل قد إيه بجد
- 88الـ Concurrency Limits والـ Bulkheads: dependency بطيئة ما توقعش الـ app كله
- 89الـ Timeouts والـ Retries والـ Circuit Breakers: إزاي تتعامل مع dependency بطيئة أو واقعة
- 90OpenTelemetry والـ Distributed Tracing: الـ request راح فين وضاع وقته فين
- 91Docker Layers والـ Build Context: ليه الـ build بياخد دقيقة وفيه الـ .env بتاعك
- 92Multi-stage Builds و Non-root: image صغيرة ومن غير root
- 93Docker Compose والـ Networks: الـ services بتلاقي بعض إزاي
- 94Docker Volumes: الـ data بتتحفَظ فين
- 95Healthcheck و Restart و Resource Limits: running مش معناها شغّال
- 96BuildKit والـ Build Secrets: الـ token ما يدخلش الـ image
- 97Reverse Proxy و TLS: اللي واقف قدام الـ app
- 98Multi-arch Images والـ Native Modules: اشتغلت عندي
- 99CI/CD و Rollback و Canary: الـ deploy يبقى ممل
- 100Kubernetes من الأول: Pods و Deployments و Services و Probes
- 101Modular Monolith و DDD: حدود واضحة من غير network
- 102Transactional Outbox و Inbox: الـ event ما يضيعش وما يتنفذش مرتين
- 103Sagas: عملية واحدة على تلات services من غير transaction واحدة
- 104CQRS و Event Sourcing: الـ events هي الحقيقة
- 105الـ Queues والـ Brokers: BullMQ و RabbitMQ و Kafka و SQS
- 106Realtime على أكتر من instance: Redis pub/sub و presence و resume
- 107الـ Object Storage والـ Media: presigned URLs و uploads مباشرة
- 108التكامل مع الـ Email والـ Search: retries و webhooks و indexes
- 109GraphQL و gRPC في الإنتاج: contracts و DataLoader و limits و deadlines
- 110Kafka على أكتر من zone و region: الـ replication والـ ISR والـ acks والـ MirrorMaker والـ failover
- 111TypeScript و runtime boundaries: الـ types بتختفي، والـ schemas لأ
- 112ORM ولا SQL: query builders و repositories و migrations و transactions
- 113الـ Serverless من جُوّه: cold starts و freeze و timeouts و connections
- 114الـ Testing Pyramid: unit و integration و e2e على Postgres حقيقية
- 115Contract Testing و Property-Based Testing بـ fast-check
- 116الـ Payments: idempotency و webhooks و refunds و reconciliation
- 117الـ Timezones والـ Internationalization: UTC و DST والـ locales والـ plurals والفلوس
- 118الـ Privacy والـ Data Retention: consent و export و erasure و crypto shredding
- 119الـ ADRs والـ Feature Flags: القرارات المكتوبة والـ rollout من غير deploy
- 120Multi-region active-active: حل الـ conflicts بـ HLC و CRDTs
- 121Readiness و Liveness و Startup Probes: الـ pod جاهز ولا عايش؟
- 122Incident Runbooks: من الـ alert للـ postmortem