register, login logic works

This commit is contained in:
2026-03-11 19:46:37 +01:00
parent 744dd7f42d
commit 58fc553f04
5 changed files with 177 additions and 1 deletions
+1 -1
View File
@@ -57,7 +57,7 @@ func AddNewUser(ctx context.Context, user User) (uint32, error) {
INSERT INTO users (Name, PassHash, Color)
VALUES ($1, $2, $3)
RETURNING Id
`, user.Name, user.IsPasswordHashed, user.Color).Scan(&id)
`, user.Name, user.Password, user.Color).Scan(&id)
return id, err
}
BIN
View File
Binary file not shown.
+9
View File
@@ -1,6 +1,7 @@
package main
import (
"log"
"net/http"
"golang.org/x/crypto/bcrypt"
@@ -30,6 +31,14 @@ func RegisterHandler(response http.ResponseWriter, request *http.Request) {
}
if _, err := AddNewUser(ctx, User{0, username, password, "xxx", false}); err != nil {
http.Error(response, "Internal server error", http.StatusInternalServerError)
log.Fatal(err)
return
}
response.WriteHeader(http.StatusCreated)
_, err := response.Write([]byte("registered"))
if err != nil {
http.Error(response, "Internal server error", http.StatusInternalServerError)
return
}
+151
View File
@@ -0,0 +1,151 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WS Client</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: monospace; background: #1a1a1a; color: #e0e0e0; padding: 20px; }
h2 { margin-bottom: 16px; color: #9ecfff; }
#auth-panel, #chat-panel { max-width: 600px; }
label { display: block; margin-bottom: 4px; font-size: 13px; color: #aaa; }
input[type="text"] {
width: 100%; padding: 8px; background: #2a2a2a; border: 1px solid #444;
color: #e0e0e0; font-family: monospace; font-size: 13px; border-radius: 4px;
}
button {
margin-top: 10px; padding: 8px 20px; background: #4a90d9; color: #fff;
border: none; border-radius: 4px; cursor: pointer; font-family: monospace; font-size: 13px;
}
button:hover { background: #357abd; }
button:disabled { background: #444; cursor: default; }
#status {
margin-top: 12px; font-size: 13px; padding: 6px 10px;
border-radius: 4px; background: #2a2a2a; border-left: 3px solid #555;
}
#status.ok { border-color: #4caf50; color: #81c784; }
#status.err { border-color: #f44336; color: #e57373; }
#chat-panel { display: none; margin-top: 24px; }
#log {
height: 300px; overflow-y: auto; background: #111; border: 1px solid #333;
border-radius: 4px; padding: 10px; font-size: 13px; line-height: 1.6;
}
.msg-in { color: #81c784; }
.msg-out { color: #64b5f6; }
.msg-sys { color: #888; font-style: italic; }
#send-row { display: flex; gap: 8px; margin-top: 10px; }
#send-row input { flex: 1; margin: 0; }
#send-row button { margin: 0; }
.hint { margin-top: 20px; font-size: 12px; color: #666; border-top: 1px solid #2a2a2a; padding-top: 12px; }
.hint code { background: #2a2a2a; padding: 2px 5px; border-radius: 3px; color: #ccc; }
</style>
</head>
<body>
<div id="auth-panel">
<h2>WebSocket Client</h2>
<label>JWT Token</label>
<input id="token-input" type="text" placeholder="Paste token from curl /login">
<button id="connect-btn" onclick="connect()">Connect</button>
<div id="status">Not connected</div>
<div class="hint">
Register: <code>curl -X POST localhost:8080/register -d "username=alice&password=password123"</code><br><br>
Login: <code>curl -X POST localhost:8080/login -d "username=alice&password=password123"</code>
</div>
</div>
<div id="chat-panel">
<h2>Connected as <span id="auth-name"></span></h2>
<div id="log"></div>
<div id="send-row">
<input id="msg-input" type="text" placeholder="Message..." onkeydown="if(event.key==='Enter') send()">
<button id="send-btn" onclick="send()">Send</button>
</div>
<button onclick="disconnect()" style="background:#c0392b; margin-top:10px;">Disconnect</button>
</div>
<script>
let ws = null;
function setStatus(text, cls) {
const el = document.getElementById('status');
el.textContent = text;
el.className = cls || '';
}
function log(text, cls) {
const el = document.getElementById('log');
const line = document.createElement('div');
line.className = cls || '';
line.textContent = text;
el.appendChild(line);
el.scrollTop = el.scrollHeight;
}
function connect() {
const token = document.getElementById('token-input').value.trim();
if (!token) { setStatus('Paste a token first', 'err'); return; }
document.getElementById('connect-btn').disabled = true;
setStatus('Connecting...');
ws = new WebSocket('ws://localhost:8080/ws');
ws.onopen = () => {
ws.send(JSON.stringify({ token }));
};
ws.onmessage = (e) => {
let data;
try { data = JSON.parse(e.data); } catch { log('← ' + e.data, 'msg-in'); return; }
if (data.authAs) {
document.getElementById('auth-name').textContent = data.authAs;
document.getElementById('auth-panel').style.display = 'none';
document.getElementById('chat-panel').style.display = 'block';
log('Authenticated as ' + data.authAs, 'msg-sys');
} else if (data.error) {
log('Error: ' + data.error, 'msg-sys');
} else {
log('← ' + JSON.stringify(data), 'msg-in');
}
};
ws.onerror = () => {
setStatus('Connection error', 'err');
document.getElementById('connect-btn').disabled = false;
};
ws.onclose = () => {
log('Disconnected', 'msg-sys');
document.getElementById('chat-panel').style.display = 'none';
document.getElementById('auth-panel').style.display = 'block';
document.getElementById('connect-btn').disabled = false;
setStatus('Disconnected');
ws = null;
};
}
function send() {
const input = document.getElementById('msg-input');
const text = input.value.trim();
if (!text || !ws) return;
ws.send(JSON.stringify({ message: text }));
log('→ ' + text, 'msg-out');
input.value = '';
}
function disconnect() {
if (ws) ws.close();
}
</script>
</body>
</html>
+16
View File
@@ -102,6 +102,16 @@ func sendAndCloseIfFails(conn *websocket.Conn, message map[string]any) {
}
}
func sendToAllExceptAndCloseIfFails(conn *websocket.Conn, message map[string]any) {
_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, aConn := range authenticatedConnections {
if aConn.connection != conn {
sendAndCloseIfFails(aConn.connection, message)
}
}
}
func handleUnauthenticatedMessage(ctx context.Context, conn *websocket.Conn, msg map[string]any) {
token := msg["token"].(string)
subject, err := GetSubject(token)
@@ -138,5 +148,11 @@ func handleAuthenticatedMessage(conn *websocket.Conn, msg map[string]any) {
sendAndCloseIfFails(conn, map[string]any{
"error": "no message",
})
return
}
sendToAllExceptAndCloseIfFails(conn, map[string]any{
"username": ,
"message": message,
})
}