fokan commited on
Commit
3e3d3de
·
1 Parent(s): d2bbb3a

Secure token management implementation

Browse files

- Recreated setup_tokens.py with environment variables only
- No hardcoded tokens included for security
- Added comprehensive security setup guide
- Updated .env.example with secure placeholders
- Implemented safe token loading and validation
- Added detailed usage examples and troubleshooting
- Ready for secure deployment to Hugging Face Spaces

Files changed (1) hide show
  1. setup_tokens.py +227 -0
setup_tokens.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Quick setup script for Hugging Face tokens
4
+ سكريپت إعداد سريع لرموز Hugging Face
5
+
6
+ This script loads tokens from environment variables only.
7
+ No hardcoded tokens are included for security.
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ # Add src to path
15
+ sys.path.insert(0, str(Path(__file__).parent / "src"))
16
+
17
+ def setup_tokens():
18
+ """Setup tokens from environment variables"""
19
+
20
+ print("🔑 إعداد رموز Hugging Face")
21
+ print("=" * 50)
22
+ print("📝 ملاحظة: يجب إضافة الرموز في متغيرات البيئة:")
23
+ print(" - HF_TOKEN_READ: رمز القراءة")
24
+ print(" - HF_TOKEN_WRITE: رمز الكتابة")
25
+ print(" - HF_TOKEN_FINE_GRAINED: رمز مخصص")
26
+ print("=" * 50)
27
+
28
+ try:
29
+ from src.core.token_manager import TokenManager
30
+
31
+ # Initialize token manager
32
+ token_manager = TokenManager()
33
+
34
+ # Token definitions from environment variables
35
+ tokens = {
36
+ 'read_token': {
37
+ 'token': os.getenv('HF_TOKEN_READ'),
38
+ 'type': 'read',
39
+ 'description': 'رمز القراءة - للتطوير والتعلم والوصول للنماذج العامة',
40
+ 'is_default': True
41
+ },
42
+ 'write_token': {
43
+ 'token': os.getenv('HF_TOKEN_WRITE'),
44
+ 'type': 'write',
45
+ 'description': 'رمز الكتابة - لرفع ومشاركة النماذج مع المجتمع',
46
+ 'is_default': False
47
+ },
48
+ 'fine_grained_token': {
49
+ 'token': os.getenv('HF_TOKEN_FINE_GRAINED'),
50
+ 'type': 'fine_grained',
51
+ 'description': 'رمز مخصص - للمشاريع التجارية والبيانات الطبية الحساسة',
52
+ 'is_default': False
53
+ }
54
+ }
55
+
56
+ # Save tokens
57
+ tokens_found = 0
58
+ for name, token_info in tokens.items():
59
+ token = token_info['token']
60
+
61
+ if not token:
62
+ print(f"⚠️ تخطي {name} - لم يتم العثور على الرمز في متغيرات البيئة")
63
+ continue
64
+
65
+ success = token_manager.save_token(
66
+ name=name,
67
+ token=token,
68
+ token_type=token_info['type'],
69
+ description=token_info['description'],
70
+ is_default=token_info['is_default']
71
+ )
72
+
73
+ if success:
74
+ tokens_found += 1
75
+ print(f"✅ تم حفظ {name} ({token_info['type']})")
76
+
77
+ # Validate token
78
+ validation = token_manager.validate_token(token)
79
+ if validation['valid']:
80
+ print(f" ✓ الرمز صحيح - المستخدم: {validation.get('username', 'غير معروف')}")
81
+ else:
82
+ print(f" ⚠️ تحذير: {validation.get('message', 'فشل التحقق')}")
83
+ else:
84
+ print(f"❌ فشل في حفظ {name}")
85
+
86
+ if tokens_found == 0:
87
+ print("\n❌ لم يتم العثور على أي رموز في متغيرات البيئة!")
88
+ print("💡 يرجى إضافة الرموز في إعدادات Hugging Face Spaces:")
89
+ print(" 1. اذهب إلى Settings > Variables")
90
+ print(" 2. أضف HF_TOKEN_READ, HF_TOKEN_WRITE, HF_TOKEN_FINE_GRAINED")
91
+ print(" 3. أعد تشغيل Space")
92
+ return False
93
+
94
+ print(f"\n📊 ملخص الرموز المحفوظة: {tokens_found}/3")
95
+ tokens_list = token_manager.list_tokens()
96
+
97
+ for token in tokens_list:
98
+ status = "🟢 افتراضي" if token['is_default'] else "🔵 متاح"
99
+ print(f" {status} {token['name']} ({token['type']}) - {token['usage_count']} استخدام")
100
+
101
+ print("\n🎯 تخصيص الرموز للمهام:")
102
+ task_mappings = {
103
+ 'read': 'قراءة النماذج العامة',
104
+ 'download': 'تحميل النماذج',
105
+ 'medical': 'البيانات الطبية الحساسة',
106
+ 'private': 'النماذج الخاصة والمحدودة',
107
+ 'write': 'رفع النماذج الجديدة',
108
+ 'upload': 'مشاركة المحتوى',
109
+ 'commercial': 'المشاريع التجارية',
110
+ 'enterprise': 'الاستخدام المؤسسي'
111
+ }
112
+
113
+ for task, description in task_mappings.items():
114
+ token = token_manager.get_token_for_task(task)
115
+ if token:
116
+ # Find token name
117
+ token_name = "غير معروف"
118
+ for t in tokens_list:
119
+ test_token = token_manager.get_token(t['name'])
120
+ if test_token == token:
121
+ token_name = t['name']
122
+ break
123
+ print(f" 📋 {task}: {description} → {token_name}")
124
+ else:
125
+ print(f" ❌ {task}: {description} → لا يوجد رمز مناسب")
126
+
127
+ print("\n✅ تم إعداد جميع الرموز بنجاح!")
128
+ print("\n🌐 يمكنك الآن:")
129
+ print(" • تشغيل التطبيق: python run_optimized.py")
130
+ print(" • إدارة الرموز: http://localhost:8000/tokens")
131
+ print(" • الوصول للبيانات الطبية: http://localhost:8000/medical-datasets")
132
+
133
+ return True
134
+
135
+ except ImportError as e:
136
+ print(f"❌ خطأ في الاستيراد: {e}")
137
+ print("💡 تأكد من تثبيت التبعيات: pip install -r requirements.txt")
138
+ return False
139
+ except Exception as e:
140
+ print(f"❌ خطأ في إعداد الرموز: {e}")
141
+ return False
142
+
143
+ def test_tokens():
144
+ """Test token functionality"""
145
+
146
+ print("\n🧪 اختبار وظائف الرموز")
147
+ print("=" * 30)
148
+
149
+ try:
150
+ from src.core.token_manager import TokenManager
151
+
152
+ token_manager = TokenManager()
153
+
154
+ # Test different task types
155
+ test_tasks = ['read', 'medical', 'write', 'private']
156
+
157
+ for task in test_tasks:
158
+ token = token_manager.get_token_for_task(task)
159
+ if token:
160
+ print(f"✅ {task}: رمز متوفر")
161
+ else:
162
+ print(f"❌ {task}: لا يوجد رمز")
163
+
164
+ return True
165
+
166
+ except Exception as e:
167
+ print(f"❌ خطأ في الاختبار: {e}")
168
+ return False
169
+
170
+ def show_usage_examples():
171
+ """Show usage examples"""
172
+
173
+ print("\n📚 أمثلة الاستخدام")
174
+ print("=" * 30)
175
+
176
+ examples = [
177
+ {
178
+ 'task': 'تحميل نموذج عام',
179
+ 'code': 'curl http://localhost:8000/api/tokens/for-task/read',
180
+ 'description': 'للحصول على رمز القراءة للنماذج العامة'
181
+ },
182
+ {
183
+ 'task': 'تحميل بيانات طبية',
184
+ 'code': 'curl http://localhost:8000/api/tokens/for-task/medical',
185
+ 'description': 'للحصول على رمز مخصص للبيانات الطبية'
186
+ },
187
+ {
188
+ 'task': 'رفع نموذج جديد',
189
+ 'code': 'curl http://localhost:8000/api/tokens/for-task/write',
190
+ 'description': 'للحصول على رمز الكتابة لرفع النماذج'
191
+ }
192
+ ]
193
+
194
+ for example in examples:
195
+ print(f"\n📋 {example['task']}:")
196
+ print(f" الكود: {example['code']}")
197
+ print(f" الوصف: {example['description']}")
198
+
199
+ def main():
200
+ """Main function"""
201
+
202
+ print("🚀 مرحباً بك في إعداد رموز Hugging Face")
203
+ print("Welcome to Hugging Face Tokens Setup")
204
+ print("=" * 60)
205
+
206
+ # Check if .env file exists
207
+ if not Path('.env').exists():
208
+ print("⚠️ ملف .env غير موجود")
209
+ print("💡 تأكد من نسخ .env.example إلى .env أو إضافة الرموز في متغيرات البيئة")
210
+
211
+ # Setup tokens
212
+ if setup_tokens():
213
+ # Test tokens
214
+ test_tokens()
215
+
216
+ # Show examples
217
+ show_usage_examples()
218
+
219
+ print("\n🎉 تم الإعداد بنجاح!")
220
+ return 0
221
+ else:
222
+ print("\n❌ فشل في الإعداد")
223
+ print("📖 راجع SECURITY_SETUP.md للحصول على تعليمات مفصلة")
224
+ return 1
225
+
226
+ if __name__ == "__main__":
227
+ sys.exit(main())