-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
207 lines (166 loc) · 5.9 KB
/
Copy pathserver.js
File metadata and controls
207 lines (166 loc) · 5.9 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
const express = require("express");
const path = require("path");
const fs = require("fs");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const Database = require("better-sqlite3");
const app = express();
const port = process.env.PORT || 3000;
const jwtSecret = process.env.JWT_SECRET || "nortex-debug-secret";
const dbPath = path.join(__dirname, "data", "nortex.db");
if (!fs.existsSync(path.dirname(dbPath))) {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
}
const db = new Database(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS list_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
tmdb_id INTEGER NOT NULL,
media_type TEXT NOT NULL,
title TEXT NOT NULL,
poster_path TEXT,
release_date TEXT,
first_air_date TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, tmdb_id, media_type),
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
`);
app.use(express.json());
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization || "";
const [type, token] = authHeader.split(" ");
if (type !== "Bearer" || !token) {
return res.status(401).json({ error: "Authorization required." });
}
try {
const payload = jwt.verify(token, jwtSecret);
req.userId = payload.userId;
next();
} catch (error) {
return res.status(401).json({ error: "Invalid or expired token." });
}
}
app.post("/api/auth/register", async (req, res) => {
const { email, password } = req.body || {};
if (!email || !password) {
return res.status(400).json({ error: "Email and password are required." });
}
if (password.length < 6) {
return res.status(400).json({ error: "Password must be at least 6 characters." });
}
const normalizedEmail = String(email).trim().toLowerCase();
try {
const passwordHash = await bcrypt.hash(password, 10);
const insert = db.prepare(
`INSERT INTO users (email, password_hash) VALUES (?, ?)`
);
const result = insert.run(normalizedEmail, passwordHash);
const token = jwt.sign(
{ userId: result.lastInsertRowid },
jwtSecret,
{ expiresIn: "30d" }
);
return res.json({ email: normalizedEmail, token });
} catch (error) {
if (error.code === "SQLITE_CONSTRAINT_UNIQUE") {
return res.status(409).json({ error: "That email is already registered." });
}
console.error("Register error:", error);
return res.status(500).json({ error: "Could not create account." });
}
});
app.post("/api/auth/login", async (req, res) => {
const { email, password } = req.body || {};
if (!email || !password) {
return res.status(400).json({ error: "Email and password are required." });
}
const normalizedEmail = String(email).trim().toLowerCase();
const user = db
.prepare(`SELECT id, password_hash FROM users WHERE email = ?`)
.get(normalizedEmail);
if (!user) {
return res.status(401).json({ error: "Invalid email or password." });
}
const match = await bcrypt.compare(password, user.password_hash);
if (!match) {
return res.status(401).json({ error: "Invalid email or password." });
}
const token = jwt.sign({ userId: user.id }, jwtSecret, { expiresIn: "30d" });
return res.json({ email: normalizedEmail, token });
});
app.get("/api/auth/me", authMiddleware, (req, res) => {
const user = db
.prepare(`SELECT email FROM users WHERE id = ?`)
.get(req.userId);
if (!user) {
return res.status(401).json({ error: "Not authorized." });
}
return res.json({ email: user.email });
});
app.get("/api/list", authMiddleware, (req, res) => {
const items = db
.prepare(
`SELECT tmdb_id AS id, media_type, title, poster_path, release_date, first_air_date FROM list_items WHERE user_id = ? ORDER BY created_at DESC`
)
.all(req.userId);
return res.json(items);
});
app.post("/api/list", authMiddleware, (req, res) => {
const { tmdb_id, media_type, title, poster_path, release_date, first_air_date } = req.body || {};
if (!tmdb_id || !media_type || !title) {
return res.status(400).json({ error: "Required list fields missing." });
}
try {
const insert = db.prepare(
`INSERT OR IGNORE INTO list_items (user_id, tmdb_id, media_type, title, poster_path, release_date, first_air_date) VALUES (?, ?, ?, ?, ?, ?, ?)`
);
insert.run(
req.userId,
tmdb_id,
media_type,
title,
poster_path || null,
release_date || null,
first_air_date || null
);
const item = db
.prepare(
`SELECT tmdb_id AS id, media_type, title, poster_path, release_date, first_air_date FROM list_items WHERE user_id = ? AND tmdb_id = ? AND media_type = ?`
)
.get(req.userId, tmdb_id, media_type);
return res.json(item);
} catch (error) {
console.error("List add error:", error);
return res.status(500).json({ error: "Could not save list item." });
}
});
app.delete("/api/list/:tmdbId", authMiddleware, (req, res) => {
const tmdbId = Number(req.params.tmdbId);
const media_type = String(req.query.media_type || "movie");
if (!tmdbId || !media_type) {
return res.status(400).json({ error: "Missing item identifier." });
}
db.prepare(
`DELETE FROM list_items WHERE user_id = ? AND tmdb_id = ? AND media_type = ?`
).run(req.userId, tmdbId, media_type);
return res.json({ success: true });
});
app.use((req, res, next) => {
const forbiddenPaths = ["/server.js", "/package.json", "/package-lock.json", "/yarn.lock", "/.gitignore", "/data"];
if (forbiddenPaths.some((forbidden) => req.path.startsWith(forbidden))) {
return res.status(404).end();
}
next();
});
app.use(express.static(path.join(__dirname)));
app.listen(port, () => {
console.log(`Nortex Theater server listening on port ${port}`);
});