Today I implemented role-based access control for analytics in my AI Phishing Defense Platform.
What was the goal?
Allow only PRO and ENTERPRISE API keys to access advanced usage statistics.
What was implemented?
Custom API Key Authentication
Instead of default DRF token auth, I built a custom:
class APIKeyAuthentication(BaseAuthentication)
It reads:
X-API-Key: <key>
And attaches:
request.api_key
to the request.
Important lesson:
Authentication must be side-effect free.
No DB updates inside authenticate().
Custom Permission Layer
class ProPlanOnly(BasePermission)
Checks:
- API key exists
- Key is active
- Plan is in ("pro", "enterprise")
This creates clean separation:
Authentication → Who are you?
Permission → Are you allowed here?
Usage Tracking System
Every request now logs:
endpoint
method
status code
timestamp
API key reference
This enables real SaaS metrics later.
Real Bug Found & Fixed
I accidentally had duplicate URL routes:
analytics/usage/
Django resolves first match only.
Lesson learned:
URL duplication silently overrides logic.
Architecture Now
- *Anonymous *→ basic limited access
- *Free *→ tracked analysis
- *Pro *→ analysis + analytics
This project is evolving from a demo into a monetizable security SaaS.
Tomorrow: analytics expansion layer.
Top comments (0)