forked from engineerOfLies/rabbitmqphp_example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforum.html
More file actions
executable file
·331 lines (279 loc) · 14.6 KB
/
Copy pathforum.html
File metadata and controls
executable file
·331 lines (279 loc) · 14.6 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Steddit Forum </title>
</head>
<body>
<header>
<h1> Steddit Forum </h1>
<div class="actions">
<a class="link-button" href='loggedin.html'>Go back to dashboard </a>
<button class="link-button" id="logoutButton" type="button">Log out </button>
</div>
</header>
<main>
<section class="panel" aria-labelledby="threadsHeading">
<div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap;">
<h2 id="threadsHeading" style="margin:0;"> Latest Threads</h2>
<button id="refreshThreads" type="button">Refresh</button>
</div>
<div id="statusMessage" role="alert" aria-live="polite"></div>
<div id="threads" class="thread-list" aria-live="polite">
<p id="emptyState" class="hidden">No threads available. Start a discussion below</p>
</div>
</section>
<section class="panel" aria-labelledby="createThreadHeading">
<h2 id="createThreadHeading" style="margin:0;"> Start a new thread </h2>
<form id="createThreadForm" novalidate>
<label for="threadTitle">Title</label>
<input type="text" id="threadTitle" name="title" placeholder="share an update or ask a question!" required>
<label for="threadBody">Details</label>
<textarea id="threadBody" name="body" placeholder="Find more information from fellow stock traders!" required></textarea>
<button type="submit"> Post Thread </button>
</form>
</section>
</main>
<script>
(function(){
const statusMessage = document.getElementById('statusMessage');
const threadContainer = document.getElementById('threads');
const emptyState = document.getElementById('emptyState');
const refreshButton = document.getElementById('refreshThreads');
const logoutButton = document.getElementById('logoutButton');
const createThreadForm = document.getElementById("createThreadForm");
const successResponse = (res) => {
if(!res) return false;
if(res.status && typeof res.status === "string" && res.status.toLowerCase() === "success") return true;
if (typeof res.returnCode !== "undefined" && Number(res.returnCode) === 0) return true;
if (res.valid === true) return true;
if (res.ok === true) return true;
if (res.success === true) return true;
return false;
};
const readSessionData = () => {
let sessionId = sessionStorage.getItem('session_id');
let authToken = sessionStorage.getItem('auth_token');
if (!sessionId || !authToken) {
const LsSid = localStorage.getItem('session_id');
const LsToken = localStorage.getItem('auth_token');
if (LsSid && LsToken) {
sessionStorage.setItem('session_id', LsSid);
sessionStorage.setItem('auth_token', LsToken);
sessionId = LsSid;
authToken = LsToken;
}
}
if (!sessionId || !authToken) return null;
return {
session_id: sessionId,
sessionId,
sessionid: sessionId,
auth_token: authToken
};
};
const requireSessionData = () => {
const session = readSessionData();
if (!session) {
throw new Error('Missing session credentials. Please log in again.');
}
return session;
};
const redirectToLogin = (message) => {
alert(message || 'Session is no longer valid! Redirecting back to login page');
window.location.href = "index.html";
};
const TYPE_ALIASES = {
validate_session: ['validate_session'],
list_threads: ['list_threads'],
create_thread: ['create_thread']
};
const request = async(type, payload = {}, {needsSession = true} = {}) => {
const sessionData = needsSession ? requireSessionData() : (readSessionData() || {});
const candidates = TYPE_ALIASES[type] || [type];
let lastErr;
for (const t of candidates){
try {
const base = needsSession ? requireSessionData() : {};
const clean = { ...base, ...payload };
const allow = {
validate_session: ['session_id', 'auth_token'],
list_threads: ['session_id', 'auth_token'],
create_thread: ['session_id', 'auth_token', 'title', 'body']
}[type] || Object.keys(clean);
const filtered = {};
for (const k of allow){
if (clean[k] !== undefined){
filtered[k] = clean[k];
}
}
const body = JSON.stringify({ ...filtered, type: t });
console.debug('[request body] =', body);
if (t === "create_thread"){
const box =
document.getElementById('requestPreview') ||
(() => {
const el = document.createElement('div');
el.id = 'requestPreview';
document.querySelector("#createThreadForm").after(el);
return el;
})();
box.textContent = `\nTitle: ${filtered.title}\n\nBody: ${filtered.body}`;
}
const response = await fetch(`mqGateway.php`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'same-origin',
body
});
if (!response.ok){
const text = await response.text().catch(() => '');
if (response.status == 400 && /unknown request type/i.test(text)){
lastErr = new Error('Unknown request type');
continue;
}
throw new Error(`Server Error: ${response.status} ${response.statusText} ${text}`);
}
const data = await response.json().catch(() => {
console.debug('[response text] =', data);
throw new Error("Invalid JSON response from gateway");
})
return data;
}catch (e){
lastErr = e;
if(!(e.message && e.message.toLowerCase().includes('unknown request type'))){
break;
}
}
}
throw lastErr || new Error('Request failed for unknown reasons');
};
const toBool = (v) => v === true || v === 'true' || v === 1 || v === '1';
const ensureAuthentication = async () => {
try {
const session = readSessionData();
if (!session || !session.session_id || !session.auth_token){
throw new Error('Missing session credentials. Please log in again.');
}
console.log('validate_session ->', session.session_id, session.auth_token);
const res = await request('validate_session');
const ok =
!!(res && typeof res === "object" && (
successResponse(res) ||
toBool(res.session_valid) ||
toBool(res.valid) ||
toBool(res.authenticated) ||
toBool(res.ok) ||
(typeof res.status === "string" && res.status.toLowerCase() === "ok")
)
);
if(!ok){
throw new Error(res.message || "Session is no longer valid");
}
} catch (err){
console.error(err);
redirectToLogin(err.message);
return;
}
};
const renderThread = (threads = []) => {
threadContainer.innerHTML = '';
if (!threads.length){
emptyState.classList.remove('hidden');
threadContainer.appendChild(emptyState);
return;
}
emptyState.classList.add('hidden');
const fragment = document.createDocumentFragment();
threads.forEach((thread) => {
const card = document.createElement('article');
card.className = "thread-card";
const title = document.createElement("h2");
title.textContent = thread.title || 'Untitled Thread';
card.appendChild(title);
if(thread.body){
const body = document.createElement('p');
body.textContent = thread.body;
card.appendChild(body);
}
const meta = document.createElement('div');
meta.className = 'thread-meta';
const author = thread.author || thread.username || 'anonymous';
const created = thread.created_at ? new Date(thread.created_at).toLocaleString() : '';
meta.textContent = created ? `${author} • ${created}` : author;
card.appendChild(meta);
fragment.appendChild(card);
});
threadContainer.appendChild(fragment);
};
const loadThreads = async () => {
statusMessage.textContent = 'Loading threads.';
try {
const res = await request('list_threads');
const threads =
Array.isArray(res?.threads) ? res.threads :
Array.isArray(res?.data) ? res.data :
Array.isArray(res?.items) ? res.items :
null;
if (threads){
renderThread(threads);
statusMessage.textContent = '';
} else if(successResponse(res)){
renderThread([]);
statusMessage.textContent = '';
} else {
throw new Error(res.message || "Unable to load threads");
}
} catch (err){
console.log(err);
statusMessage.textContent = err.message;
renderThread([]);
}
};
const createThread = async (title, body) => {
statusMessage.textContent = "Posting thread";
try {
const res = await request('create_thread', {title, body});
if (!successResponse(res) && !(res?.ok === true || res?.success === true || res?.created === true)){
console.warn("Create returned non-standard response:", res);
}
createThreadForm.reset();
await loadThreads();
statusMessage.textContent = "Thread posted successfully!";
setTimeout(() => { statusMessage.textContent = '';}, 2500);
}catch (err){
console.error(err);
statusMessage.textContent = err.message;
}
};
const logout = async () => {
document.cookie = 'session_id=; Max-Age=0; path=/;';
document.cookie = 'auth_token=; Max-Age=0; path=/;';
sessionStorage.clear();
localStorage.clear();
window.location.href = "index.html";
};
logoutButton.addEventListener('click', logout);
refreshButton.addEventListener('click', loadThreads);
createThreadForm.addEventListener('submit', async (event) => {
event.preventDefault();
const title = document.getElementById('threadTitle').value.trim();
const body = document.getElementById('threadBody').value.trim();
if (!title || !body){
statusMessage.textContent = "Please provide a thread title and some thread details";
return;
}
await createThread(title, body);
});
window.addEventListener('DOMContentLoaded', async () => {
await ensureAuthentication();
await loadThreads();
});
})();
</script>
</body>
</html>