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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class Authentication {
|
| 2 |
+
constructor() {
|
| 3 |
+
this.tokenKey = 'authToken';
|
| 4 |
+
this.userKey = 'currentUser';
|
| 5 |
+
this.usersKey = 'appUsers';
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
generateToken(userId, username, role = 'student') {
|
| 9 |
+
// ایجاد توکن ساده برای محیط استاتیک
|
| 10 |
+
const tokenData = {
|
| 11 |
+
userId: userId,
|
| 12 |
+
username: username,
|
| 13 |
+
role: role,
|
| 14 |
+
timestamp: Date.now(),
|
| 15 |
+
exp: Date.now() + (7 * 24 * 60 * 60 * 1000) // 7 روز
|
| 16 |
+
};
|
| 17 |
+
return btoa(JSON.stringify(tokenData));
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
verifyToken(token) {
|
| 21 |
+
try {
|
| 22 |
+
const tokenData = JSON.parse(atob(token));
|
| 23 |
+
if (tokenData.exp > Date.now()) {
|
| 24 |
+
return tokenData;
|
| 25 |
+
} else {
|
| 26 |
+
this.logout();
|
| 27 |
+
return null;
|
| 28 |
+
}
|
| 29 |
+
} catch (error) {
|
| 30 |
+
console.error('Token verification failed:', error);
|
| 31 |
+
return null;
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
hashPassword(password) {
|
| 36 |
+
// هش ساده برای محیط توسعه - در تولید از روش امنتری استفاده شود
|
| 37 |
+
let hash = 0;
|
| 38 |
+
for (let i = 0; i < password.length; i++) {
|
| 39 |
+
const char = password.charCodeAt(i);
|
| 40 |
+
hash = ((hash << 5) - hash) + char;
|
| 41 |
+
hash = hash & hash;
|
| 42 |
+
}
|
| 43 |
+
return hash.toString();
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
setToken(token) {
|
| 47 |
+
localStorage.setItem(this.tokenKey, token);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
getToken() {
|
| 51 |
+
return localStorage.getItem(this.tokenKey);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
setCurrentUser(user) {
|
| 55 |
+
localStorage.setItem(this.userKey, JSON.stringify(user));
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
getCurrentUser() {
|
| 59 |
+
const userStr = localStorage.getItem(this.userKey);
|
| 60 |
+
return userStr ? JSON.parse(userStr) : null;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
isAuthenticated() {
|
| 64 |
+
const token = this.getToken();
|
| 65 |
+
if (!token) return false;
|
| 66 |
+
|
| 67 |
+
const tokenData = this.verifyToken(token);
|
| 68 |
+
return tokenData !== null;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
logout() {
|
| 72 |
+
localStorage.removeItem(this.tokenKey);
|
| 73 |
+
localStorage.removeItem(this.userKey);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// مدیریت کاربران در localStorage
|
| 77 |
+
initializeDefaultUsers() {
|
| 78 |
+
const existingUsers = this.getUsers();
|
| 79 |
+
if (Object.keys(existingUsers).length === 0) {
|
| 80 |
+
const defaultUsers = {
|
| 81 |
+
'1': {
|
| 82 |
+
userId: '1',
|
| 83 |
+
username: 'student',
|
| 84 |
+
email: 'student@example.com',
|
| 85 |
+
password: this.hashPassword('password123'),
|
| 86 |
+
role: 'student',
|
| 87 |
+
createdAt: new Date().toISOString(),
|
| 88 |
+
profile: {
|
| 89 |
+
fullName: 'دانشجوی نمونه',
|
| 90 |
+
bio: 'علاقمند به توسعه وب'
|
| 91 |
+
},
|
| 92 |
+
progress: {
|
| 93 |
+
totalScore: 0,
|
| 94 |
+
completedLessons: [],
|
| 95 |
+
currentLesson: 1
|
| 96 |
+
},
|
| 97 |
+
isActive: true
|
| 98 |
+
},
|
| 99 |
+
'2': {
|
| 100 |
+
userId: '2',
|
| 101 |
+
username: 'admin',
|
| 102 |
+
email: 'admin@example.com',
|
| 103 |
+
password: this.hashPassword('admin123'),
|
| 104 |
+
role: 'admin',
|
| 105 |
+
createdAt: new Date().toISOString(),
|
| 106 |
+
profile: {
|
| 107 |
+
fullName: 'مدیر سیستم',
|
| 108 |
+
bio: 'مدیر پلتفرم آموزشی'
|
| 109 |
+
},
|
| 110 |
+
progress: {
|
| 111 |
+
totalScore: 0,
|
| 112 |
+
completedLessons: [],
|
| 113 |
+
currentLesson: 1
|
| 114 |
+
},
|
| 115 |
+
isActive: true
|
| 116 |
+
}
|
| 117 |
+
};
|
| 118 |
+
this.saveUsers(defaultUsers);
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
getUsers() {
|
| 123 |
+
const usersStr = localStorage.getItem(this.usersKey);
|
| 124 |
+
return usersStr ? JSON.parse(usersStr) : {};
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
saveUsers(users) {
|
| 128 |
+
localStorage.setItem(this.usersKey, JSON.stringify(users));
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
registerUser(username, email, password, role = 'student', profile = {}) {
|
| 132 |
+
const users = this.getUsers();
|
| 133 |
+
|
| 134 |
+
// بررسی وجود کاربر
|
| 135 |
+
for (const userId in users) {
|
| 136 |
+
if (users[userId].username === username) {
|
| 137 |
+
return { success: false, message: 'نام کاربری already exists' };
|
| 138 |
+
}
|
| 139 |
+
if (users[userId].email === email) {
|
| 140 |
+
return { success: false, message: 'ایمیل already exists' };
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// ایجاد کاربر جدید
|
| 145 |
+
const newUserId = Object.keys(users).length + 1;
|
| 146 |
+
const newUser = {
|
| 147 |
+
userId: newUserId.toString(),
|
| 148 |
+
username: username,
|
| 149 |
+
email: email,
|
| 150 |
+
password: this.hashPassword(password),
|
| 151 |
+
role: role,
|
| 152 |
+
createdAt: new Date().toISOString(),
|
| 153 |
+
profile: {
|
| 154 |
+
fullName: profile.fullName || '',
|
| 155 |
+
bio: profile.bio || '',
|
| 156 |
+
avatar: profile.avatar || ''
|
| 157 |
+
},
|
| 158 |
+
progress: {
|
| 159 |
+
totalScore: 0,
|
| 160 |
+
completedLessons: [],
|
| 161 |
+
currentLesson: 1,
|
| 162 |
+
achievements: []
|
| 163 |
+
},
|
| 164 |
+
isActive: true
|
| 165 |
+
};
|
| 166 |
+
|
| 167 |
+
users[newUserId] = newUser;
|
| 168 |
+
this.saveUsers(users);
|
| 169 |
+
|
| 170 |
+
return { success: true, user: newUser };
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
loginUser(username, password) {
|
| 174 |
+
const users = this.getUsers();
|
| 175 |
+
const hashedPassword = this.hashPassword(password);
|
| 176 |
+
|
| 177 |
+
for (const userId in users) {
|
| 178 |
+
const user = users[userId];
|
| 179 |
+
if (user.username === username && user.password === hashedPassword && user.isActive) {
|
| 180 |
+
// ایجاد توکن
|
| 181 |
+
const token = this.generateToken(user.userId, user.username, user.role);
|
| 182 |
+
this.setToken(token);
|
| 183 |
+
this.setCurrentUser(user);
|
| 184 |
+
|
| 185 |
+
// بهروزرسانی آخرین ورود
|
| 186 |
+
user.lastLogin = new Date().toISOString();
|
| 187 |
+
this.saveUsers(users);
|
| 188 |
+
|
| 189 |
+
return { success: true, user: user, token: token };
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
return { success: false, message: 'Invalid username or password' };
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
updateUserProgress(userId, score = 0, completedLesson = null) {
|
| 197 |
+
const users = this.getUsers();
|
| 198 |
+
if (users[userId]) {
|
| 199 |
+
const user = users[userId];
|
| 200 |
+
|
| 201 |
+
if (score > 0) {
|
| 202 |
+
user.progress.totalScore = (user.progress.totalScore || 0) + score;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
if (completedLesson && !user.progress.completedLessons.includes(completedLesson)) {
|
| 206 |
+
user.progress.completedLessons.push(completedLesson);
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
this.saveUsers(users);
|
| 210 |
+
return { success: true, progress: user.progress };
|
| 211 |
+
}
|
| 212 |
+
return { success: false, message: 'User not found' };
|
| 213 |
+
}
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
// ایجاد نمونه singleton
|
| 217 |
+
const authManager = new Authentication();
|