Create auth_middleware.js
Browse files
middleware/auth_middleware.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class AuthMiddleware {
|
| 2 |
+
static checkAuth(requiredRole = null) {
|
| 3 |
+
return (callback) => {
|
| 4 |
+
// بررسی احراز هویت
|
| 5 |
+
if (!authManager.isAuthenticated()) {
|
| 6 |
+
authzManager.showLoginRequired();
|
| 7 |
+
return false;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
// بررسی نقش اگر مشخص شده باشد
|
| 11 |
+
if (requiredRole && !authzManager.hasRole(requiredRole)) {
|
| 12 |
+
authzManager.showAccessDenied();
|
| 13 |
+
return false;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
return callback();
|
| 17 |
+
};
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
static optionalAuth(callback) {
|
| 21 |
+
return () => {
|
| 22 |
+
// اگر کاربر احراز هویت شده باشد، اطلاعاتش را پاس میدهد
|
| 23 |
+
const user = authManager.getCurrentUser();
|
| 24 |
+
return callback(user);
|
| 25 |
+
};
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
static initializeApp() {
|
| 29 |
+
// مقداردهی اولیه کاربران پیشفرض
|
| 30 |
+
authManager.initializeDefaultUsers();
|
| 31 |
+
|
| 32 |
+
// بررسی توکن موجود
|
| 33 |
+
const token = authManager.getToken();
|
| 34 |
+
if (token) {
|
| 35 |
+
const tokenData = authManager.verifyToken(token);
|
| 36 |
+
if (!tokenData) {
|
| 37 |
+
authManager.logout();
|
| 38 |
+
console.log('Token expired, user logged out');
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// نمایش وضعیت ورود در کنسول
|
| 43 |
+
const currentUser = authManager.getCurrentUser();
|
| 44 |
+
if (currentUser) {
|
| 45 |
+
console.log(`User authenticated: ${currentUser.username} (${currentUser.role})`);
|
| 46 |
+
} else {
|
| 47 |
+
console.log('No user authenticated');
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// میانافزارهای سریع
|
| 53 |
+
const requireAuth = (callback) => AuthMiddleware.checkAuth()(callback);
|
| 54 |
+
const requireStudent = (callback) => AuthMiddleware.checkAuth('student')(callback);
|
| 55 |
+
const requireInstructor = (callback) => AuthMiddleware.checkAuth('instructor')(callback);
|
| 56 |
+
const requireAdmin = (callback) => AuthMiddleware.checkAuth('admin')(callback);
|