فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Update Auth.js
davoodmehraban89 committed
Sep 20, 2026 at 23:25 UTC
3cf5719b3c088c34a55917a78a738aa79c6b0bda
1 file changed
+280
-29
src/core/Auth.js
+280
-29
@@ -1,42 +1,262 @@
1
// ============================================================
2
-// Auth — احراز هویت ساده
2
+// Auth — احراز هویت محلی
3
+// - رمزها با PBKDF2-SHA256 هش میشوند (هرگز متن خام ذخیره نمیشود)
4
+// - بدون ورود موفق، برنامه بارگذاری نمیشود (صفحه قفل)
5
+// - نشست فقط شناسه کاربر را نگه میدارد، نه رمز و هش
6
+// توجه: این لایه جلوی دسترسی معمولی را میگیرد؛ دادههای IndexedDB
7
+// رمزگذاری نمیشوند و کسی که به فایلهای کامپیوتر دسترسی دارد میتواند آنها را بخواند.
8
// ============================================================
9
5
-import { StorageService } from './StorageService.js';
10
+import { StorageService, CREDENTIAL_FIELDS } from './StorageService.js';
11
import { EventBus } from './EventBus.js';
12
13
+const PBKDF2_ITERATIONS = 600000;
14
+const MIN_PASSWORD_LENGTH = 8;
15
+const LEGACY_DEFAULT_PASSWORD = 'admin123';
16
+const AUTH_ERROR = 'نام کاربری یا رمز عبور اشتباه است';
17
+
18
+const encoder = new TextEncoder();
19
+const toB64 = (bytes) => btoa(String.fromCharCode(...bytes));
20
+const fromB64 = (b64) => Uint8Array.from(atob(b64), c => c.charCodeAt(0));
21
+const sleep = (ms) => new Promise(r => setTimeout(r, ms));
22
+
23
+async function derive(password, salt, iterations) {
24
+ const key = await crypto.subtle.importKey('raw', encoder.encode(password), 'PBKDF2', false, ['deriveBits']);
25
+ const bits = await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, key, 256);
26
+ return new Uint8Array(bits);
27
+}
28
+
29
+function timingSafeEqual(a, b) {
30
+ if (a.length !== b.length) return false;
31
+ let diff = 0;
32
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
33
+ return diff === 0;
34
+}
35
+
36
+export async function hashPassword(password) {
37
+ const salt = crypto.getRandomValues(new Uint8Array(16));
38
+ const hash = await derive(password, salt, PBKDF2_ITERATIONS);
39
+ return {
40
+ pwAlgo: 'pbkdf2-sha256',
41
+ pwIter: PBKDF2_ITERATIONS,
42
+ pwSalt: toB64(salt),
43
+ pwHash: toB64(hash)
44
+ };
45
+}
46
+
47
+export async function verifyPassword(password, user) {
48
+ if (!user || !user.pwHash || !user.pwSalt) return false;
49
+ const hash = await derive(String(password ?? ''), fromB64(user.pwSalt), user.pwIter || PBKDF2_ITERATIONS);
50
+ return timingSafeEqual(hash, fromB64(user.pwHash));
51
+}
52
+
53
+const needsPassword = (user) => !!user.mustSetPassword || !user.pwHash;
54
+
55
class AuthImpl {
56
constructor() {
57
this.currentUser = null;
58
this.sessionKey = 'finora_pro_session';
59
+ this._failures = 0;
60
}
61
62
+ // ---------- راهاندازی ----------
63
+
64
async init() {
15
- const sessionUser = sessionStorage.getItem(this.sessionKey);
16
- if (sessionUser) {
17
- this.currentUser = JSON.parse(sessionUser);
18
- } else {
19
- const users = await StorageService.getAll('users');
20
- if (users.length === 0) {
21
- const admin = {
22
- id: 'user_admin',
23
- username: 'admin',
24
- pass: 'admin123',
25
- role: 'admin',
26
- displayName: 'مدیر سیستم',
27
- createdAt: new Date().toISOString()
28
- };
29
- await StorageService.put('users', admin);
30
- users.push(admin);
31
- }
32
- this.currentUser = users[0];
33
- sessionStorage.setItem(this.sessionKey, JSON.stringify(this.currentUser));
65
+ await this._migrateLegacyPasswords();
66
+
67
+ let users = await StorageService.getAll('users');
68
+ if (users.length === 0) {
69
+ // اولین اجرا: کاربر مدیر بدون رمز ساخته میشود و صفحه قفل از او رمز میگیرد
70
+ const admin = await StorageService.put('users', {
71
+ id: 'user_admin',
72
+ username: 'admin',
73
+ role: 'admin',
74
+ displayName: 'مدیر سیستم',
75
+ mustSetPassword: true,
76
+ createdAt: new Date().toISOString()
77
+ });
78
+ users = [admin];
79
}
80
+
81
+ let user = this._restoreSession(users);
82
+ if (!user) user = await this._showLockScreen(users);
83
+
84
+ this._startSession(user);
85
this._updateUI();
86
EventBus.emit('auth:ready', this.currentUser);
87
return this.currentUser;
88
}
89
90
+ // رمزهای متن خام نسخههای قبلی را هش میکند. رمز پیشفرض عمومی admin123 بیاعتبار
91
+ // میشود و کاربر باید رمز جدید تعیین کند.
92
+ async _migrateLegacyPasswords() {
93
+ const users = await StorageService.getAll('users');
94
+ for (const u of users) {
95
+ if (u.pass === undefined) continue;
96
+ const legacy = u.pass;
97
+ const next = { ...u };
98
+ delete next.pass;
99
+ if (typeof legacy !== 'string' || legacy === '' || legacy === LEGACY_DEFAULT_PASSWORD) {
100
+ next.mustSetPassword = true;
101
+ } else {
102
+ Object.assign(next, await hashPassword(legacy));
103
+ delete next.mustSetPassword;
104
+ }
105
+ await StorageService.put('users', next);
106
+ }
107
+ }
108
+
109
+ _restoreSession(users) {
110
+ const raw = sessionStorage.getItem(this.sessionKey);
111
+ if (!raw) return null;
112
+ let id = raw;
113
+ try {
114
+ const parsed = JSON.parse(raw); // نشست قدیمی کل شیء کاربر بود
115
+ if (parsed && typeof parsed === 'object' && parsed.id) id = parsed.id;
116
+ } catch (_) { /* نشست جدید فقط شناسه است */ }
117
+ const user = users.find(u => u.id === id);
118
+ if (!user || needsPassword(user)) return null;
119
+ return user;
120
+ }
121
+
122
+ _publicUser(user) {
123
+ const copy = { ...user };
124
+ CREDENTIAL_FIELDS.forEach(f => delete copy[f]);
125
+ delete copy.mustSetPassword;
126
+ return copy;
127
+ }
128
+
129
+ _startSession(user) {
130
+ this.currentUser = this._publicUser(user);
131
+ sessionStorage.setItem(this.sessionKey, user.id);
132
+ }
133
+
134
+ async _setPassword(user, password) {
135
+ const next = { ...user, ...(await hashPassword(password)), mustSetPassword: false };
136
+ delete next.pass;
137
+ return StorageService.put('users', next);
138
+ }
139
+
140
+ // ---------- صفحه قفل ----------
141
+
142
+ _showLockScreen(users) {
143
+ return new Promise((resolve) => {
144
+ const splash = document.getElementById('splash');
145
+ const splashDisplay = splash ? splash.style.display : '';
146
+ if (splash) splash.style.display = 'none';
147
+
148
+ const root = document.createElement('div');
149
+ root.id = 'finoraAuthOverlay';
150
+ root.setAttribute('dir', 'rtl');
151
+ root.style.cssText = 'position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;background:#0f172a;font-family:inherit;';
152
+ root.innerHTML = `
153
+ <form id="finoraAuthForm" autocomplete="on" style="width:min(92vw,380px);background:#fff;color:#0f172a;border-radius:16px;padding:28px;box-shadow:0 20px 60px rgba(0,0,0,.4);display:flex;flex-direction:column;gap:12px;">
154
+ <div id="faTitle" style="font-size:20px;font-weight:700;"></div>
155
+ <div id="faHint" style="font-size:13px;color:#475569;line-height:1.7;"></div>
156
+ <input id="faUser" name="username" type="text" placeholder="نام کاربری" autocomplete="username" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;">
157
+ <input id="faPass" name="password" type="password" placeholder="رمز عبور" autocomplete="current-password" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;">
158
+ <input id="faPass2" name="password2" type="password" placeholder="تکرار رمز عبور" autocomplete="new-password" style="padding:12px;border:1px solid #cbd5e1;border-radius:10px;font:inherit;display:none;">
159
+ <div id="faError" role="alert" style="min-height:20px;font-size:13px;color:#b91c1c;"></div>
160
+ <button id="faSubmit" type="submit" style="padding:12px;border:0;border-radius:10px;background:#2563eb;color:#fff;font:inherit;font-weight:700;cursor:pointer;">ورود</button>
161
+ </form>`;
162
+ document.body.appendChild(root);
163
+
164
+ const $ = (id) => root.querySelector('#' + id);
165
+ const form = $('finoraAuthForm');
166
+ const el = {
167
+ title: $('faTitle'), hint: $('faHint'), user: $('faUser'),
168
+ pass: $('faPass'), pass2: $('faPass2'), error: $('faError'), submit: $('faSubmit')
169
+ };
170
+
171
+ let mode = 'login';
172
+ let busy = false;
173
+ const showError = (msg) => { el.error.textContent = msg || ''; };
174
+
175
+ const setMode = (next, user) => {
176
+ mode = next;
177
+ showError('');
178
+ el.pass.value = '';
179
+ el.pass2.value = '';
180
+ if (next === 'setup') {
181
+ el.title.textContent = 'تعیین رمز عبور';
182
+ el.hint.textContent = `برای «${user.displayName || user.username}» یک رمز عبور حداقل ${MIN_PASSWORD_LENGTH} کاراکتری انتخاب کنید.`;
183
+ el.user.value = user.username;
184
+ el.user.readOnly = true;
185
+ el.pass.placeholder = 'رمز عبور جدید';
186
+ el.pass.autocomplete = 'new-password';
187
+ el.pass2.style.display = '';
188
+ el.submit.textContent = 'ذخیره و ورود';
189
+ el.pass.focus();
190
+ } else {
191
+ el.title.textContent = 'ورود به فینورا پرو';
192
+ el.hint.textContent = 'برای ادامه وارد شوید.';
193
+ el.user.readOnly = false;
194
+ el.pass.placeholder = 'رمز عبور';
195
+ el.pass.autocomplete = 'current-password';
196
+ el.pass2.style.display = 'none';
197
+ el.submit.textContent = 'ورود';
198
+ (el.user.value ? el.pass : el.user).focus();
199
+ }
200
+ };
201
+
202
+ const finish = (user) => {
203
+ root.remove();
204
+ if (splash) splash.style.display = splashDisplay;
205
+ this._failures = 0;
206
+ resolve(user);
207
+ };
208
+
209
+ // اگر فقط یک کاربر هست، نام کاربری پر میشود؛ اگر او رمز ندارد مستقیم به تعیین رمز میرویم
210
+ if (users.length === 1) {
211
+ el.user.value = users[0].username;
212
+ if (needsPassword(users[0])) setMode('setup', users[0]);
213
+ else setMode('login');
214
+ } else {
215
+ setMode('login');
216
+ }
217
+
218
+ form.addEventListener('submit', async (e) => {
219
+ e.preventDefault();
220
+ if (busy) return;
221
+ busy = true;
222
+ el.submit.disabled = true;
223
+ showError('');
224
+ try {
225
+ const username = el.user.value.trim();
226
+ const password = el.pass.value;
227
+ const user = users.find(u => u.username === username);
228
+
229
+ if (mode === 'setup') {
230
+ if (password.length < MIN_PASSWORD_LENGTH) {
231
+ showError(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
232
+ } else if (password !== el.pass2.value) {
233
+ showError('تکرار رمز عبور با رمز واردشده یکسان نیست');
234
+ } else if (password === LEGACY_DEFAULT_PASSWORD) {
235
+ showError('این رمز پیشفرض و ناامن است؛ رمز دیگری انتخاب کنید');
236
+ } else {
237
+ finish(await this._setPassword(user, password));
238
+ }
239
+ } else if (user && needsPassword(user)) {
240
+ setMode('setup', user);
241
+ } else if (user && await verifyPassword(password, user)) {
242
+ finish(user);
243
+ } else {
244
+ this._failures++;
245
+ await sleep(Math.min(500 * 2 ** (this._failures - 1), 15000));
246
+ showError(AUTH_ERROR);
247
+ }
248
+ } catch (err) {
249
+ showError(err && err.message ? err.message : 'خطای ناشناخته');
250
+ } finally {
251
+ busy = false;
252
+ el.submit.disabled = false;
253
+ }
254
+ });
255
+ });
256
+ }
257
+
258
+ // ---------- رابط عمومی ----------
259
+
260
_updateUI() {
261
const u = this.currentUser;
262
if (!u) return;
@@ -52,14 +272,16 @@ class AuthImpl {
272
isAdmin() { return this.currentUser?.role === 'admin'; }
273
274
async login(username, password) {
275
+ await this._migrateLegacyPasswords();
276
const users = await StorageService.getAll('users');
56
- const user = users.find(u => u.username === username && u.pass === password);
57
- if (!user) throw new Error('نام کاربری یا رمز عبور اشتباه است');
58
- this.currentUser = user;
59
- sessionStorage.setItem(this.sessionKey, JSON.stringify(user));
277
+ const user = users.find(u => u.username === username);
278
+ if (!user || needsPassword(user) || !(await verifyPassword(password, user))) {
279
+ throw new Error(AUTH_ERROR);
280
+ }
281
+ this._startSession(user);
282
this._updateUI();
61
- EventBus.emit('auth:login', user);
62
- return user;
283
+ EventBus.emit('auth:login', this.currentUser);
284
+ return this.currentUser;
285
}
286
287
logout() {
@@ -67,8 +289,37 @@ class AuthImpl {
289
this.currentUser = null;
290
sessionStorage.removeItem(this.sessionKey);
291
EventBus.emit('auth:logout');
70
- window.location.reload();
292
+ window.location.reload(); // پس از بارگذاری دوباره، صفحه قفل نمایش داده میشود
293
+ }
294
+
295
+ async changePassword(oldPassword, newPassword) {
296
+ if (!this.currentUser) throw new Error('ابتدا وارد شوید');
297
+ const user = await StorageService.get('users', this.currentUser.id);
298
+ if (!(await verifyPassword(oldPassword, user))) throw new Error('رمز عبور فعلی اشتباه است');
299
+ if (typeof newPassword !== 'string' || newPassword.length < MIN_PASSWORD_LENGTH) {
300
+ throw new Error(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
301
+ }
302
+ await this._setPassword(user, newPassword);
303
+ return true;
304
+ }
305
+
306
+ async createUser({ username, password, displayName, role = 'user' } = {}) {
307
+ if (!this.isAdmin()) throw new Error('فقط مدیر میتواند کاربر بسازد');
308
+ const name = String(username ?? '').trim();
309
+ if (!name) throw new Error('نام کاربری الزامی است');
310
+ if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) {
311
+ throw new Error(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
312
+ }
313
+ const users = await StorageService.getAll('users');
314
+ if (users.some(u => u.username === name)) throw new Error('این نام کاربری قبلاً ثبت شده است');
315
+ const created = await StorageService.put('users', {
316
+ username: name,
317
+ displayName: displayName || name,
318
+ role: role === 'admin' ? 'admin' : 'user',
319
+ ...(await hashPassword(password))
320
+ });
321
+ return this._publicUser(created);
322
}
323
}
324
74
-export const Auth = new AuthImpl();
\ No newline at end of file
325
+export const Auth = new AuthImpl();