From 4ccaf627b40086d837dd5533f0150bbdccf9b9c2 Mon Sep 17 00:00:00 2001 From: gitGnome Date: Thu, 26 Mar 2026 14:21:30 +0100 Subject: [PATCH] i wanted to add full cahce but i dont have time :( --- cache.go | 20 ++++++++++++++++++++ database.go | 8 ++++++++ http.go | 27 +++++++++------------------ 3 files changed, 37 insertions(+), 18 deletions(-) diff --git a/cache.go b/cache.go index 067493a..cd1bbf9 100644 --- a/cache.go +++ b/cache.go @@ -22,6 +22,26 @@ func CacheGetClientById(id uint32) (*Client, error) { return client, nil } +func CacheGetIdByName(name string) (uint32, error) { + client, err := CacheGetClientByName(name) + if err != nil { + return 0, err + } + return client.Id, nil +} + +func CacheGetClientByName(name string) (*Client, error) { + mu.RLock() + defer mu.RUnlock() + + for _, client := range CacheClients { + if client.Name == name { + return client, nil + } + } + return nil, fmt.Errorf("client %s not found", name) +} + func CacheSetClient(client *Client) { mu.Lock() defer mu.Unlock() diff --git a/database.go b/database.go index 4f7829b..c75265e 100644 --- a/database.go +++ b/database.go @@ -73,6 +73,14 @@ func DbSaveClientWithoutGroups(ctx context.Context, client *Client) error { return err } +func DbGetIdByClientName(ctx context.Context, name string) (uint32, error) { + var id uint32 + err := dbConn.QueryRow(ctx, ` + SELECT id FROM clients WHERE name = $1 + `, name).Scan(&id) + return id, err +} + func DbSetClientByName(ctx context.Context, client *Client) error { err := dbConn.QueryRow(ctx, ` SELECT name, pass_hash, color_red, color_green, color_blue, created_at FROM clients WHERE name = $1 diff --git a/http.go b/http.go index e44f503..f6d2c96 100644 --- a/http.go +++ b/http.go @@ -88,33 +88,24 @@ func HttpHandleLogin(response http.ResponseWriter, request *http.Request) { return } - var client = Client{Name: username} - if len(client.Name) < 8 { + if len(username) < 8 { http.Error(response, "no or short password", http.StatusBadRequest) return } - ctx := request.Context() + var ( + clientId uint32 + err error + ctx = request.Context() + ) - err := DbSetClientByName(ctx, &client) + clientId, err = CacheGetIdByName(username) if err != nil { - http.Error(response, "bad login", http.StatusUnauthorized) - return - } + clientId, err = DbGetIdByClientName(ctx, username) + if err != nil { - _, err = CacheGetClientById(client.Id) - if err == nil { - otherLoggedIn, err := CacheGetClientById(client.Id) - if err == nil { - otherLoggedIn.WsConn.CloseNow() } } - - token, err := TokenCreate(client.Id) - if err != nil { - http.Error(response, "internal server error", http.StatusInternalServerError) - } - response.Write([]byte(token)) } func HttpHandleGroupCreate(response http.ResponseWriter, request *http.Request) {