-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4554 lines (3970 loc) · 146 KB
/
server.js
File metadata and controls
4554 lines (3970 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// server.js
import express from 'express';
import cookieParser from 'cookie-parser';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import Database from 'better-sqlite3';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import slugify from 'slugify';
import expressLayouts from 'express-ejs-layouts';
import crypto from 'crypto';
import cron from 'node-cron';
import multer from 'multer';
import 'dotenv/config';
import nodemailer from 'nodemailer';
import {
sendNewQuestionNotifications,
sendQuestionAnswered,
sendNewFeedbackNotifications,
sendMail, // valfritt för egna tester
} from "./mailer.js";
const ROOT = path.resolve(process.cwd());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const uploadDir = path.join(__dirname, 'uploads', 'questions');
fs.mkdirSync(uploadDir, { recursive: true });
const app = express();
/* --- DB-path + se till att katalogen finns --- */
const DB_PATH = process.env.DB_PATH || 'helpdesk.db';
// När DB_PATH är absolut (/app/data/helpdesk.db) -> skapa /app/data
// När det är relativt (helpdesk.db) blir dir '.' och då gör vi inget.
const dbDir = path.dirname(DB_PATH);
if (dbDir && dbDir !== '.' && !fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
/* --- Öppna databasen EFTER att katalogen finns --- */
const db = new Database(DB_PATH);
// --- Partner API endpoints + keys ---
const DEALER_APIS = [
{ source: 'nms', url: 'https://portal.nmstuning.se/api/dealers', apiKey: 'jNtCK7Z5qR8sqnxN5LpkdF5hJQqJ9m' },
{ source: 'dynex', url: 'https://portal.dynexperformance.se/api/dealers', apiKey: '04d87a25-3711-11f0-88c2-ac1f6bad7482' },
{ source: 'smt', url: 'https://portal.smtperformance.se/api/dealers', apiKey: '27766a92-cea4-11f0-8c11-ac1f6bad7482' },
];
const DEALER_SOURCES = DEALER_APIS.map(x => x.source);
const DEALER_SOURCE_SET = new Set(DEALER_SOURCES);
// Ord/fraser som triggar flagg (case-insensitive, hela ord)
const FLAG_WORDS = [
'dynex',
'nms',
'nmstuning',
'dynexperformance',
'velox',
'sedox',
'smt',
];
// Bygg regexar för matchning
const FLAG_REGEXES = FLAG_WORDS.map(w => ({
word: w,
rx: new RegExp(`\\b${w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'iu')
}));
function findFlaggedWord(text = '') {
const hit = FLAG_REGEXES.find(obj => obj.rx.test(text));
return hit ? hit.word : null;
}
// MD5 helper
function md5(s) {
return crypto.createHash('md5').update(String(s), 'utf8').digest('hex');
}
// Normalisera ett dealer-record från API:t
function normalizeDealer(rec) {
return {
dealer_id: rec.ID || '',
email: (rec.email || '').trim().toLowerCase(),
username: rec.username || '',
company: rec.company || '',
firstname: rec.firstname || '',
lastname: rec.lastname || '',
telephone: rec.telephone || null,
added: rec.added || null,
};
}
/* --- SQLite setup + bootstrap --- */
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
/* Hjälpare för migrationer – definiera EN gång */
function hasColumn(table, col) {
const cols = db.prepare(`PRAGMA table_info(${table})`).all();
return cols.some(c => c.name === col);
}
function addColumnIfMissing(table, col, ddl) {
if (!hasColumn(table, col)) {
db.prepare(`ALTER TABLE ${table} ADD COLUMN ${col} ${ddl}`).run();
}
}
// 2) Se till att topics-tabellen finns
db.prepare(`
CREATE TABLE IF NOT EXISTS topics (
id INTEGER PRIMARY KEY,
slug TEXT UNIQUE,
title TEXT NOT NULL,
body TEXT,
is_resource INTEGER NOT NULL DEFAULT 0,
is_featured INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT
)
`).run();
// 3) Lägg bara till kolumnen om den saknas (om du kör mot äldre DB)
const hasIsFeatured = db.prepare(`
SELECT 1
FROM pragma_table_info('topics')
WHERE name = 'is_featured'
`).get();
if (!hasIsFeatured) {
db.prepare(`ALTER TABLE topics ADD COLUMN is_featured INTEGER NOT NULL DEFAULT 0`).run();
}
// 4) Index
db.prepare(`CREATE INDEX IF NOT EXISTS idx_topics_is_featured ON topics(is_featured)`).run();
// --- Migrationer ---
// topics_base.views
try {
addColumnIfMissing('topics_base', 'views', 'INTEGER DEFAULT 0');
} catch (_) { /* ignore */ }
// questions.answered_role (och answered_by om den saknas i äldre DB)
try { addColumnIfMissing('questions', 'answered_role', 'TEXT'); } catch (_) {}
try { addColumnIfMissing('questions', 'answered_by', 'TEXT'); } catch (_) {}
addColumnIfMissing('feedbacks', 'updated_at', 'TEXT');
addColumnIfMissing('users', 'is_active', 'INTEGER DEFAULT 1');
try { addColumnIfMissing('topics', 'is_starred', 'INTEGER DEFAULT 0'); } catch (_) {}
try {
db.prepare(`
UPDATE questions
SET answered_role = COALESCE((
SELECT u.role
FROM users u
WHERE lower(u.email) = lower(questions.answered_by)
OR u.name = questions.answered_by
LIMIT 1
), answered_role)
WHERE is_answered = 1
`).run();
} catch (e) { /* ignore */ }
try {
db.prepare(`ALTER TABLE questions ADD COLUMN internal_comment TEXT`).run();
} catch (e) {
// kolumnen finns redan
}
function initSchemaAndSeed() {
// Bas-schema
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT DEFAULT '',
role TEXT NOT NULL DEFAULT 'user',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS categories (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
icon TEXT,
sort_order INTEGER
);
CREATE TABLE IF NOT EXISTS topics_base (
id TEXT PRIMARY KEY,
created_by INTEGER,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
answer_for_question_id INTEGER,
FOREIGN KEY(created_by) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS topics (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
excerpt TEXT,
body TEXT,
tags TEXT,
is_resource INTEGER DEFAULT 0,
download_url TEXT,
FOREIGN KEY(id) REFERENCES topics_base(id) ON DELETE CASCADE
);
CREATE VIRTUAL TABLE IF NOT EXISTS topics_fts USING fts5(
id UNINDEXED, title, excerpt, body, content=''
);
CREATE TABLE IF NOT EXISTS topic_category (
topic_id TEXT NOT NULL,
category_id TEXT NOT NULL,
PRIMARY KEY (topic_id, category_id),
FOREIGN KEY(topic_id) REFERENCES topics_base(id) ON DELETE CASCADE,
FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
title TEXT NOT NULL,
body TEXT,
status TEXT NOT NULL DEFAULT 'open',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
answered_at TEXT,
user_seen_answer_at TEXT,
admin_seen_new INTEGER DEFAULT 0,
answer_title TEXT,
answer_body TEXT,
answer_tags TEXT,
answered_by TEXT,
is_answered INTEGER DEFAULT 0,
FOREIGN KEY(user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS question_topic (
question_id INTEGER NOT NULL,
topic_id TEXT NOT NULL,
PRIMARY KEY (question_id, topic_id),
FOREIGN KEY(question_id) REFERENCES questions(id) ON DELETE CASCADE,
FOREIGN KEY(topic_id) REFERENCES topics_base(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS user_favorites (
user_id INTEGER NOT NULL,
topic_id TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_id, topic_id),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(topic_id) REFERENCES topics_base(id) ON DELETE CASCADE
);
/* Index för listningar (profil-sida) */
CREATE INDEX IF NOT EXISTS idx_user_favorites_user_created
ON user_favorites(user_id, created_at DESC);
/* Index för existenskoll/toggla */
CREATE INDEX IF NOT EXISTS idx_user_favorites_topic
ON user_favorites(topic_id);
CREATE TABLE IF NOT EXISTS user_favorites_questions (
user_id INTEGER NOT NULL,
question_id INTEGER NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_id, question_id),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(question_id) REFERENCES questions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ufq_user_created ON user_favorites_questions(user_id, created_at DESC);
CREATE TABLE IF NOT EXISTS user_favorites_questions (
user_id INTEGER NOT NULL,
question_id INTEGER NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (user_id, question_id),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(question_id) REFERENCES questions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_user_favq_user_created
ON user_favorites_questions(user_id, created_at DESC);
`);
// Extra kolumner
addColumnIfMissing('topics_base', 'answer_for_question_id', 'INTEGER');
addColumnIfMissing('topics', 'is_resource', 'INTEGER DEFAULT 0');
addColumnIfMissing('topics', 'download_url', 'TEXT');
addColumnIfMissing('topics', 'downloads', 'INTEGER DEFAULT 0');
// Backfill users.password_hash (ska inte vara NULL)
try {
db.prepare(`UPDATE users SET password_hash='' WHERE password_hash IS NULL`).run();
} catch (e) {
console.warn('[DB:migration] kunde inte backfilla password_hash:', e.message);
}
// Säkerställ tidsstämplar finns (för gamla DB:er)
addColumnIfMissing('users', 'created_at', 'TEXT');
addColumnIfMissing('users', 'updated_at', 'TEXT');
db.prepare(`UPDATE users SET created_at = COALESCE(created_at, datetime('now'))`).run();
db.prepare(`UPDATE users SET updated_at = COALESCE(updated_at, datetime('now'))`).run();
db.prepare(`
CREATE TABLE IF NOT EXISTS question_machines (
question_id INTEGER NOT NULL,
machine TEXT NOT NULL,
FOREIGN KEY(question_id) REFERENCES questions(id) ON DELETE CASCADE
)
`).run();
// Efter att du öppnat db och ev. skapat tabeller
db.prepare(`
CREATE UNIQUE INDEX IF NOT EXISTS ux_topic_category_topic
ON topic_category(topic_id)
`).run();
db.prepare(`
CREATE UNIQUE INDEX IF NOT EXISTS ux_topic_categories_topic
ON topic_categories(topic_id)
`).run();
// Rebuild FTS om tom
const ftsCountRow = db.prepare(`SELECT count(*) AS n FROM topics_fts`).get();
if (!ftsCountRow || !ftsCountRow.n) {
const rows = db.prepare(`SELECT id, title, excerpt, body FROM topics`).all();
const ins = db.prepare(`INSERT INTO topics_fts (id,title,excerpt,body) VALUES (?,?,?,?)`);
const tx = db.transaction(arr => { arr.forEach(r => ins.run(r.id, r.title||'', r.excerpt||'', r.body||'')); });
tx(rows);
if (rows.length) console.log(`[DB] Rebuilt FTS for ${rows.length} topics`);
}
// Seed admin om saknas
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@example.com';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin123';
const adminExists = db.prepare(`SELECT 1 FROM users WHERE role='admin' LIMIT 1`).get();
if (!adminExists) {
const hash = bcrypt.hashSync(ADMIN_PASSWORD, 10);
db.prepare(`
INSERT INTO users (email, password_hash, name, role)
VALUES (?,?,?, 'admin')
`).run(ADMIN_EMAIL, hash, 'Administrator');
console.log('[DB] Seeded admin:', ADMIN_EMAIL);
}
}
// Kör init (EN gång)
initSchemaAndSeed();
/* Valfri: migrations för gamla DB:er som saknar svarskolumner i questions */
const qCols = {
answer_title: 'TEXT',
answer_body: 'TEXT',
answer_tags: 'TEXT',
answered_by: 'TEXT',
answered_at: 'TEXT',
is_answered: 'INTEGER DEFAULT 0',
user_seen_answer_at: 'TEXT',
};
for (const [col, ddl] of Object.entries(qCols)) {
addColumnIfMissing('questions', col, ddl);
}
// --- Dealers schema (NMS/Dynex) ---
db.exec(`
CREATE TABLE IF NOT EXISTS dealers (
source TEXT NOT NULL, -- t.ex. 'nms' | 'dynex' | 'smt'
dealer_id TEXT NOT NULL,
email TEXT,
username TEXT,
company TEXT,
firstname TEXT,
lastname TEXT,
telephone TEXT,
added TEXT,
md5_token TEXT NOT NULL, -- md5(dealer_id + email)
created_local TEXT,
updated_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (source, dealer_id)
);
CREATE INDEX IF NOT EXISTS idx_dealers_md5 ON dealers (md5_token);
CREATE INDEX IF NOT EXISTS idx_dealers_email ON dealers (email);
CREATE INDEX IF NOT EXISTS idx_dealers_updated ON dealers (updated_at);
`);
// --- MIGRATION: moderation/flagging på frågor ---
try { addColumnIfMissing('questions', 'hidden', 'INTEGER DEFAULT 0'); } catch (_) {}
try { addColumnIfMissing('questions', 'flagged', 'INTEGER DEFAULT 0'); } catch (_) {}
try { addColumnIfMissing('questions', 'flagged_reason', 'TEXT'); } catch (_) {}
try { addColumnIfMissing('questions', 'moderated_by', 'TEXT'); } catch (_) {}
try { addColumnIfMissing('questions', 'moderated_at', 'TEXT'); } catch (_) {}
try {
// Kolla befintliga kolumner en gång
const cols = db.prepare(`PRAGMA table_info(dealers)`).all().map(c => c.name);
// Lägg till md5_token om den saknas + backfill
if (!cols.includes('md5_token')) {
db.exec(`ALTER TABLE dealers ADD COLUMN md5_token TEXT`);
const rows = db.prepare(`
SELECT source, dealer_id, IFNULL(lower(email), '') AS email
FROM dealers
`).all();
const upd = db.prepare(`UPDATE dealers SET md5_token = ? WHERE source = ? AND dealer_id = ?`);
for (const r of rows) {
const token = crypto.createHash('md5')
.update(String(r.dealer_id) + String(r.email), 'utf8')
.digest('hex');
upd.run(token, r.source, r.dealer_id);
}
}
// Lägg till created_local om den saknas + backfill (först-sedd-tid)
if (!cols.includes('created_local')) {
db.exec(`ALTER TABLE dealers ADD COLUMN created_local TEXT`);
db.prepare(`
UPDATE dealers
SET created_local = COALESCE(created_local, updated_at, datetime('now'))
`).run();
}
// (Index skapas idempotent i CREATE INDEX ovan)
} catch (e) {
}
// Körs vid appstart – lägg strax efter att db initierats
try {
db.exec(`
-- Hindra support/admin -> dealer
CREATE TRIGGER IF NOT EXISTS trg_prevent_downgrade_to_dealer
BEFORE UPDATE OF role ON users
FOR EACH ROW
WHEN NEW.role = 'dealer' AND OLD.role IN ('support','admin')
BEGIN
SELECT RAISE(ABORT, 'protected role: cannot downgrade support/admin to dealer');
END;
-- (valfritt) Hindra support/admin -> user
CREATE TRIGGER IF NOT EXISTS trg_prevent_downgrade_to_user
BEFORE UPDATE OF role ON users
FOR EACH ROW
WHEN NEW.role = 'user' AND OLD.role IN ('support','admin')
BEGIN
SELECT RAISE(ABORT, 'protected role: cannot downgrade support/admin to user');
END;
`);
console.log('✅ SQLite triggers skapade/redo');
} catch (e) {
console.error('⚠️ Kunde inte skapa SQLite-triggers:', e.message);
}
// Frågekategorier (junction)
db.exec(`
CREATE TABLE IF NOT EXISTS question_category (
question_id INTEGER NOT NULL,
category_id TEXT NOT NULL,
PRIMARY KEY (question_id, category_id)
);
CREATE INDEX IF NOT EXISTS idx_qc_cat ON question_category (category_id);
CREATE INDEX IF NOT EXISTS idx_qc_q ON question_category (question_id);
`);
// --- MIGRATION: skapa topic_categories om den saknas ---
db.exec(`
CREATE TABLE IF NOT EXISTS topic_categories (
topic_id TEXT NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (topic_id, category_id)
);
CREATE INDEX IF NOT EXISTS idx_topic_categories_cat ON topic_categories(category_id);
CREATE INDEX IF NOT EXISTS idx_topic_categories_topic ON topic_categories(topic_id);
`);
try {
db.prepare(`ALTER TABLE questions ADD COLUMN image_url TEXT`).run();
} catch (e) {
// kolumnen finns redan – ignorera
}
try {
db.prepare(`ALTER TABLE questions ADD COLUMN views INTEGER DEFAULT 0`).run();
} catch (e) {
// kolumnen finns redan – ignorera
}
try {
db.prepare(`ALTER TABLE questions ADD COLUMN answered_role TEXT`).run();
} catch (e) {
// kolumnen finns redan – ignorera
}
// --- MIGRATION: questions.linked_question_id ---
try {
// Lägg till kolumnen om den saknas
const hasLinkedCol = db.prepare(`PRAGMA table_info(questions)`)
.all()
.some(c => c.name === 'linked_question_id');
if (!hasLinkedCol) {
db.prepare(`ALTER TABLE questions ADD COLUMN linked_question_id INTEGER`).run();
}
// Index för snabbare kopplings-uppslag
db.prepare(`
CREATE INDEX IF NOT EXISTS idx_questions_linked_q
ON questions(linked_question_id)
`).run();
} catch (e) {
// ignorera (kolumn/index kan redan finnas)
}
// Skapa tabell för feedback (om den inte finns)
db.prepare(`
CREATE TABLE IF NOT EXISTS feedbacks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
category TEXT NOT NULL, -- 'wish' | 'suggestion' | 'bug'
message TEXT NOT NULL,
is_handled INTEGER DEFAULT 0, -- 0 = ny/öppen, 1 = hanterad
created_at TEXT DEFAULT (datetime('now')),
handled_at TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
)
`).run();
// ---------- EJS + Layouts ----------
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(expressLayouts);
app.set('layout', 'layout'); // => views/layout.ejs
app.set('layout extractScripts', true); // valfritt: <%- script %> block
app.set('layout extractStyles', true); // valfritt: <%- style %> block
// ---------- Middleware ----------
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/tinymce', express.static(path.join(__dirname, 'node_modules', 'tinymce')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// ---- Globala locals (EN källa för showHero + popularTags) ----
app.use((req, res, next) => {
res.locals.title = 'Tuning Helpdesk';
res.locals.user = getUser(req) || null;
// Döp vilka prefix som ska DÖLJA hero
const noHeroPrefixes = ['/admin', '/login', '/register', '/ask', '/topic', '/profile', '/explore', '/questions', '/resources'];
res.locals.showHero = !noHeroPrefixes.some(p => req.path.startsWith(p));
// Populära "chips" (taggar/kategorier) – globala
try {
const rows = db.prepare(`
SELECT title
FROM categories
ORDER BY COALESCE(sort_order, 9999), title
LIMIT 8
`).all();
res.locals.popularTags = rows.map(r => r.title);
} catch {
res.locals.popularTags = [];
}
next();
});
function requireLogin(req, res, next) {
const me = getUser(req); // du använder redan getUser(req) på andra ställen
if (!me) {
// Om ej inloggad → skicka till login
return res.redirect('/login');
}
req.user = me;
next();
}
// Upsert-statement för dealers
const upsertDealerStmt = db.prepare(`
INSERT INTO dealers (
source, dealer_id, email, username, company, firstname, lastname, telephone, added, md5_token,
created_local, updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
ON CONFLICT(source, dealer_id) DO UPDATE SET
email = excluded.email,
username = excluded.username,
company = excluded.company,
firstname = excluded.firstname,
lastname = excluded.lastname,
telephone = excluded.telephone,
added = excluded.added,
md5_token = excluded.md5_token,
created_local = COALESCE(dealers.created_local, excluded.created_local),
updated_at = datetime('now')
`);
// Hämta dealers från partner-API
async function fetchDealersFrom(source, url, apiKey) {
const res = await fetch(url, {
headers: {
'X-Tfs-siteapikey': apiKey,
'Accept': 'application/json'
}
});
if (!res.ok) throw new Error(`Dealer API (${source}) HTTP ${res.status}`);
const data = await res.json();
if (!Array.isArray(data)) throw new Error(`Dealer API (${source}) gav oväntat format`);
return data;
}
function upsertDealers(source, list) {
const tx = db.transaction(() => {
for (const rec of list) {
const rawEmail = (rec.email || '').trim();
const emailLc = rawEmail.toLowerCase();
const dealerId = rec.ID || '';
const token = md5(dealerId + rawEmail);
// Upsert i dealers
upsertDealerStmt.run(
source,
dealerId,
emailLc,
rec.username || '',
rec.company || '',
rec.firstname || '',
rec.lastname || '',
rec.telephone || null,
rec.added || null,
token
);
if (rawEmail) {
const displayName =
[rec.firstname, rec.lastname].filter(Boolean).join(' ') ||
rec.username || rec.company || rawEmail;
db.prepare(`
INSERT INTO users (email, name, role, password_hash, created_at, updated_at)
SELECT ?, ?, 'dealer', '', datetime('now'), datetime('now')
WHERE NOT EXISTS (
SELECT 1 FROM users WHERE lower(email) = lower(?)
)
`).run(rawEmail, displayName, rawEmail);
}
}
});
tx();
}
// Kör sync för båda källorna
async function syncAllDealers() {
for (const cfg of DEALER_APIS) {
const rows = await fetchDealersFrom(cfg.source, cfg.url, cfg.apiKey);
upsertDealers(cfg.source, rows);
}
}
app.use((req, res, next) => {
const u = getUser(req);
res.locals.me = u || null;
res.locals.notifCount = 0;
res.locals.adminOpenCount = 0;
res.locals.notifications = [];
try {
// ----- STAFF: admin/support -----
if (u && (u.role === 'admin' || u.role === 'support')) {
// 1) Öppna frågor
const openQCountRow = db.prepare(`
SELECT COUNT(*) AS n
FROM questions
WHERE COALESCE(status,'open') = 'open'
`).get();
const openQCount = openQCountRow?.n || 0;
const openQRows = db.prepare(`
SELECT id, title, created_at
FROM questions
WHERE COALESCE(status,'open') = 'open'
ORDER BY datetime(created_at) DESC
LIMIT 5
`).all();
// 2) Ohanterad feedback
const openFCountRow = db.prepare(`
SELECT COUNT(*) AS n
FROM feedbacks
WHERE is_handled = 0
`).get();
const openFCount = openFCountRow?.n || 0;
const openFRows = db.prepare(`
SELECT id, category, created_at
FROM feedbacks
WHERE is_handled = 0
ORDER BY datetime(created_at) DESC
LIMIT 5
`).all();
// Sätt räknare
res.locals.adminOpenCount = openQCount;
res.locals.notifCount = openQCount + openFCount;
// Bygg notislistan (feedback först)
const staffNotifications = [];
openFRows.forEach(f => {
const label =
f.category === 'bug' ? 'Problem' :
f.category === 'suggestion' ? 'Förslag' : 'Önskemål';
staffNotifications.push({
id: `f-${f.id}`,
title: `Ny feedback: ${label}`,
message: 'Ny feedback',
href: `/admin/feedback`
});
});
openQRows.forEach(q => {
staffNotifications.push({
id: `q-${q.id}`,
title: q.title || 'Ny fråga',
message: 'Ny obesvarad fråga',
href: `/questions/${q.id}`
});
});
res.locals.notifications = staffNotifications;
}
// ----- INLOGGADE ICKE-STAFF: user/dealer/kund -----
else if (u) {
// Räkna obesedda svar för användarens egna frågor
const unseenCountRow = db.prepare(`
SELECT COUNT(*) AS n
FROM questions
WHERE user_id = ?
AND (
COALESCE(status,'') = 'answered' OR COALESCE(is_answered,0) = 1
)
AND (
user_seen_answer_at IS NULL
OR datetime(user_seen_answer_at) < datetime(COALESCE(answered_at, updated_at, created_at))
)
`).get(u.id);
res.locals.notifCount = unseenCountRow?.n || 0;
const unseenRows = db.prepare(`
SELECT id, title, COALESCE(answered_at, updated_at, created_at) AS ts
FROM questions
WHERE user_id = ?
AND (
COALESCE(status,'') = 'answered' OR COALESCE(is_answered,0) = 1
)
AND (
user_seen_answer_at IS NULL
OR datetime(user_seen_answer_at) < datetime(COALESCE(answered_at, updated_at, created_at))
)
ORDER BY datetime(ts) DESC
LIMIT 10
`).all(u.id);
res.locals.notifications = unseenRows.map(row => ({
id: `q-${row.id}`,
title: row.title || 'Ditt svar är klart',
message: 'Nytt svar på din fråga',
href: `/questions/${row.id}`
}));
}
// ----- Gäst: inga notiser -----
else {
res.locals.notifCount = 0;
res.locals.adminOpenCount = 0;
res.locals.notifications = [];
}
} catch (e) {
// Felsäkert fallback
res.locals.notifCount = 0;
res.locals.adminOpenCount = 0;
res.locals.notifications = [];
// valfritt: console.error(e);
}
next();
});
// Städning av kategori-kopplingar
const cleanCategories = db.transaction(() => {
// 4a) Rensa dubbletter inom varje tabell
db.prepare(`
DELETE FROM topic_category
WHERE rowid NOT IN (SELECT MIN(rowid) FROM topic_category GROUP BY topic_id)
`).run();
db.prepare(`
DELETE FROM topic_categories
WHERE rowid NOT IN (SELECT MIN(rowid) FROM topic_categories GROUP BY topic_id)
`).run();
// 4b) Om en post finns i BÅDA tabellerna med olika kategorier:
// välj singulartabellen som "sanning".
db.prepare(`
DELETE FROM topic_categories
WHERE topic_id IN (SELECT topic_id FROM topic_category)
AND category_id <> (SELECT category_id FROM topic_category WHERE topic_id = topic_categories.topic_id)
`).run();
// 4c) Säkerställ att plural innehåller samma som singular (valfritt)
db.prepare(`
INSERT OR REPLACE INTO topic_categories(topic_id, category_id)
SELECT topic_id, category_id FROM topic_category
`).run();
});
// Kör städningen
cleanCategories();
app.use((err, req, res, next) => {
if (err.type === 'entity.too.large') {
return res.status(413).send('Din text är för stor. Försök korta ner innehållet.');
}
console.error(err);
res.status(500).send('Ett oväntat fel uppstod.');
});
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret';
// ---------- auth helpers ----------
function signUser(u) {
return jwt.sign(
{ id: u.id, email: u.email, role: u.role, name: u.name || '' },
JWT_SECRET,
{ expiresIn: '14d' }
);
}
function getUser(req) {
const t = req.cookies?.auth;
if (!t) return null;
try { return jwt.verify(t, JWT_SECRET); } catch { return null; }
}
function requireAuth(req, res, next) {
const u = getUser(req);
if (!u) return res.status(401).json({ error: 'unauthorized' });
req.user = u; next();
}
function requireAdmin(req, res, next) {
const u = getUser(req);
if (!u || u.role !== 'admin') return res.status(403).json({ error: 'forbidden' });
req.user = u; next();
}
function requireSupportOrAdmin(req, res, next) {
const me = getUser(req);
if (!me || (me.role !== 'admin' && me.role !== 'support')) {
return res.status(403).send('Åtkomst nekad');
}
req.user = me;
next();
}
function requireStaff(req, res, next) {
const u = getUser(req);
if (!u || !['admin', 'support'].includes(u.role)) {
return res.status(403).send('Forbidden');
}
req.user = u;
next();
}
// ---------- AUTH API ----------
// --- SSO md5-login ---
app.get('/sso/md5-login', async (req, res) => {
try {
const token = String(req.query.token || '').trim().toLowerCase();
const redirectTo = (req.query.redirect && String(req.query.redirect)) || '/';
if (!token) return res.status(400).send('Missing token');
// 1) Hitta dealer via md5-token
const dealer = db.prepare(`SELECT * FROM dealers WHERE md5_token = ?`).get(token);
if (!dealer) return res.status(403).send('Invalid token');
const email = dealer.email || '';
if (!email) return res.status(422).send('Dealer has no email');
// 2) Hitta/skap användare på e-post
let user = db.prepare(`SELECT id, email, role, name FROM users WHERE lower(email)=lower(?)`).get(email);
if (!user) {
const displayName =
[dealer.firstname, dealer.lastname].filter(Boolean).join(' ') ||
dealer.username || dealer.company || email;
db.prepare(`
INSERT INTO users (email, name, role, password_hash, created_at, updated_at)
VALUES (?, ?, 'user', '', datetime('now'), datetime('now'))
`).run(email, displayName);
user = db.prepare(`SELECT id, email, role, name FROM users WHERE lower(email)=lower(?)`).get(email);
}
// 3) AUTO-roll: sätt ENDAST 'dealer' om nuvarande roll är tom eller 'user'.
// Rör aldrig admin/support/dealer.
const isDealerEmail = !!db.prepare(`
SELECT 1 FROM dealers WHERE lower(email) = lower(?) LIMIT 1
`).get(user.email);
// Rör inte admin/support/dealer; konvertera bara tom/user -> dealer
if (isDealerEmail && !['admin','dealer','support'].includes(user.role)) {
db.prepare(`UPDATE users SET role='dealer', updated_at=datetime('now') WHERE id=?`).run(user.id);
user.role = 'dealer';
}
// 4) Cookie/JWT & bump updated_at
res.cookie('auth', signUser(user), {
httpOnly: true, sameSite: 'lax', secure: false, maxAge: 14 * 24 * 3600 * 1000
});
db.prepare(`UPDATE users SET updated_at = datetime('now') WHERE id=?`).run(user.id);
return res.redirect(redirectTo);
} catch (err) {
return res.status(500).send('Login failed');
}
});
// Kör: GET /admin/tools/backfill-dealer-roles
app.get('/admin/tools/backfill-dealer-roles', requireAdmin, (req, res) => {
const sql = `
UPDATE users
SET role = 'dealer',
updated_at = datetime('now')
WHERE (role IS NULL OR trim(lower(role)) IN ('', 'user'))
AND lower(email) IN (
SELECT lower(email)
FROM dealers
WHERE email IS NOT NULL
AND email <> ''
)
`;
const info = db.prepare(sql).run();
res.send(`Dealer-roller uppdaterade: ${info.changes} användare`);
});
// Tillåtna roller
const ALLOWED_ROLES = ['admin', 'user', 'dealer', 'support'];
// PUT /api/users/:id/role -> uppdatera roll för user-id
app.put('/api/users/:id/role', requireAdmin, express.json(), (req, res) => {
const uid = Number(req.params.id);
const role = String(req.body.role || '').toLowerCase();
if (!Number.isFinite(uid)) return res.status(400).json({ error: 'ogiltigt user-id' });
if (!ALLOWED_ROLES.includes(role)) return res.status(400).json({ error: 'ogiltig roll' });
const user = db.prepare(`SELECT id, email, role FROM users WHERE id=?`).get(uid);
if (!user) return res.status(404).json({ error: 'användare saknas' });
// skydda mot att avskaffa sin egen admin-rätt (valfritt men klokt)
if (req.user && req.user.id === uid && role !== 'admin') {
return res.status(400).json({ error: 'du kan inte ta bort din egen admin-roll' });
}
db.prepare(`UPDATE users SET role=?, updated_at=datetime('now') WHERE id=?`).run(role, uid);
return res.json({ ok: true, id: uid, role });
});
// PUT /api/dealers/:dealer_id/role -> acceptera email (primärt) eller dealer_id (fallback)
app.put('/api/dealers/:dealer_id/role', requireAdmin, express.json(), (req, res) => {
const dealerRef = String(req.params.dealer_id || '').trim();
const role = String(req.body.role || '').toLowerCase();
if (!ALLOWED_ROLES.includes(role)) return res.status(400).json({ error: 'ogiltig roll' });
// UI skickar email; behåll dealer_id-stöd för bakåtkompatibilitet.
let dealer = db.prepare(`
SELECT *
FROM dealers
WHERE lower(email) = lower(?)
ORDER BY datetime(updated_at) DESC
LIMIT 1
`).get(dealerRef);
if (!dealer) {
dealer = db.prepare(`
SELECT *
FROM dealers
WHERE dealer_id = ?
ORDER BY datetime(updated_at) DESC
LIMIT 1
`).get(dealerRef);
}
if (!dealer) return res.status(404).json({ error: 'dealer saknas' });
if (!dealer.email) return res.status(422).json({ error: 'dealern saknar e-post' });
let user = db.prepare(`SELECT id, email, role, name FROM users WHERE lower(email)=lower(?)`).get(dealer.email);