package main import ( "context" "encoding/json" "libshared" "log" "net/http" ) func accountNew(w http.ResponseWriter, r *http.Request) { var accountID int64 var err error if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var req NewAccountRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { w.WriteHeader(http.StatusBadRequest) apiresponse := libshared.NewAPIResponse("fail", "Invalid JSON request", APIResponse{}) json.NewEncoder(w).Encode(apiresponse) return } if err := validateRequest(&req); err != nil { w.WriteHeader(http.StatusBadRequest) apiresponse := libshared.NewAPIResponse("fail", err.Error(), APIResponse{}) json.NewEncoder(w).Encode(apiresponse) return } for { accountID, err = generateSecureNumber(13) if err != nil { w.WriteHeader(http.StatusInternalServerError) apiresponse := libshared.NewAPIResponse("fail", "failed to generate account ID", APIResponse{}) json.NewEncoder(w).Encode(apiresponse) return } accountExist := libshared.Pool.QueryRow(context.Background(), "SELECT FROM accounts WHERE accountid = $1", accountID) err = accountExist.Scan() if err != nil { break } } _, err = libshared.Pool.Exec( context.Background(), "INSERT INTO accounts (accountID, email, first_name, last_name, address, country_code) VALUES ($1, $2, $3, $4, $5, $6)", accountID, req.Email, req.FirstName, req.LastName, req.Address, req.CountryCode) if err != nil { w.WriteHeader(http.StatusBadRequest) apiresponse := libshared.NewAPIResponse("fail", "failed to create account", APIResponse{}) json.NewEncoder(w).Encode(apiresponse) return } salt, _ := generateSalt() hashText := hashPassword(req.Password, salt) _, err = libshared.Pool.Exec(context.Background(), "INSERT INTO identities (accountid, provider, provider_user_id, password_hash) VALUES ($1, $2, $3, $4)", accountID, "local", "root", hashText) if err != nil { log.Println("Failed to create root identity for new account:", err) w.WriteHeader(http.StatusInternalServerError) return } _, err = libshared.Pool.Exec(context.Background(), "INSERT INTO roles (accountid, rolename, description) VALUES ($1, $2, $3)", accountID, "admin", "Administrative Role with full permissions") if err != nil { log.Println("Failed to create administrative role:", err) w.WriteHeader(http.StatusInternalServerError) return } log.Println("Just Created new root account") log.Println(accountID, "local", "root", hashText) w.Header().Set("Content-Type", "application/json") apiresponse := libshared.NewAPIResponse("success", "Account created successfully", APIResponse{ Success: true, AccountID: accountID, }) json.NewEncoder(w).Encode(apiresponse) log.Println("New account created with ID:", accountID, req.Email, req.FirstName, req.LastName, req.Address, req.CountryCode) }