-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
165 lines (140 loc) · 4.71 KB
/
server.ts
File metadata and controls
165 lines (140 loc) · 4.71 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
import express from "express";
import { createServer as createViteServer } from "vite";
import axios from "axios";
import cookieParser from "cookie-parser";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
app.use(cookieParser());
// --- GitHub OAuth Routes ---
app.get("/api/auth/github/url", (req, res) => {
const clientId = process.env.GITHUB_CLIENT_ID;
if (!clientId) {
return res.status(500).json({ error: "GITHUB_CLIENT_ID not configured" });
}
const redirectUri = `${process.env.APP_URL || 'http://localhost:3000'}/api/auth/github/callback`;
const url = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=repo,user`;
res.json({ url });
});
app.get("/api/auth/github/callback", async (req, res) => {
const { code } = req.query;
const clientId = process.env.GITHUB_CLIENT_ID;
const clientSecret = process.env.GITHUB_CLIENT_SECRET;
try {
const response = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id: clientId,
client_secret: clientSecret,
code,
},
{
headers: {
Accept: "application/json",
},
}
);
const accessToken = response.data.access_token;
if (!accessToken) {
throw new Error("Failed to get access token");
}
// Store token in a cookie (SameSite=None for iframe compatibility)
res.cookie("github_token", accessToken, {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
});
res.send(`
<html>
<body>
<script>
if (window.opener) {
window.opener.postMessage({ type: 'OAUTH_AUTH_SUCCESS', provider: 'github' }, '*');
window.close();
} else {
window.location.href = '/';
}
</script>
<p>Authentication successful. This window should close automatically.</p>
</body>
</html>
`);
} catch (error: any) {
console.error("GitHub OAuth error:", error.response?.data || error.message);
res.status(500).send("Authentication failed");
}
});
app.get("/api/auth/github/status", (req, res) => {
const token = req.cookies.github_token;
res.json({ isAuthenticated: !!token });
});
app.post("/api/auth/logout", (req, res) => {
res.clearCookie("github_token", {
httpOnly: true,
secure: true,
sameSite: "none",
});
res.json({ success: true });
});
// --- GitHub API Proxy Routes ---
app.get("/api/github/repos", async (req, res) => {
const token = req.cookies.github_token;
if (!token) return res.status(401).json({ error: "Unauthorized" });
try {
const response = await axios.get("https://api.github.com/user/repos?sort=updated&per_page=10", {
headers: {
Authorization: `token ${token}`,
Accept: "application/vnd.github.v3+json",
},
});
res.json(response.data);
} catch (error: any) {
res.status(error.response?.status || 500).json(error.response?.data || { error: "Failed to fetch repos" });
}
});
app.post("/api/github/repos", async (req, res) => {
const token = req.cookies.github_token;
if (!token) return res.status(401).json({ error: "Unauthorized" });
const { name, description, private: isPrivate } = req.body;
try {
const response = await axios.post(
"https://api.github.com/user/repos",
{ name, description, private: isPrivate },
{
headers: {
Authorization: `token ${token}`,
Accept: "application/vnd.github.v3+json",
},
}
);
res.json(response.data);
} catch (error: any) {
res.status(error.response?.status || 500).json(error.response?.data || { error: "Failed to create repo" });
}
});
// --- Vite Integration ---
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.join(__dirname, "dist")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();