-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
189 lines (154 loc) · 5.23 KB
/
Copy pathserver.js
File metadata and controls
189 lines (154 loc) · 5.23 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
import express from 'express';
import sqlite3 from 'sqlite3';
import cors from 'cors';
import bcrypt from 'bcrypt';
import session from 'express-session';
import sqliteStore from 'connect-sqlite3';
const app = express();
const db = new sqlite3.Database('./swipet.db');
const SQLiteStore = sqliteStore(session);
app.use(cors({
origin: 'http://localhost:5173',
credentials: true
}));
app.use(express.json());
app.use(session({
store: new SQLiteStore({db: 'sessions.db', dir: './'}),
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60,
secure: false,
httpOnly: true
}
}));
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
full_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`);
db.run(`CREATE TABLE IF NOT EXISTS pets (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
bio TEXT,
image TEXT,
owner_id INTEGER,
FOREIGN KEY(owner_id) REFERENCES users(id)
)`);
});
app.get('/api/pets', (req, res) => {
db.all("SELECT * FROM pets", [], (err, rows) => {
if(err) return res.status(500).json(err);
res.json(rows);
});
});
app.get('/api/my-pets', (req, res) => {
if (!req.session || !req.session.user) {
return res.status(401).json({message: "Unauthorized"});
}
const userId = req.session.user.id;
const sql = "SELECT * FROM pets WHERE owner_id = ? ORDER BY id DESC";
db.all(sql, [userId], (err, rows) => {
if(err) {
console.error("Error occused while getting pets:", err.message);
return res.status(500).json({error: "Internal database error"});
}
res.json(rows);
});
});
app.delete('/api/pets/:id', (req, res) => {
if (!req.session.user) return res.status(401).send();
const petId = req.params.id;
const userId = req.session.user.id;
db.run("DELETE FROM pets WHERE id = ? AND owner_id = ?", [petId, userId], function(err) {
if (err) return res.status(500).json({message: "Internal server error", error: err.message});
if (this.changes === 0) return res.status(403).json({message: "You dont have acces to do that"});
res.json({message: "Deleted successfully"});
});
});
app.get('/api/islogged', (req, res) => {
if (req.session.user) {
res.json({
loggedIn: true,
user: req.session.user
});
} else {
res.json({ loggedIn: false });
}
});
app.post('/api/logout', (req, res) => {
req.session.destroy();
res.clearCookie('connect.sid');
res.json({ message: "Logged out!" });
});
app.post('/api/login', (req, res) => {
const { email, password } = req.body;
db.get("SELECT * FROM users WHERE email = ?", [email], async (err, user) => {
if (err) {
return res.status(500).json({ message: "Internal database error" });
}
if(!user) {
return res.status(400).json({ message: "Invalid email or password" });
}
const isMatch = await bcrypt.compare(password, user.password_hash);
if(isMatch) {
req.session.user = {
id: user.id,
fullName: user.full_name
};
res.json({
message: "Successfully logged in!",
user: req.session.user
});
} else {
res.status(401).json({ message: "Invalid email or password" });
}
});
});
app.post('/api/register', async (req, res) => {
const {fullName, email, password} = req.body;
try {
const salt = 10;
const password_hash = await bcrypt.hash(password, salt);
const sql = "INSERT INTO users(full_name, email, password_hash) VALUES (?, ?, ?)";
db.run(sql, [fullName, email, password_hash], function (err) {
if(err) {
if(err.message.includes('UNIQUE constraint failed')) {
return res.status(400).json({
message: "This email is already registered"
});
}
return res.status(500).json({
message: "Internal database error"
});
}
res.status(201).json({
message: "Account created succesfully!",
});
});
} catch (error) {
res.status(500).json({
message: "Internal server error" + error
});
}
});
app.post('/api/pets', (req, res) => {
if(!req.session || !req.session.user) {
return res.status(401).json({message: "Unauthorized user"});
}
const {name, age, bio, image} = req.body;
const ownerId = req.session.user.id;
const sql = "INSERT INTO pets (name, age, bio, image, owner_id) VALUES (?, ?, ?, ?, ?)";
db.run(sql, [name, age, bio, image, ownerId], function(err) {
if (err) {
return res.status(500).json({message: "Error while saving"});
}
res.status(201).json({message: "Pet posted succesfully", petId: this.lastID});
});
});
app.listen(3001, () => console.log('Server is running on http://localhost:3001'));