-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblog.js
More file actions
192 lines (160 loc) · 5.53 KB
/
blog.js
File metadata and controls
192 lines (160 loc) · 5.53 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
// blog.js
import { renderPost, renderBlogPage } from './render.js';
import { filterXSS } from 'xss';
import { handleAdminRequest } from './admin.js';
import { renderLoginForm, renderTemplate } from './templates.js';
import { verifyPassword } from './auth.js';
import { createJWT, verifyJWT } from './jwt.js';
import { darkMinCSS, lightMinCSS } from './styles.js';
import { marked } from 'marked';
import { parseCookies } from './utils.js';
import { escapeHtml } from './utils.js';
import { hashPassword } from './auth.js';
export default {
async fetch(request, env) {
const url = new URL(request.url);
const pathname = url.pathname;
const method = request.method;
// Serve Dark CSS
if (pathname === '/styles/dark_min.css') {
return new Response(darkMinCSS, {
headers: {
'Content-Type': 'text/css',
'Cache-Control': 'public, max-age=3600'
},
});
}
// Serve Light CSS
if (pathname === '/styles/light_min.css') {
return new Response(lightMinCSS, {
headers: {
'Content-Type': 'text/css',
'Cache-Control': 'public, max-age=3600'
},
});
}
// Add default theme route (for initial load)
if (pathname === '/styles/theme.css') {
// Default to dark theme
return new Response(darkMinCSS, {
headers: {
'Content-Type': 'text/css',
'Cache-Control': 'public, max-age=3600'
},
});
}
// Serve Login Page
if (pathname === '/login' && method === 'GET') {
return new Response(renderLoginForm(), {
headers: { 'Content-Type': 'text/html' },
});
}
// Handle Login Submission
if (pathname === '/login' && method === 'POST') {
try {
const formData = await request.formData();
const username = formData.get('username');
const password = formData.get('password');
const userRecord = await env.DB.prepare(
`SELECT * FROM users WHERE username = ?`
)
.bind(username)
.first();
if (!userRecord) {
return new Response('Invalid username or password', { status: 401 });
}
const isValidPassword = await verifyPassword(
password,
userRecord.password,
userRecord.salt
);
if (!isValidPassword) {
return new Response('Invalid username or password', { status: 401 });
}
// Ensure you're using 'id' as the key
const token = await createJWT({ id: userRecord.id }, env.JWT_SECRET);
// Determine if the connection is secure
const isSecure = request.url.startsWith('https://');
const secureAttribute = isSecure ? 'Secure; ' : '';
// Set the token in the cookie and redirect
const headers = new Headers();
// In login handler, update line 66:
headers.append('Set-Cookie', `token=${token}; HttpOnly; ${secureAttribute}Path=/`);
headers.append('Location', url.origin + '/'); // Use absolute URL for redirect
// Return a response with the redirect and cookie
return new Response(null, {
status: 303, // Use 303 for the redirect
headers: headers,
});
} catch (error) {
// Correcting this block
return new Response(`Error: ${error.message}`, { status: 500 });
}
}
// Handle Logout
if (pathname === '/logout' && method === 'GET') {
const headers = new Headers();
headers.append('Set-Cookie', `token=; HttpOnly; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`);
headers.append('Location', '/');
return new Response(null, {
status: 303,
headers: headers,
});
}
// Handle Admin Routes
if (pathname.startsWith('/admin')) {
const cookies = parseCookies(request);
const token = cookies.token;
let user = null;
if (token) {
user = await verifyJWT(token, env.JWT_SECRET);
}
//if (!token) {
// return new Response('Unauthorized', { status: 401 });
//}
//const user = await verifyJWT(token, env.JWT_SECRET);
if (!user) {
return new Response('Unauthorized', { status: 401 });
}
return await handleAdminRequest(request, env);
}
// Main Blog Route
if (pathname === '/') {
try {
// Fetch posts from the database
const postsResult = await env.DB.prepare(
`SELECT * FROM posts ORDER BY created_at DESC`
).all();
const posts = postsResult.results;
// Check if user is authenticated
const cookies = parseCookies(request);
const token = cookies.token;
let user = null;
if (token) {
user = await verifyJWT(token, env.JWT_SECRET);
}
let postsHtml = '';
if (posts && posts.length > 0) {
posts.forEach((post) => {
postsHtml += renderPost(post, user);
});
} else {
postsHtml = `<p>No posts available.</p>`;
}
// Show login/logout link based on authentication status
let authLinks = '';
if (user) {
authLinks = `<a href="/admin/add">Create New Post</a> | <a href="/logout">Logout</a>`;
} else {
authLinks = `<a href="/login">Login</a>`;
}
const html = renderBlogPage(postsHtml, authLinks);
return new Response(html, {
headers: { 'Content-Type': 'text/html' },
});
} catch (error) {
return new Response(`Error: ${error.message}`, { status: 500 });
}
}
}
};