-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
204 lines (171 loc) · 5.9 KB
/
Copy pathserver.js
File metadata and controls
204 lines (171 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
import express from "express";
import http from "http";
import { Server } from "socket.io";
import { createClient } from "redis";
import jwt from "jsonwebtoken";
import fs from "fs";
import admin from "firebase-admin";
import dotenv from "dotenv";
dotenv.config();
import { Middleware } from "./middleware.js";
const path = process.env.SERVICE_ACCOUNT_CREDS;
const serviceAccountCreds = JSON.parse(fs.readFileSync(path, "utf8"));
admin.initializeApp({
credential: admin.credential.cert(serviceAccountCreds),
});
const app = express();
const db = admin.firestore();
//app.use(middleware)
app.use(express.json());
//.createServer() takes in request listener as an argument. app - the express object which is callable - has a signature of app(req,res) so it is a request listener.
//server here is a raw node HTTP server.
const server = http.createServer(app);
const io = new Server(server);
const redisClient = createClient();
app.use(express.static("public"));
app.post("/api/auth", async (req, res) => {
const { idToken } = req.body;
const decoded = await admin.auth().verifyIdToken(idToken);
const jwtToken = jwt.sign(
{
uid: decoded.uid,
email: decoded.email,
},
process.env.JWT_SECRET,
{ expiresIn: "2h" },
);
res.json({ token: jwtToken });
});
app.use(Middleware);
app.post("/api/canvases", async (req, res) => {
try {
const { name, height, width, access } = req.body;
const userid = req.user.uid;
const canvasref = await db.collection("canvases").add({
name,
width,
height,
access,
owner: userid,
createdat: admin.firestore.FieldValue.serverTimestamp(),
});
const canvasdoc = await canvasref.get();
res.status(201).json({
id: canvasref.id,
...canvasdoc.data(),
});
} catch (error) {
console.log("POST canvases error:", error);
res.status(500).json({ error: "internal server error" });
}
});
app.get("/api/canvases", async (req, res) => {
const access = req.query.access;
const userid = req.user.uid;
const useremail = req.user.email;
let db_query = db.collection("canvases");
try {
if (access) {
// console.log(access)
if (access === "private") {
db_query = db_query
.where("access", "==", access)
.where("owner", "==", userid);
} else if (access === "shared") {
db_query = db_query.where("shareWith", "array-contains", useremail);
}
else{
db_query=db_query.where("access", "==", access)
}
} else {
db_query = db_query.where("owner", "==", userid)
}
const canvasesref = await db_query.get();
const result = canvasesref.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
res.json(result);
} catch (err) {
console.error("GET canvases error:", err);
res.status(500).json({ error: "internal server error" });
}
});
app.post("/api/:canvasId/emails", async (req, res) => {
try {
const { canvasId } = req.params;
const { email } = req.body;
const canvasRef = db.collection("canvases").doc(canvasId);
await canvasRef.update({
shareWith: admin.firestore.FieldValue.arrayUnion(email),
});
const updatedDoc = await canvasRef.get();
const updated = updatedDoc.data();
res.json({
shareWith: updated.shareWith,
});
} catch (err) {
console.error("POST email error:", err);
res.status(500).send("internal server error");
}
});
app.get("/api/:canvasId/emails", async (req, res) => {
try {
const { canvasId } = req.params;
const canvasRef = db.collection("canvases").doc(canvasId);
const doc = await canvasRef.get();
res.json({
shareWith: doc.data().shareWith,
});
} catch (err) {
console.error("GET emails error:", err);
res.status(500).send("internal server error");
}
});
redisClient.on("error", (err) => console.log("Redis couldn't connect", err));
async function connectToRedis() {
await redisClient.connect();
console.log("Redis connected!");
}
connectToRedis();
io.use(async (socket, next) => {
try {
const token = socket.handshake.auth.token;
const decoded = await admin.auth().verifyIdToken(token);
socket.user = decoded;
next();
} catch (err) {
next(new Error("Unauthorized"));
}
});
io.on("connection", async (socket) => {
console.log("A user connected");
socket.on("sendingId", async (canvasId) => {
const canvasDoc = await db.collection("canvases").doc(canvasId).get();
const canvas = canvasDoc.data();
if (canvas.access == "private") {
if (
canvas.owner !== socket.user.uid
// !canvas.shareWith.includes(socket.user.uid)
) {
console.log("Unauthorized access attempt by", socket.user.uid);
return;
}
}
socket.join(`canvas_${canvasId}`);
const cache = await redisClient.lRange(`canvas:${canvasId}`, 0, -1);
socket.emit("canvas_init", cache.map(JSON.parse));
socket.on("pixel_update_sent", (data) => {
redisClient
.rPush(`canvas:${canvasId}`, JSON.stringify(data))
.catch(() => console.error("Redis has a problem.."));
socket.to(`canvas_${canvasId}`).emit("pixel_update_message", data);
});
});
socket.on("disconnect", () => console.log("A user disconnected"));
}); // process.on("SIGINT", async () => {
// await redisClient.del("canvas:1");
// process.exit(0);
// });
//
server.listen(3000, "0.0.0.0", () => console.log("Server running"));