beta da beta da beta 0.0.01 '-'

This commit is contained in:
2025-06-11 19:52:07 -03:00
commit 86327ddad6
20 changed files with 1474 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
package config_data
import (
"bufio"
"errors"
"log"
"os"
"strings"
"github.com/gocql/gocql"
)
const (
file_path = "./"
)
func FileAuthGET() (map[string]interface{}, error) {
file, err := os.Open(file_path + "zartigo.conf")
if err != nil {
datafile := []byte("# nada por agora")
os.MkdirAll(file_path, 0755)
os.WriteFile(file_path+"zartigo.conf", datafile, 0644)
log.Fatal("o arquivo de config não existia, mas foi criado no caminho " + file_path + " o configure e rode novamente.")
}
defer file.Close()
MapDATA := make(map[string]interface{})
ScanData := bufio.NewScanner(file)
for ScanData.Scan() {
linhas := strings.TrimSpace(ScanData.Text())
partes := strings.SplitN(linhas, "=", 2)
if linhas == "" || strings.HasPrefix(linhas, "#") || len(partes) != 2 {
continue
}
key := strings.TrimSpace(partes[0])
value := strings.TrimSpace(partes[1])
if commit := strings.Index(value, "#"); commit != -1 {
value = strings.TrimSpace(value[:commit])
}
switch strings.Contains((value), ",") {
case true:
valueList := strings.Split(value, ",")
for i := range valueList {
valueList[i] = strings.TrimSpace(valueList[i])
}
MapDATA[key] = valueList
break
case false:
MapDATA[key] = value
break
}
}
return MapDATA, nil
}
func UseDB(ServerIP string, DataBaseNAME string) (*gocql.Session, error) {
cred, err := FileAuthGET()
con := gocql.NewCluster(ServerIP)
con.Keyspace = DataBaseNAME
con.Authenticator = gocql.PasswordAuthenticator{
Username: cred["user"].(string),
Password: cred["password"].(string),
}
session, err := con.CreateSession()
if err != nil {
return nil, errors.New("error ao conectar no banco de dados")
}
log.Println("conexão efetuada com sucesso")
return session, nil
}

102
back_end/func_db.go Normal file
View File

@@ -0,0 +1,102 @@
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
"github.com/go-sql-driver/mysql"
"github.com/google/uuid"
)
func sessionCookie(id int) (*http.Cookie, error) {
sessionID := uuid.New().String()
sessionInfo := map[string]interface{}{
"user_id": id,
}
err := redisCL.HSet(ctx, sessionID, sessionInfo).Err()
if err != nil {
return nil, fmt.Errorf("alguma coisa deu errado ao criar seu cookie de sessão")
}
err = redisCL.Expire(ctx, sessionID, 24*time.Hour).Err()
if err != nil {
log.Fatal(err)
}
cookie := &http.Cookie{
Name: "PlayerSession",
Value: sessionID,
Path: "/*",
HttpOnly: true,
Expires: time.Now().Add(24 * time.Hour),
}
return cookie, nil
}
func verifyTabeles(tbex []string, tb string) bool {
for _, a := range tbex {
if tb == a {
log.Println("a tabela: " + a + " existe")
return true
}
}
return false
}
func Database(DBname string, DBuser string, DBpass string, DBport int, DBhost string) error {
cfg := mysql.NewConfig()
cfg.Net = "tcp"
cfg.Addr = DBhost + ":3306"
cfg.DBName = DBname
cfg.User = DBuser
cfg.Passwd = DBpass
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return err
}
if db.Ping() != nil {
log.Fatal(db.Ping())
return fmt.Errorf("error ao fazer conexão")
}
log.Println("database conectado")
return nil
}
func CheckTables(query string) error {
log.Println("veirificando tabelas obrigatorias")
rows, err := db.Query(query)
if err != nil {
return fmt.Errorf("erro ao verificar tabelas: %v", err)
}
defer rows.Close()
var tables []string
for rows.Next() {
var t string
err = rows.Scan(&t)
if err != nil {
return err
}
tables = append(tables, t)
}
for a, _ := range table_list {
if !verifyTabeles(tables, a) {
rows, err := db.Query(table_list[a])
rows.Next()
if err != nil {
return fmt.Errorf("a tabela: %s não foi criada", a)
}
log.Printf("tabela %s foi criada.\n", a)
}
}
log.Println("verificação comcluida.")
return nil
}

28
back_end/globais.go Normal file
View File

@@ -0,0 +1,28 @@
package main
import (
"context"
"database/sql"
"github.com/go-redis/redis/v8"
)
type Table struct {
Name string
}
type resp_json struct {
Status string `json:"Status"`
Message string `json:"Message,omitempty"`
Logs map[string]string `json:"Logs,omitempty"`
}
var (
db *sql.DB
redisCL *redis.Client
ctx = context.Background()
table_list = map[string]string{
"players": "CREATE TABLE players (`id` INT NOT NULL AUTO_INCREMENT,`foto` MEDIUMTEXT NOT NULL,`player` VARCHAR(15) NOT NULL,`password` TEXT NOT NULL,`nome` VARCHAR(30) NOT NULL,`level` INT NOT NULL DEFAULT '0',`idade` INT NOT NULL DEFAULT '18',`altura` FLOAT NOT NULL DEFAULT '1.40',`vida` INT NOT NULL DEFAULT '10',`vida_maxima` INT NOT NULL DEFAULT '10',`destresa` INT NOT NULL DEFAULT '0',`inteligencia` INT NOT NULL DEFAULT '0',`força` INT NOT NULL DEFAULT '0',`constituição` INT NOT NULL DEFAULT '0',`cárisma` INT NOT NULL DEFAULT '0',`inventario` INT NOT NULL DEFAULT '10',`descrição` TEXT NOT NULL,PRIMARY KEY (`id`)) ENGINE = InnoDB;",
"roll_logs": "CREATE TABLE roll_logs (`id` INT NOT NULL AUTO_INCREMENT , `log` TEXT NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;",
}
)

37
back_end/go.mod Normal file
View File

@@ -0,0 +1,37 @@
module rpgzrox
go 1.24.3
require github.com/gocql/gocql v1.7.0
require (
github.com/go-redis/redis/v8 v8.11.5
github.com/google/uuid v1.6.0
golang.org/x/time v0.11.0
)
require (
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/go-sql-driver/mysql v1.9.2
)
require (
github.com/golang/snappy v0.0.3 // indirect
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect
github.com/labstack/echo/v4 v4.13.4
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.39.0
golang.org/x/net v0.40.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
)

75
back_end/go.sum Normal file
View File

@@ -0,0 +1,75 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932 h1:mXoPYz/Ul5HYEDvkta6I8/rnYM5gSdSV2tJ6XbZuEtY=
github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932/go.mod h1:NOuUCSz6Q9T7+igc/hlvDOUdtWKryOrtFyIVABv/p7k=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/gocql/gocql v1.7.0 h1:O+7U7/1gSN7QTEAaMEsJc1Oq2QHXvCWoF3DFK9HDHus=
github.com/gocql/gocql v1.7.0/go.mod h1:vnlvXyFZeLBF0Wy+RS8hrOdbn0UWsWtdg07XJnFxZ+4=
github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed h1:5upAirOpQc1Q53c0bnx2ufif5kANL7bfZWcc6VJWJd8=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

94
back_end/main.go Normal file
View File

@@ -0,0 +1,94 @@
package main
import (
/* libs padrão */
"fmt"
"log"
"net/http"
"time"
/* libs minha */
"rpgzrox/config_data"
/* libs externas */
"github.com/go-redis/redis/v8"
"golang.org/x/time/rate"
//"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func main() {
load_data, _ := config_data.FileAuthGET()
log.Println("load config_data")
Database(load_data["dbname"].(string), load_data["dbuser"].(string), load_data["dbpass"].(string), 3306, load_data["dbhost"].(string))
err := CheckTables("SHOW TABLES;")
if err != nil {
log.Fatal(err)
}
e := echo.New()
e.HideBanner = true
e.HidePort = true
log.Println("iniciando banco de dados cache")
redisCL = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
})
log.Println("Definindo configurações de Rate Limit")
rateLimiterStore := middleware.NewRateLimiterMemoryStoreWithConfig(
middleware.RateLimiterMemoryStoreConfig{
Rate: rate.Every(10 * time.Second),
Burst: 2,
ExpiresIn: 60 * time.Minute,
},
)
rateLimit := middleware.RateLimiterWithConfig(middleware.RateLimiterConfig{
Store: rateLimiterStore,
IdentifierExtractor: func(c echo.Context) (string, error) {
return c.RealIP(), nil
},
DenyHandler: func(c echo.Context, identifier string, err error) error {
if err := redisCL.Set(ctx, identifier, "blocked", 1*time.Hour).Err(); err != nil {
log.Printf("erro ao setar bloqueio no Redis: %v", err)
}
return c.JSON(http.StatusTooManyRequests, resp_json{
Status: "Timeout",
Message: "Uma tentativa de força bruta foi identificada, você tomou time_out",
})
},
})
timeoutMiddleware := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
blocked, err := redisCL.Exists(ctx, c.RealIP()).Result()
if err == nil && blocked == 1 {
return c.JSON(http.StatusTooManyRequests, resp_json{
Status: "Timeout",
Message: "Você ainda está em período de timeout",
})
}
return next(c)
}
}
log.Println("concluido, back_end rodando")
/* rotas */
e.GET("/", func(c echo.Context) error {
return c.JSON(http.StatusOK, resp_json{
Status: "Success",
Message: "Api esta online",
})
})
e.POST("login", login, timeoutMiddleware, rateLimit)
/* log */
e.Logger.Fatal(e.Start(fmt.Sprintf(":%s", load_data["port"])))
}

56
back_end/rotas.go Normal file
View File

@@ -0,0 +1,56 @@
package main
import (
"log"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"golang.org/x/crypto/bcrypt"
)
func login(c echo.Context) error {
player := c.FormValue("player")
password := c.FormValue("password")
if strings.TrimSpace(player) == "" || strings.TrimSpace(password) == "" {
return c.JSON(http.StatusForbidden, resp_json{
Status: "Error",
Message: "algum parametro esta faltando tente novamente",
})
}
/*passhash, err := bcrypt.GenerateFromPassword([]byte(password), 15)
if err != nil {
log.Println("Algo deu errado com a hash de senha.")
return c.JSON(http.StatusInternalServerError, resp_json{
Status: "Error",
Message: "Erro ao criar hash de senha do usuario: " + player,
})
}*/
var id int
var DBpass string
err := db.QueryRow("SELECT id, password FROM players WHERE player=? LIMIT 1", player).Scan(&id, &DBpass)
if err == nil {
if bcrypt.CompareHashAndPassword([]byte(DBpass), []byte(password)) == nil {
newCookie, err := sessionCookie(id)
if err != nil {
log.Println(err)
}
c.SetCookie(newCookie)
return c.JSON(http.StatusOK, resp_json{
Status: "Success",
Message: "Login sucesso",
})
}
}
return c.JSON(http.StatusForbidden, resp_json{
Status: "Error",
Message: "Usuario ou senha incorreto",
})
}

BIN
back_end/rpgzrox Executable file

Binary file not shown.

6
back_end/zartigo.conf Normal file
View File

@@ -0,0 +1,6 @@
# nada por agora
port = 8085
dbhost = 127.0.0.1
dbname = rpgzrox
dbuser = rpg
dbpass = cronostrigo