-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (64 loc) · 1.98 KB
/
Copy pathserver.js
File metadata and controls
81 lines (64 loc) · 1.98 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const { AccessToken } = require("livekit-server-sdk");
const { createClient } = require("@supabase/supabase-js");
const app = express();
app.use(cors());
app.use(express.json());
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY
);
const PORT = 3000;
app.get("/getToken", async (req, res) => {
try {
if (req.method === "OPTIONS") {
return res.sendStatus(200);
}
const room = req.query.room;
const username = req.query.username;
if (!room || !username) {
return res.status(400).json({ error: "room and username are required" });
}
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: "unauthorized" });
}
const sessionToken = authHeader.replace("Bearer ", "");
const { data: { user }, error: authError } = await supabase.auth.getUser(sessionToken);
if (authError || !user) {
return res.status(401).json({ error: "invalid session" });
}
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("username")
.eq("id", user.id)
.single();
if (profileError || !profile) {
return res.status(401).json({ error: "profile not found" });
}
if (profile.username !== username) {
return res.status(403).json({ error: "username mismatch" });
}
const at = new AccessToken(
process.env.LIVEKIT_API_KEY,
process.env.LIVEKIT_API_SECRET,
{ identity: username }
);
at.addGrant({
roomJoin: true,
room,
canPublish: true,
canSubscribe: true,
});
const token = await at.toJwt();
res.json({ token });
} catch (err) {
console.error(err);
res.status(500).json({ error: "failed to generate token" });
}
});
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://0.0.0:${PORT}`);
});