added register to client + fixed config bug + fixed register duplicate user bug
All checks were successful
build and deploy kleinTodo / build (push) Successful in 15s

This commit is contained in:
Darius klein 2026-01-11 21:05:37 +01:00
parent 579015cd7b
commit 716a65f019
7 changed files with 157 additions and 16 deletions

View File

@ -2,6 +2,7 @@ package config
import ( import (
"errors" "errors"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -62,15 +63,20 @@ func ReadConfig() (Config, error) {
return config, err return config, err
} }
file, err := os.ReadFile(configPath) if common.FileExists(configPath) {
if err != nil {
return config, err
}
_, err = toml.Decode(string(file), &config) file, err := os.ReadFile(configPath)
if err != nil { if err != nil {
return config, err return config, err
} }
return config, nil _, err = toml.Decode(string(file), &config)
if err != nil {
return config, err
}
return config, nil
}
slog.Error("Config file not found. User [todo config create] to create a new one.")
return config, errors.New("config file not found. User [todo config create] to create a new one")
} }

View File

@ -1,10 +1,11 @@
package config package config
import ( import (
"bytes"
"context" "context"
"fmt" "fmt"
"os"
"github.com/BurntSushi/toml"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
) )
@ -19,15 +20,17 @@ func GetConfig() *cli.Command {
// getConfigAction logic for GetConfig // getConfigAction logic for GetConfig
func getConfigAction(context context.Context, c *cli.Command) error { func getConfigAction(context context.Context, c *cli.Command) error {
_, configPath, err := GetConfigPath() configFile, err := ReadConfig()
if err != nil { if err != nil {
return err return err
} }
file, err := os.ReadFile(configPath) var buf bytes.Buffer
if err != nil { if err := toml.NewEncoder(&buf).Encode(configFile); err != nil {
return err return err
} }
fmt.Println(string(file))
tomlString := buf.String()
fmt.Println(tomlString)
return nil return nil
} }

View File

@ -51,6 +51,7 @@ func commands() []*cli.Command {
Sync(), Sync(),
Add(), Add(),
Todo(), Todo(),
Register(),
{ {
Name: "update", Name: "update",
Usage: "Update the vennexCLI to a specific version", Usage: "Update the vennexCLI to a specific version",

116
client/todo/register.go Normal file
View File

@ -0,0 +1,116 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"gitea.kleinsense.nl/DariusKlein/kleinTodo/client/todo/clientCommon/config"
"gitea.kleinsense.nl/DariusKlein/kleinTodo/client/todo/httpClient"
"gitea.kleinsense.nl/DariusKlein/kleinTodo/common"
"github.com/BurntSushi/toml"
"github.com/urfave/cli/v3"
)
// Register Command
func Register() *cli.Command {
return &cli.Command{
Name: "register",
Usage: "Register new user to kleinTodo server",
Action: registerAction,
Flags: registerFlags(),
}
}
// registerFlags Register cli flags
func registerFlags() []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: usernameFlagName,
Aliases: []string{"u"},
Required: true,
},
&cli.StringFlag{
Name: passwordFlagName,
Aliases: []string{"p"},
Required: true,
},
&cli.StringFlag{
Name: serverUrlFlagName,
Aliases: []string{"url"},
Required: true,
},
}
}
// registerAction logic for Template
func registerAction(context context.Context, c *cli.Command) error {
var username = c.String(usernameFlagName)
var password = c.String(passwordFlagName)
var serverUrl = c.String(serverUrlFlagName)
err := registerAndGetToken(serverUrl, username, password)
if err != nil {
return err
}
if (cfg.Server.Credentials.Username != username || cfg.Server.Credentials.Password != password) &&
common.AskUserBool("Do you wish to save your credentials? (WARNING: stored in plaintext)") {
cfg.Server.Credentials.Username = username
cfg.Server.Credentials.Password = password
}
if cfg.Server.Url != serverUrl && common.AskUserBool("Do you wish to save your chosen server url?") {
cfg.Server.Url = serverUrl
}
path, configPath, err := config.GetConfigPath()
if err != nil {
return err
}
if err = os.MkdirAll(path, 0770); err != nil {
return err
}
configBytes, err := toml.Marshal(cfg)
err = os.WriteFile(configPath, configBytes, 0644)
log.Println("Registered new user to kleinTodo server successfully")
return nil
}
func registerAndGetToken(url, username, password string) error {
credentials := common.Credentials{
Username: username,
Password: password,
}
payload, err := json.Marshal(credentials)
if err != nil {
return fmt.Errorf("error marshaling credentials: %w", err)
}
req, err := http.NewRequest("POST", url+"/register", bytes.NewBuffer(payload))
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.GetHttpClient("").Do(req)
if err != nil {
return fmt.Errorf("error sending request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("register failed with status %d: %s", resp.StatusCode, string(body))
}
return nil
}

View File

@ -194,7 +194,7 @@ func (s *BoltStore) ExistsByKey(bucket, key string) (bool, error) {
// Get returns nil if the key doesn't exist // Get returns nil if the key doesn't exist
valBytes := b.Get([]byte(key)) valBytes := b.Get([]byte(key))
if valBytes != nil { if valBytes != nil {
exists = string(valBytes) == key exists = true
} }
return nil return nil
}) })

13
common/files.go Normal file
View File

@ -0,0 +1,13 @@
package common
import (
"os"
)
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

View File

@ -22,7 +22,9 @@ func RegisterHandler(w http.ResponseWriter, r *http.Request) {
} }
// Check if user exists // Check if user exists
if exists, err := db.ExistsByKey(common.UserBucket, user.Username); exists || err != nil { if exists, err := db.ExistsByKey(common.UserBucket, user.Username); exists || err != nil {
log.Println(err.Error()) if err != nil {
log.Println(err.Error())
}
w.WriteHeader(http.StatusUnprocessableEntity) w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(`{"error":"user already exists"}`)) w.Write([]byte(`{"error":"user already exists"}`))
return return