Change LoginHandler response to always use JSON, add token-grabber.js example for interacting with the login API.

This commit is contained in:
天クマ 2026-03-28 11:31:41 -03:00
commit bf1c71f176
3 changed files with 46 additions and 9 deletions

View file

@ -0,0 +1,23 @@
import readline from 'readline/promises';
import { stdin as input, stdout as output } from 'process';
const rl = readline.createInterface({ input, output });
const username = await rl.question('Please enter your username: ');
const password = await rl.question('Please enter your password: ');
rl.close();
const loginResponse = await fetch('http://localhost:8080/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await loginResponse.json();
if (data.success != 'true') {
console.log(`Login not successful: ${data.message}`);
process.exit(1);
}
const sessionID = data.sessionId;
console.log(`Your token is: ${sessionID}`);

View file

@ -1,5 +1,6 @@
package org.adrianvictor.livingroom.http; package org.adrianvictor.livingroom.http;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -18,12 +19,20 @@ public record HttpResponse(
public static HttpResponse text(int status, String text) { public static HttpResponse text(int status, String text) {
return new HttpResponse( return new HttpResponse(
400, status,
text.getBytes(), text.getBytes(),
Map.of() Map.of()
); );
} }
public static HttpResponse json(int status, String text) {
return new HttpResponse(
status,
text.getBytes(StandardCharsets.UTF_8),
Map.of("Content-Type", "application/json")
);
}
public static HttpResponse ok(byte[] body, String contentType) { public static HttpResponse ok(byte[] body, String contentType) {
return ok(body, contentType, new HashMap<>()); return ok(body, contentType, new HashMap<>());
} }

View file

@ -26,7 +26,8 @@ public class LoginHandler implements Handler {
Session session = AuthenticationHelper.getAuthenticatedSession(exchange); Session session = AuthenticationHelper.getAuthenticatedSession(exchange);
if (session != null) { if (session != null) {
return HttpResponse.text(400, "You're already logged in."); String jsonResponse = "{\"success\": false, \"message\": \"You're already logged in.\"}";
return HttpResponse.json(400, jsonResponse);
} }
try { try {
@ -39,7 +40,8 @@ public class LoginHandler implements Handler {
String password = (String) json.get("password"); String password = (String) json.get("password");
if (password == null || username == null) { if (password == null || username == null) {
return HttpResponse.text(400, "You must provide an username and password."); String jsonResponse = "{\"success\": false, \"message\": \"Invalid username or password.\"}";
return HttpResponse.json(400, jsonResponse);
} }
try { try {
@ -50,20 +52,23 @@ public class LoginHandler implements Handler {
"SESSIONID=" + s.getSessionId() + "; Path=/; HttpOnly; SameSite=Strict"); "SESSIONID=" + s.getSessionId() + "; Path=/; HttpOnly; SameSite=Strict");
String jsonResponse = "{\"success\": true, \"sessionId\": \"" + s.getSessionId() + "\"}"; String jsonResponse = "{\"success\": true, \"sessionId\": \"" + s.getSessionId() + "\"}";
return HttpResponse.ok(jsonResponse.getBytes(StandardCharsets.UTF_8), "application/json"); return HttpResponse.json(200, jsonResponse);
} else { } else {
return HttpResponse.text(401, "Invalid username or password"); String jsonResponse = "{\"success\": false, \"message\": \"Invalid username or password.\"}";
return HttpResponse.json(401, jsonResponse);
} }
} catch (Exception e) { } catch (Exception e) {
Logger.error("User lookup error: " + e.getMessage()); Logger.error("User lookup error: " + e.getMessage());
return HttpResponse.text(401, "Invalid username or password"); String jsonResponse = "{\"success\": false, \"message\": \"Invalid username or password.\"}";
return HttpResponse.json(401, jsonResponse);
} }
} catch (IOException e) { } catch (IOException e) {
Logger.error("Error reading request body: " + e.getMessage()); Logger.error("Error reading request body: " + e.getMessage());
return HttpResponse.text(400, "Invalid request"); String jsonResponse = "{\"success\": false, \"message\": \"Invalid request.\"}";
return HttpResponse.json(400, jsonResponse);
} catch (ParseException e) { } catch (ParseException e) {
Logger.error("Error parsing JSON: " + e.getMessage()); String jsonResponse = "{\"success\": false, \"message\": \"Invalid body JSON.\"}";
return HttpResponse.text(400, "Invalid JSON format"); return HttpResponse.json(400, jsonResponse);
} }
} }
} }