-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
162 lines (141 loc) · 5.37 KB
/
index.js
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const app = express();
app.use(bodyParser.json());
app.use(cors());
const PASTEBIN_API = "https://pastebin.com/api/api_post.php";
const API_DEV_KEY = process.env.PASTEBIN_API_KEY;
const SECRET_KEY = process.env.SECRET_KEY || "lifeishard"; // JWT secret key
// Initialize SQLite database
const db = new sqlite3.Database('./data.db', (err) => {
if (err) console.error(err.message);
console.log('Connected to SQLite database.');
});
// Create tables
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS chapters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
book_title TEXT,
chapter_title TEXT,
pastebin_url TEXT
)
`);
// Register route
app.post('/api/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: "Username and password are required." });
}
const hashedPassword = bcrypt.hashSync(password, 10);
db.run(`INSERT INTO users (username, password) VALUES (?, ?)`, [username, hashedPassword], function (err) {
if (err) return res.status(500).json({ error: "Username already exists." });
res.status(201).json({ message: "User registered successfully." });
});
});
// Login route
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: "Username and password are required." });
}
db.get(`SELECT * FROM users WHERE username = ?`, [username], (err, user) => {
if (err || !user || !bcrypt.compareSync(password, user.password)) {
return res.status(401).json({ error: "Invalid credentials." });
}
const token = jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn: '1h' });
res.json({ message: "Login successful.", token });
});
});
// Middleware for authentication
const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: "Access denied." });
try {
const decoded = jwt.verify(token, SECRET_KEY);
req.user = decoded;
next();
} catch {
res.status(401).json({ error: "Invalid token." });
}
};
// Save data to Pastebin and database
app.post('/api/save-to-pastebin', authenticate, async (req, res) => {
const { bookTitle, chapterTitle, content } = req.body;
if (!bookTitle || !chapterTitle || !content) {
return res.status(400).json({ error: "Book title, chapter title, and content are required." });
}
try {
const response = await axios.post(PASTEBIN_API, new URLSearchParams({
api_dev_key: API_DEV_KEY,
api_option: "paste",
api_paste_code: content,
api_paste_name: chapterTitle,
api_paste_private: "1",
api_paste_expire_date: "1M",
}));
const pastebinUrl = response.data;
db.run(`INSERT INTO chapters (book_title, chapter_title, pastebin_url) VALUES (?, ?, ?)`,
[bookTitle, chapterTitle, pastebinUrl],
function (err) {
if (err) return res.status(500).json({ error: "Failed to save data to database." });
res.json({ message: "Data saved successfully.", link: pastebinUrl });
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Failed to save chapter to Pastebin." });
}
});
// Public API to fetch chapters with pagination
app.get('/api/chapters', (req, res) => {
const limit = parseInt(req.query.limit) || 100;
const page = parseInt(req.query.page) || 1;
const offset = (page - 1) * limit;
db.all(`SELECT book_title, chapter_title, pastebin_url FROM chapters LIMIT ? OFFSET ?`, [limit, offset], (err, rows) => {
if (err) {
console.error(err);
return res.status(500).json({ error: "Failed to fetch chapters." });
}
db.get(`SELECT COUNT(*) AS total FROM chapters`, (err, result) => {
if (err) {
console.error(err);
return res.status(500).json({ error: "Failed to count chapters." });
}
res.json({ chapters: rows, total: result.total });
});
});
});
// API to search for book titles
app.get('/api/search', (req, res) => {
const searchTerm = req.query.q;
if (!searchTerm) {
return res.status(400).json({ error: "Search term is required." });
}
db.all(
`SELECT book_title, chapter_title, pastebin_url
FROM chapters
WHERE book_title LIKE ?`,
[`%${searchTerm}%`],
(err, rows) => {
if (err) {
console.error(err);
return res.status(500).json({ error: "Failed to search for books." });
}
res.json({ results: rows });
}
);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));